Alex Lungu
Alex Lungu

Reputation: 1114

AWS API Gateway: Add header if response is Unauthorized

I setup an API Gateway in AWS that uses custom authorizers to implement an OAuth2 flow. It works fine. When the user is not authorized they get a 401 Authorized response. That is correct as well, but I would like to add a header that gives the client the endpoint where it can get the token. Something like AuthorizeUrl: url

How can I add this header to my response?

Upvotes: 3

Views: 1708

Answers (3)

amsh
amsh

Reputation: 3377

AWS added this functionality last year. Refer to this

To do it manually:

  1. Go to 'Response Headers' in API Gateway Console.
  2. Choose Unauthorized (401)
  3. Below 'Response Headers' add AuthorizeUrl and url
  4. Save and deploy API to some stage.

To add this to Cloudformation, refer to this similar answer.

You can also add this to swagger, by adding this snippet(yaml):

x-amazon-apigateway-gateway-responses:
  UNAUTHORIZED:
    statusCode: 401
    responseParameters:
      gatewayresponse.header.AuthorizeUrl:"url"
    responseTemplates:
      application/json: "{\"message\":$context.error.messageString}"

Upvotes: 1

jackko
jackko

Reputation: 7344

Unfortunately this isn't possible but it's on our backlog. I know it doesn't really make sense when the client gets a 401 but you can't tell them how to authorize.

I don't have an ETA to provide but I'll add a +1 to the feature request.

Upvotes: 1

Dave Maple
Dave Maple

Reputation: 8412

In the API Gateway console go to the "Method Response" interface. You can add HTTP Status 401. In "Response Headers" add your custom "AuthorizeUrl" header. Then in the "Integration Response" interface you can add the value you'd like for that header.

Upvotes: -1

Related Questions