我们使用的 API 网关端点应通过特定受众的权限进行限制。
其想法是使用 lambda 授权程序从外部服务获取权限,然后创建策略以允许或拒绝对端点的访问。
为了将权限与 API 端点相匹配,端点需要向授权者提供所需的权限。
我现在的问题是如何使用端点数据自己所需的权限来丰富端点数据,并在授权者 lambda 中使用它们(可能通过事件)以进行进一步验证。
示例:
这是我的 lambda 代码:
import {Callback, Context} from 'aws-lambda';
import {Authorizer} from './authorizer';
export class App {
constructor(private authorizer: Authorizer = new Authorizer()) {
}
public handleEvent(event, callback: Callback): Promise<void> {
return this.authorizer.checkAuthorization(event, callback)
.then((policy) => callback(null, policy))
.catch((error) => callback(error, null));
}
}
const app: App = new App();
module.exports.lambda_handler = async (event) => {
return await app.handleEvent(event);
};
checkAuthorization方法的代码:
export class Authorizer {
public resourceAuthorizer: ResourceAuthorizer = new ResourceAuthorizer();
public authenticationChecker: AuthenticationChecker = new AuthenticationChecker();
public checkAuthorization(event, callback): Promise<object> {
const endpointPermissions = event.endpointPermissions; // <== this is what I need, a custom field in the event which
// is provided from the api endpoint in some way
// in my example this whould contain a string or json
// with 'View:Pets' and 'View:Somethingelse'
return this.authenticationChecker.check(event)
.then((decodedJwt) => {
const principalId: string = decodedJwt.payload.sub;
return Promise.resolve(decodedJwt)
.then((jwt) => this.resourceAuthorizer.check(jwt, event.endpointPermissions))
.then((payload) => callback(null,
getAuthorizationPolicy(principalId, 'Allow', event.endpointPermissions, payload)))
.catch((payload) => callback(null,
getAuthorizationPolicy(principalId, 'Deny', event.endpointPermissions, payload)));
}).catch((error) => {
console.log(error);
callback('Unauthorized');
});
}
}
event.endpointPermissions基本上就是我正在寻找的。根据 API 端点,应填充该端点所需的权限。然后,resourceAuthorizer 从外部服务获取用户权限,并将其与端点权限进行比较,然后创建允许或拒绝策略。
那么我可以在哪里输入 API 端点中的端点权限以将它们提供给授权者?
传递给Authorizer的事件包含一个methodArn,其格式为:
arn:aws:execute-api:<Region id>:<Account id>:<API id>/<Stage>/<Method>/<Resource path>
这将为您提供所需的方法和资源路径。它还将为您提供 API 的标识符,但不是 API 本身的名称。
API id,可用于通过使用 AWS 开发工具包获取 API 名称。请参阅此处。
这应该为您提供构建端点权限值所需的一切。
经过对这个话题的苦苦研究,我认为目前没有办法。我什至尝试使用请求模板向标头添加自定义值。但请求模板似乎只能在授权者之后调用。 所以我仍然找不到最好的方法。我正在考虑为每个 lambda 函数设置环境。这种方式的局限性是我们只能在 Lambda 函数上设置环境,而不能在每个 http 事件上设置环境。 @StV 上面提到的方式也不是一个坏主意。但这有点不方便,因为我们必须向客户端站点上的所有请求添加查询字符串