Manthan Sharma
Manthan Sharma

Reputation: 11

AWS Cognito Authentication Working on Postman but not on Angular web app

I configured Authentication for all the APIs which are deployed on the server. Now when I hit the endpoint by Postman. It is working fine, accepting jwt token to access other APIs but when I am hitting the same API with Angular app then even after passing Authentication in headers it is saying Unauthorized error.

Please help me!

The code is as follows:

createHeader() {
    return (this.header = new HttpHeaders({
      "Content-Type": "application/json",
      Authorization: localStorage.getItem("token")
    }));
  }

Upvotes: 0

Views: 1320

Answers (2)

Manthan Sharma
Manthan Sharma

Reputation: 11

Actually the problem was related to cors which was not allowing the angular app to hit any lambda API through amazon gateway.

Solution: There are two ways which are as follows:

1) You can run the below command on the terminal which will let you hit the API gateway API:

google-chrome --disable-web-security --user-data-dir="/tmp/chrome_tmp"

2) The second way involves editing your serverless.yml file:

- http:
      path: permission/
      method: any
      cors: true

You have to declare cors as true. Now the question is what it will do? The answer is as follows:

The serverless framework allows you to configure CORS in detail. The cors: true is a shortcut for the following configuration.

cors:
origins:
    - '*'
headers:
    - Content-Type
    - X-Amz-Date
    - Authorization
    - X-Api-Key
    - X-Amz-Security-Token
allowCredentials: false  

Upvotes: 0

AJ Longstreet
AJ Longstreet

Reputation: 11

It's likely that Postman is adding the "Bearer " prefix to the auth token which is not happening in your code above.

try:

  createHeader() {
    return (this.header = new HttpHeaders({
      "Content-Type": "application/json",
      Authorization: `Bearer ${localStorage.getItem("token")}`
    }));
  }

Upvotes: 1

Related Questions