[英]Getting 401 Unauthorized from AWS Cognito + API Gateway when accessing from Postman or cURL
[英]AWS API Gateway 401 Unauthorized when lambda fails
我正在使用无服务器框架部署一组在 API 网关上运行的 API,使用 cognito 作为授权方。 一切似乎都正常,但我发现一个问题,当 lambda 由于某种原因(可能超时或某些未处理的异常)崩溃时,API 网关返回 401 未授权。
我添加了一些网关响应,我可以处理一些错误,但即使我收到初始错误,我也会继续在前端收到 401 Unauthorized。
这是我的 serverless.yml 文件的一部分:
getSimulationStatus:
handler: getSimulationStatus.handler
events:
- http:
path: /simulation/status
method: post
cors: true
authorizer:
arn: arn:aws:cognito-idp:us-east-1:${self:custom.settings.COGNITO_ARN}
resources:
Resources:
GatewayResponseDefault5XX:
Type: 'AWS::ApiGateway::GatewayResponse'
Properties:
ResponseParameters:
gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
gatewayresponse.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
gatewayresponse.header.Access-Control-Allow-Methods: "'*'"
ResponseType: DEFAULT_5XX
RestApiId:
Ref: 'ApiGatewayRestApi'
GatewayResponseDefault4XX:
Type: 'AWS::ApiGateway::GatewayResponse'
Properties:
ResponseParameters:
gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
gatewayresponse.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
gatewayresponse.header.Access-Control-Allow-Methods: "'*'"
ResponseType: DEFAULT_4XX
RestApiId:
Ref: 'ApiGatewayRestApi'
对于使用 Angular 的前端,我有一个捕获所有这些事件的错误拦截器。 目前强制执行 504 请求超时,我能够看到,但也出现了 401 未授权。
这是拦截器的代码:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
console.log("error captured", err);
return throwError(err.error.message);
}));
}
如果我从后端收到 401,我的想法是退出,但目前如果我的任何 lambda 失败,我会立即退出。
关于可能是什么问题的任何想法?
我有更好的解决方案。为什么在将请求发送到 api 网关之前不验证令牌是否有效?
你可以安装这个:
npm i jwt-decode
就我而言,我总是有一个功能可以返回标头,并允许我在每次调用 API 时验证 function 中的令牌。
这里有一个验证令牌的 function(如果你使用放大或类似的东西,你只需要传递 cognito 的令牌)。
import jwt_decode from "jwt-decode";
....
some code
....
tokenValidator(){
if(localStorage.getItem('access_token') == null){
//call signout cognito and go to login
}
const decoded = jwt_decode(localStorage.getItem('access_token'));
if (decoded.exp === undefined) return null;
const date = new Date(0);
date.setUTCSeconds(decoded.exp);
if(new Date() > date){
//call signout cognito and go to login
}
}
此解决方案可防止您遇到问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.