parse authorization headers in typescript

To parse the authorization header in Typescript, you can use the nodejs built-in http module to access the headers from the incoming request object. Here's an example:

index.ts
import { IncomingMessage } from 'http';

function parseAuthorizationHeader(req: IncomingMessage): string {
  if (req.headers.authorization) {
    const authHeader = req.headers.authorization;
    // Split the header into parts
    const authHeaderParts = authHeader.split(' ');
    // Check if the header is in the correct format
    if (authHeaderParts.length === 2 && authHeaderParts[0] === 'Bearer') {
      return authHeaderParts[1];
    } else {
      throw new Error('Invalid Authorization header format!');
    }
  } else {
    throw new Error('Authorization header not found!');
  }
}
593 chars
18 lines

This function takes the IncomingMessage object as an input, which represents the request that is coming in. It checks if the 'authorization' header exists in the request headers. If it does, it splits the header into parts (separated by a space), and checks if it's in the correct format ('Bearer token'). If it is, it returns the token. Otherwise, it throws an error.

gistlibby LogSnag