简体   繁体   中英

How to use tokens (OAuth ?) with AWS API Gateway and AWS Lambda

I have setup an AWS Lambda function using this tutorial . I incorporated AWS API Gateway with my Lambda function using this other tutorial . The second tutorial gave the code below (A) for the lambda function to accept tokens. For testing purposes, I successfully used Postman and passed in "allow/deny/unauthorized" in the header to access different parts of the lambda function.

My question is how can I incorporate real tokens into API Gateway/AWS Lambda? I see in the comments (in the code block below - A) it states " // Call oauth provider, crack jwt token, etc. ". I am not sure how to do so.... I have been searching online for examples of this (because this most be a common thing people do right?) and have not been able to find a solid example of this. Any help would be greatly appreciated! Excuse my limited knowledge on this subject.

My end goal is to : 1) Have unauthenticated users from a mobile app hit the API Gateway endpoint that would then call my lambda function to validate the token. 2) If the token has been validated, another lambda function will be called to do stuff.

A

exports.handler = function(event, context) {
var token = event.authorizationToken;
// Call oauth provider, crack jwt token, etc.
// In this example, the token is treated as the status for simplicity.

switch (token) {
    case 'allow':
        context.succeed(generatePolicy('user', 'Allow', event.methodArn));
        break;
    case 'deny':
        context.succeed(generatePolicy('user', 'Deny', event.methodArn));
        break;
    case 'unauthorized':
        context.fail("Unauthorized");
        break;
    default:
        context.fail("error dawg");
}
};

var generatePolicy = function(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 = resource;
      policyDocument.Statement[0] = statementOne;
      authResponse.policyDocument = policyDocument;
  }
  return authResponse;

}

Examples:

  1. Example using a self-encoded access token
    Introducing custom authorizers in Amazon API Gateway ( AWS Compute Blog )

  2. Example using an unrealistic access token
    Enable Amazon API Gateway Custom Authorization ( AWS Documentation )

  3. Example using an external authorization server
    Amazon API Gateway Custom Authorizer + OAuth ( Authlete )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM