向 OPTIONS 请求添加身份验证

Add authentication to OPTIONS request

如何将 header 添加到针对 cross-domain API 的 OPTIONS 请求?

我正在处理的 API 要求在所有请求中将 JWT 令牌设置为 Authorization header。

当我尝试访问 API 时,Angular 首先执行一个 OPTIONS 请求,该请求不关心我为 "real" 像这样请求:

this._headers = new Headers({
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer my-token-here'
});

return this._http
            .post(AppConfig.apiUrl + 'auth/logout', params, {headers: this._headers})
            ...
            ...

当没有提供令牌时,API returns HTTP 状态 401 和 Angular 认为 OPTIONS 请求失败。

根据 CORS specification when a preflight request 执行的用户凭据被排除在外。

(...) using the method OPTIONS, and with the following additional constraints:

  • (...)
  • Exclude the author request headers.
  • Exclude user credentials.
  • (...)

(重点是我的)

考虑到这一点,问题似乎出在事情的 API 方面, 应该接受 OPTIONS 请求而不需要身份验证

可以使用 withCredentials 选项为 CORS 预检请求提供身份验证:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      withCredentials: true
    });
    return next.handle(request);
  }
}

另请参阅:

如果您使用的是 Cloudformation 模板,则必须将 AddDefaultAuthorizerToCorsPreflight 声明为 false,如本例所示:

MyApiGateway:
  Type: AWS::Serverless::Api
  Properties:
    StageName: !Ref Stage
    Auth:
      Authorizers:
        CognitoAuthorizer:
          UserPoolArn: !GetAtt UserPool.Arn
      DefaultAuthorizer: CognitoAuthorizer
      AddDefaultAuthorizerToCorsPreflight: false
    Cors:
      AllowMethods: "'POST,OPTIONS'"
      AllowHeaders: "'Access-Control-Allow-Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with,x-requested-for'"
      AllowOrigin: "'*'"

这将允许 OPTIONS 未经授权接受请求headers