Options
All
  • Public
  • Public/Protected
  • All
Menu

The TokenValidator class is the object exposed by the library to perform token validation. Use the TokenValidator class if you wish to validate id or access tokens for your app.

TokenValidator can be initialized as follows:

const nodeTokenValidation = require("@azure/node-token-validation");
const tokenValidator = new nodeTokenValidation.TokenValidator();

Note that the TokenValidator may be initialized with optional configurations. When configurations are not provided, library defaults will be used. See Configuration for more details.

Once initialized, APIs for token validation are available for use.

Hierarchy

  • TokenValidator

Index

Constructors

constructor

Methods

validateToken

  • Base function for token validation.

    validateToken takes in a JWT token and options in the form of TokenValidationParameters, which must be set for the token to be validated. validateToken may be called directly, or called by other TokenValidator APIs.

    The following operations are performed on the token by the JOSE library:

    • Verifies the JWT format
    • Verifies the JWS signature
    • Validates the JWT claims set

    See documentation for more details on JOSE: https://github.com/panva/jose

    validateToken also performs the following additional operations on the token:

    • Validates additional claims for id tokens (nonce, c_hash, at_hash)

    Parameters

    TokenValidationParameters are built and defaults added if not already set.

    Usage example

    To validate a token using the validateToken API, pass in a token along with the tokenValidationParams.

    const nodeTokenValidation = require("@azure/node-token-validation");
    const tokenValidator = new nodeTokenValidation.TokenValidator();
    
    const tokenValidationParams = {
       validIssuers: ["issuer-here"],
       validAudiences: ["audience-here"]
    };
    
    tokenValidator.validateToken("token-here", tokenValidationParams).then((response) => {
       // Use token validation response
    }).catch((error) => {
       // Handle error here
    });
    

    A sample demonstrating usage can also be found here.

    Returns

    validateToken returns a TokenValidationResponse if a token is successfully validated.

    Errors

    The following configuration errors from the Node Token Validation library may be thrown when validating a token. Ensure the missing token/claims are present before validating.

    • Missing token error
    • Empty issuer error
    • Empty audience error
    • Missing nonce error
    • Invalid metadata error

    The following validation errors from the Node Token Validation library may be thrown. This indicates an invalid token.

    • Invalid nonce error
    • Invalid c_hash error
    • Invalid at_hash error

    Additional errors regarding the JWS signature or JWT claims may be thrown by the JOSE library. These errors indicate an invalid token.

    Parameters

    Returns Promise<TokenValidationResponse>

