AWS API Gateway Custom Authorization with Lambda

You can define and use your own custom authorization model on API Gateway with Lambda. Each method is able to use different authorization models.
This post includes AWS API Gateway, Lambda and JWT

First of all we need to create a Lambda function to do Auth process and validate JWT and then we’ll use it on API Gateway.

npm install jsonwebtoken

fj_authorization

var AWS = require('aws-sdk');
var jwt = require('jsonwebtoken');

function generatePolicyDocument(principalId, effect, resource) {
    var authResponse = {};
    authResponse.principalId = principalId;
    if (effect && resource) {
        var policyDocument = {};
        policyDocument.Version = '2012-10-17'; // default version
        policyDocument.Statement = [];
        var statementOne = {};
        statementOne.Action = 'execute-api:Invoke'; // default action
        statementOne.Effect = effect;
        statementOne.Resource = "arn:aws:execute-api:eu-west-1:812827172:ujasuas8d/prod/*"; // You can customize like arn:aws:execute-api:eu-west-1:812827172:ujasuas8d/prod/read/*
        policyDocument.Statement[0] = statementOne;
        authResponse.policyDocument = policyDocument;

        console.log('authResponse ', JSON.stringify(authResponse,null,''));
    }
    return authResponse;
}


exports.handler = function jwtHandler(event, context){
    var token = event.authorizationToken.split(' ');
    if(token[0] === 'Bearer'){  // sample Authorization header, Authorization: Bearer Uaia0sLKAA09sKdmna0saiasoayas9281GHan
        // Token-based re-authorization
        // Verify

        try {
            var verifiedJwt = jwt.verify(token[1], "YOUR_HASH_KEY")
            context.succeed(generatePolicyDocument(verifiedJwt.id, 'Allow', event.methodArn)); // giving permission to id in JWT on API
        } catch (ex) {
            console.log(ex, ex.stack);
            context.fail("Unauthorized");
        }

    } else {
        // Require a "Bearer" token
        console.log('Wrong token type', token[0]);
        context.fail('Unauthorized');
    }
};

Now we need to define Custom Authorization on API Gateway.

apigateway_lambda_custom_authorization_1
apigateway_lambda_custom_authorization_2

  1. Lambda function name
  2. Authorization token source.

apigateway_lambda_custom_authorization_3 apigateway_lambda_custom_authorization_4

 

apigateway_lambda_custom_authorization_5

Now every request calling this method firstly authorizated by fj_authorization function if JWT token is valid.

Leave a Reply

Your email address will not be published.