如何在AWS Lambda中验证Cognito访问令牌以允许Gateway API调用?

won*_*lik 1 amazon-web-services amazon-cognito aws-lambda aws-api-gateway

我想要做的是为我的Lambda函数设置API网关,在DynamoDB中保存一些(或者我想仅为登录用户使用的其他东西).但我不明白如何验证AccessToken以及如何从中获取用户.

我在AWS论坛上发现了这篇文章,我决定尝试方法1.

Cognito用户池+ API网关+ API网关自定义授权程序+ Cognito用户池访问令牌.

所以现在我已登录用户:

var authenticationData = {
  Username : 'username', // your username here
  Password : 'password', // your password here
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);

var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
  onSuccess: function (result) {
    console.log('access token + ' + result.getAccessToken().getJwtToken());
....
Run Code Online (Sandbox Code Playgroud)

和他的accessToken.我还在API调用中设置了自定义API网关自定义授权程序.

现在我应该验证访问令牌并决定是允许还是拒绝方法调用.但我不明白该怎么做以及如何从令牌中检索用户?

Abd*_*ala 6

您不需要 API Gateway Custom Authorizer ... 只是为了对 API 端点进行身份验证 - 转到其方法请求并选择 AWS_IAM 进行授权下拉列表 .. 默认情况下选择 NONE ...

当访问令牌发送到此端点时 - 它将自动检查访问令牌角色(在与 cognito 服务通信后)并检查与角色相关的策略。

如果 IAM 策略允许调用此端点 - AWS API 将进一步执行它,否则它将以 403 错误或某些错误返回给您

您不需要编写任何代码 - 除非您要应用一些完全不同的身份验证逻辑 - 这可以通过“API Gateway Custom Authorizer”实现