validateTokenFromRequest

  • Function to validate token from request object.

    validateTokenFromRequest extracts the token from either the request authorization header or the request body, and calls validateToken to validate the token.

    validateTokenFromRequest may be called directly or called by other TokenValidator APIs. See validateToken for details on claims validated and errors thrown.

    Parameters

    validateTokenFromRequest takes in a request in the form of {@link ExpressRequest}, with headers, and optional body and sessions. The token to be validated should be present in either the authorization header or the request body.

    It also takes in options in the form of TokenValidationParameters, which must be set for the token to be validated.

    Usage example

    The following code snippet demonstrates instantiating the TokenValidator and using validateTokenFromRequest.

    const validator = require('@azure/node-token-validation');
    
    // Instantiate TokenValidator
    const tokenValidator = new validator.TokenValidator();
    
    // Ensure token is present in request authorization header or body
    const request = {
       // Your request here
    };
    
    // Set token validation parameters
    const tokenValidationParams = {
       validIssuers: ['valid-issuer-here],
       validAudiences: ['valid-audience-here]
    };
    
    // Validate token
    tokenValidator.validateTokenFromRequest(request, tokenValidationParams).then((response) => {
       // Use token validation response
    }).catch((error) => {
       // Handle error here
    });
    

    Response

    If a token is successfully validated, validateTokenFromRequest will return a TokenValidationResponse.

    Errors

    validateTokenFromRequest may throw a Missing Token Error if a token is not found in the authorization header or request body.

    At this time, validateTokenFromRequest is only validating tokens from the authorization header with the authorization scheme of "Bearer". Tokens extracted from the authorization header that are not "Bearer" tokens will be validated separately from the Node Token Validation library in the future.

    Parameters

    Returns Promise<TokenValidationResponse>

validateTokenFromResponse

  • Function to validate tokens from msal-node token acquisition response.

    validateTokenFromResponse is able to validate both the id token and the access token returned on an MSAL acquire token response and return an array of TokenValidationResponse. validateTokenFromResponse currently only validates tokens if the tokenType on the response is 'Bearer'.

    validateTokenFromResponse calls validateToken to perform token validation. See validateToken for details on claims validated and errors thrown.

    Parameters

    validateTokenFromResponse takes in a response in the form of an AuthenticationResult. This is the response from MSAL's acquire token APIs, and can be passed into validateTokenFromResponse directly.

    It also takes in optional idTokenOptions or accessTokenOptions in the form of TokenValidationParameters. These are the parameters against which the id token or the access token from the response will be validated.

    If options are not provided, but an id token or an access token is present in the response, validation will not occur, and a message indicating that the token was not validated will be logged.

    Usage example

    See the below example for how to instantiate TokenValidator and use validateTokenFromResponse:

    const validator = require('@azure/node-token-validation');
    
    // Instantiate TokenValidator
    const tokenValidator = new validator.TokenValidator();
    
    // Additional steps are needed before this to acquire token using msal-node. Omitted for brevity. See full sample for details.
    clientApplication.acquireTokenByCode(tokenRequest, authCodeResponse).then((response) => {
    
         // Set id token options
         const idTokenOptions = {
             validIssuers: ['valid-issuer-here],
             validAudiences: ['valid-audience-here],
             // Nonce should be validated against claims received from response
             nonce: response.idTokenClaims.nonce
         };
    
         // Validate token
         tokenValidator.validateTokenFromResponse(response, idTokenOptions).then((response) => {
              // Use token validation response
         }).catch((error) => {
              // Handle token validation errors here
         });
    
    }).catch((error) => {
         // Handle token acquisition errors here
    });
    

    A sample demonstrating acquiring a token using msal-node and validating the response can be found here. More information on how to acquire tokens using msal-node can be found here.

    Returns

    validateTokenFromResponse returns an array of TokenValidationResponse, with separate responses for the id tokens and access tokens validated.

    Errors

    validateTokenFromResponse will currently throw an Invalid Authentication Scheme error if the tokenType on the response is not "Bearer". The Node Token Validation library is currently only handling bearer tokens. Other types of tokens will be validated separately from the Node Token Validation library in the future.

    Parameters

    Returns Promise<TokenValidationResponse[]>

validateTokenMiddleware

  • Middleware-style function to validate token from request.

    validateTokenMiddleware is an Express.js-style middleware function that validates a token on an Express network request. It can also optionally extract a token from the request session and add it to the authorization header before validating.

    validateTokenMiddleware calls {@link validateRequest} and validateToken to carry out token validation. See {@link validateRequest} for details on token extraction from a request header or body. See validateToken for details on claims validated and errors thrown.

    Parameters

    validateTokenMiddleware takes in options in the form of TokenValidationParameters, which must be set for the token to be validated.

    validateTokenMiddleware also takes in an optional resource string. This is the resource for which an access token should be extracted from req.sessions.protectedResources, and attached to the authorization header.

    Returns

    validateTokenMiddleware returns a TokenValidationMiddlewareResponse, and will call next() when a token is found and successfully validated.

    Usage example

    See the below example for how to instantiate TokenValidator and use validateTokenMiddleware.

    const validator = require('@azure/node-token-validation');
    
    // Instantiate TokenValidator
    const tokenValidator = new validator.TokenValidator();
    
    // Set token validation parameters
    const tokenValidationParams = {
         validIssuers: ['valid-issuer-here],
         validAudiences: ['valid-audience-here]
    };
    
    // Validate token
    app.get('/myRoute', 
         // Write function or have some other way of putting token in req.session.protectedResources
         mainController.getToken('custom', appSettings, msalClient, cryptoProvider),
         // Use validateTokenMiddleware
         tokenValidator.validateTokenMiddleware(tokenValidationParams, 'custom'), 
         (req, res) => {
             // Call function with validated access token stored in req.session.protectedResources.custom
             res.status(200);  
         });
    

    A sample demonstrating this usage can also be found here.

    Errors

    The next function may be called with a missing token error for the following reasons:

    • The resource provided is not a protectedResource in req.session. As the resource is not found, a token is unable to be found and added.
    • The resource provided is found in req.session.protectedResource, but no access token was in the resource.

    You should ensure that a token is available in req.sessions.protectedResource[YOUR-RESOURCE] before calling validateTokenMiddleware again.

    validateTokenMiddleware will also call next with any other errors that are thrown in validateRequest and validateToken.

    Parameters

    Returns TokenValidationMiddlewareResponse

    {@link (TokenValidationMiddlewareResponse:type)}

Generated using TypeDoc