简体   繁体   中英

Api Gateway Cognito Authorizer: client token works on AWS ui but not on Postman

I used the serverless framework to setup some POST apis and then wrote a crude NextJs app to try to authenticate with Cognito and then use the apis protected by the authorizer.

  1. I validated the api and it works without the authorizer. (Tested in Postman)
  2. I am printing to the console the access_token and the id_token received from cognito.
  3. The id_token passes the UI based Authorizer test on aws
  4. My requests both on the front-end app and Postman fail however despite including the Authorization header with the token (tried both tokens).
  5. I also tried to manually enable CORS on the Aws UI but still no luck.

I also looked at this article ( https://www.serverless.com/blog/cors-api-gateway-survival-guide/ ) but no luck and at this point I don't know what to do.

Part of my serverless.yml:

custom:
  allowedHeaders:
    - Accept
    - Content-Type
    - Content-Length
    - Authorization
    - X-Amz-Date
    - X-Api-Key
    - X-Amz-Security-Token
    - X-Amz-User-Agent
    - app_user_id
    - app_user_name
...
createResource:
    handler: api/${name}.handler
    description: POST /${name}
    events:
      - http:
          path: api/${name}
          method: post
          authorizer:
            type: COGNITO_USER_POOLS
            authorizerId:
              Ref: ApiGatewayCognitoAuthorizer
            scopes:
              - email
          cors:
            origin: '*'
            headers: ${self:custom.allowedHeaders}
          reqValidatorName: ${name}RequestValidator
          integration: lambda
          request:
            template:
              application/json: ${file(api/resource/mappingTemplates/${name}RequestMappingTemplate.vm)}
            passThrough: WHEN_NO_MATCH
...
ApiGatewayCognitoAuthorizer:
      Type: AWS::ApiGateway::Authorizer
      Properties:
        Name: CognitoUserPool-${self:provider.environment.VERSION}
        Type: COGNITO_USER_POOLS
        IdentitySource: method.request.header.Authorization
        RestApiId:
          Ref: ApiGatewayRestApi
        ProviderARNs:
          - ${self:custom.settings.cognitoARN-${env:ENV_NAME}}

I solved the issue after a bunch of attempts. I found this article that is very similar:stackoverflow.com/questions/46345005/… The solution that worked for me was to add 'openid' to the api's oauth scopes instead of just 'email'. Then I tried access_token as opposed to id_token on both Postman and the browser and hallelujah

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM