Безсерверный фреймворк - лямбда-функция с Authorizer COGNITO_USER_POOLS всегда возвращает «Несанкционированный» - PullRequest
0 голосов
/ 07 октября 2019

Я не могу понять, что не так с моей авторизацией.

У меня есть функция Hello, которая возвращает только простое статическое сообщение. Если я развертываю без установленного «Авторизатора», это работает. Я проверял на Почтальоне. Проблема начинается, когда я пытаюсь добавить Authorizer.

У меня полностью работает мой Cognito. На своем внешнем интерфейсе я могу зарегистрироваться, затем войти в систему и затем получить токен из этого сеанса входа.

Когда я захожу в Почтальон и тестирую, я всегда получаю "несанкционированный" как ответы. На Почтальоне я тестирую по методу GET, на вкладке «Заголовки» я добавил атрибут «Авторизация» и вставил по значению токен, который я имею из сеанса входа в систему. Я также проверил это в поле значения префикса «носитель», как рекомендовано в некоторых местах. Безуспешно.

enter image description here

Я пытался на прошлой неделе решить эту проблему. Пожалуйста, любая помощь будет чрезвычайно полезна.

serverless.yml

provider:
  name: aws
  runtime: nodejs10.x
  stage: dev
  region: eu-west-1
  environment: 
    MY_TABLE: ${self:custom.myStage}_${self:custom.settings.tb_items}
    MY_STAGE: ${self:custom.myStage}
    MY_DOMAIN: ${self:custom.myDomain}
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "dynamodb:GetItem"
        - "dynamodb:PutItem"
        - "dynamodb:UpdateItem"
        - "dynamodb:DeleteItem"
        - "dynamodb:Scan"
      Resource: "*"

functions:
  hello:
    handler: ${self:custom.pathFunc}/phraseOption.hello
    events:
      - http: 
          method: GET 
          path: hello
          cors: true
          integration: lambda-proxy
          authorizer:
            type: COGNITO_USER_POOLS
            authorizerId:
              Ref: ApiGatewayAuthorizer

resources:
  Resources:
    CognitoUserPool:
      Type: "AWS::Cognito::UserPool"
      DeletionPolicy: Retain
      Properties:
        MfaConfiguration: OFF
        UserPoolName: ${self:custom.myStage}_aePool
        EmailVerificationSubject: 'Your verification Code'
        EmailVerificationMessage: 'Use this code to confirm your sign up {####}'
        AutoVerifiedAttributes:
          - email
        UsernameAttributes:
          - email
        Policies:
          PasswordPolicy:
            MinimumLength: 6
            RequireLowercase: False
            RequireNumbers: False
            RequireSymbols: False
            RequireUppercase: False
    CognitoUserPoolClient:
      Type: "AWS::Cognito::UserPoolClient"
      DeletionPolicy: Retain
      Properties:
        ClientName: ${self:custom.myStage}_aePoolClient
        GenerateSecret: False
        UserPoolId:
          Ref: CognitoUserPool
    ApiGatewayAuthorizer: 
      Type: AWS::ApiGateway::Authorizer
      Properties: 
        Name: CognitoUserPool
        Type: COGNITO_USER_POOLS
        IdentitySource: method.request.header.Authorization
        RestApiId: 
          Ref: ApiGatewayRestApi
        ProviderARNs: 
          - Fn::GetAtt:
              - CognitoUserPool
              - Arn

phraseOptions.js

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Your function executed successfully!',
      input: event,
    }),
  };

  callback(null, response);
};

I can see the function was created with the correct Auth:

enter image description here

Also Authorizer create as expected (I guess)

enter image description here

Swagger

---
swagger: "2.0"
info:
  version: "2019-10-07T21:24:17Z"
  title: "XXXXXX"
host: "XXXXXX"
basePath: "/dev"
schemes:
- "https"
paths:
  /getPhrase:
    get:
      responses: {}
    options:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          headers:
            Access-Control-Allow-Origin:
              type: "string"
            Access-Control-Allow-Methods:
              type: "string"
            Access-Control-Allow-Credentials:
              type: "string"
            Access-Control-Allow-Headers:
              type: "string"
  /hello:
    get:
      responses: {}
      security:
      - CognitoUserPool: []
  /item:
    post:
      responses: {}
    options:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          headers:
            Access-Control-Allow-Origin:
              type: "string"
            Access-Control-Allow-Methods:
              type: "string"
            Access-Control-Allow-Credentials:
              type: "string"
            Access-Control-Allow-Headers:
              type: "string"
  /item/{itemId}:
    get:
      responses: {}
    put:
      responses: {}
    delete:
      responses: {}
    options:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          headers:
            Access-Control-Allow-Origin:
              type: "string"
            Access-Control-Allow-Methods:
              type: "string"
            Access-Control-Allow-Credentials:
              type: "string"
            Access-Control-Allow-Headers:
              type: "string"
  /items:
    get:
      responses: {}
    options:
      consumes:
      - "application/json"
      produces:
      - "application/json"
      responses:
        200:
          description: "200 response"
          headers:
            Access-Control-Allow-Origin:
              type: "string"
            Access-Control-Allow-Methods:
              type: "string"
            Access-Control-Allow-Credentials:
              type: "string"
            Access-Control-Allow-Headers:
              type: "string"
securityDefinitions:
  CognitoUserPool:
    type: "apiKey"
    name: "Authorization"
    in: "header"
    x-amazon-apigateway-authtype: "cognito_user_pools"

1 Ответ

0 голосов
/ 09 октября 2019

Я понял, что было не так!

На стороне сервера все в порядке. Вопрос о тестировании на Почтальоне - это Знак. Я использовал "cognitoUser.signInUserSession.accessToken.jwtToken", но должен был быть "cognitoUser.signInUserSession.idToken.jwtToken".

Теперь все работает как положено.

...