Protect your API on Node(Express)

Extract the Bearer Token from the request headerarrow-up-right

An authorized request should contain an Authorization header with Bearer <access_token> as its content. Extract the Authorization Token from the request header:

// auth_middleware.ts

import { IncomingHttpHeaders } from 'http';

const extractBearerTokenFromHeaders = ({ authorization }: IncomingHttpHeaders) => {
 if (!authorization) {
   throw new Error({ code: 'auth.authorization_header_missing', status: 401 });
 }

 if (!authorization.startsWith('Bearer')) {
   throw new Error({ code: 'auth.authorization_token_type_not_supported', status: 401 });
 }

 return authorization.slice(bearerTokenIdentifier.length + 1);
};

Token validationarrow-up-right

For demonstration, we use the jose package to validate the token's signature, expiration status, and required claims.

Install jose as your dependencyarrow-up-right

Retrieve Auth’s OIDC configurationsarrow-up-right

You will need a JWK public key set and the token issuer to verify the signature and source of the received JWS token. All the public Auth Authorization Configurations can be found at https://your-auth-domain/.well-known/openid-configuration.

e.g. Call https://nightly-accounts-api.complyment.com/.well-known/openid-configuration. And locate the following two fields in the response body:

Add auth middlewarearrow-up-right

Jose's jwtVerify method may help you to verify the token's JWS format, token signature, issuer, audience and the expiration status. An exception will be thrown if validation fails.

Apply middleware to your APIarrow-up-right

Last updated