【发布时间】:2016-05-29 12:48:00
【问题描述】:
我正在使用 API Gateway 的一项新功能和 Lambda 函数来使用 自定义授权者 (https://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html)。
授权方使用 JWT 令牌 来验证当前用户上下文和范围的令牌。一切正常,但有一个关于 AWS 策略的概念,我无法从文档中完全弄清楚。
Custom Authorizer 函数的输出必须是一个包含两个东西的对象:
-
principalId- 有问题 -
policyDocument- 有效的策略文档,其中包含允许用户授权访问 Lambda 资源、阶段等的声明。
现在,自定义授权者的示例当前显示了 principalId 变量的几乎任意值。但是,如果我的想法正确的话,这个principalId 对于每个用户来说应该是唯一的吗?并且可能具有与之关联的用户特定的唯一值(例如token.userId 或token.email)。
如果这是真的,那么对于我在下面提供的代码,如果 JWT 令牌 not 有效,那么我无权访问 userId 或 email,并且没有任何线索将principalId 设置为什么。我暂时将其设置为user,只是为了让拒绝策略返回一些东西,以确保响应是403 Forbidden。
谁知道为自定义授权者设置principalId的最佳实践?
var jwt = require('jsonwebtoken');
var JWT_SECRET = 'My$ecret!';
/**
* Implicit AWS API Gateway Custom Authorizer. Validates the JWT token passed
* into the Authorization header for all requests.
* @param {Object} event [description]
* @param {Object} context [description]
* @return {Object} [description]
*/
exports.handler = function(event, context) {
var token = event.authorizationToken;
try {
var decoded = jwt.verify(token, JWT_SECRET);
context.done(null, generatePolicy(decoded.id, 'Allow', 'arn:aws:execute-api:*:*:*'));
} catch(ex) {
console.error(ex.name + ": " + ex.message);
context.done(null, generatePolicy('user', 'Deny', 'arn:aws:execute-api:*:*:*'));
}
};
function generatePolicy(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;
}
【问题讨论】:
标签: amazon-web-services jwt aws-lambda aws-api-gateway