AWS API Gateway same endpoint locked and unlocked

Viewed 27

I have an endpoint in ApiGateway of the form GET /user/{userId} and I want the endpoint to be open (i.e. without any security) and return some basic non-sensitive information about a user (e.g. nickname). But I also want that when a user is authenticated and authorized (through Cognito) to show more information about that user. Is there a way to set up this in CloudFormation?

My code so far:

 /person/{id}:
    get:
      x-amazon-apigateway-integration:
        uri:
          Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyFunctionArn.Arn}/invocations
        httpMethod: POST
        type: "AWS_PROXY"
      tags:
        - Person
      summary: Find person by identifier
      description: Returns a single person matching id parameter
      operationId: GetPersonById
      security:
        - CognitoUserPool: [ ]
        - <what_can_I_put_here_for_an_open_endpoint?>
1 Answers

This could be achieved in a couple of ways. However, IMHO, the best way to implement this is to use an Authorizer accessible from the API Gateway >> API >> Authorizers:

enter image description here

You can configure a Lambda to implement the authorization logic for you and mention the details of the same in the above section (Reference). The same "Authorizer Lambda" should be configured to address the required authorization-failure logic i.e. return some basic non-sensitive information about a user (e.g. nickname) (sic).

The created Authorizer can be attached to any of the API Gateway routes. In order to do so, navigate to the Route >> Method (GET, PUT, DELETE, etc) >> Method Request >> Authorization >> Choose the configured Authorizer. The authorizer forwards the request to the respective API, only in case of successful validation from the Authorizer, where you can serve the logic for your use case i.e. when a user is authenticated and authorized (through Cognito) to show more information about that user (sic).

Related