Zach
Zach

Reputation: 468

401 returned from API gateway using Cognito authorizer - no matter what is passed in

I've got users able to log in, and log out, sign up, password reset - all using AWS amplify in my React.js code.

After they are signed in, I want to fetch my API gateway, that is using Authorization: UserCognito, then going to a lambda function where I want to be able to pull the data passed into my API and return their information from the dynamoDB with their profile info (such as name, picture, email).

When I fetch the API, I get {"message":"Unauthorized"}

I'm calling the api like this:



     getProfileInfo(user.signInUserSession.idToken.jwtToken).then(user => {
                console.log(user);
              });

and have even tried this:

```

let token = await Auth.currentCredentials();
      console.log(token);
      const options = {
        method: "POST",
        headers: {
          "content-type": "application/json",

          Authorization: token.sessionToken
        }
      };

      let res = GetProfileInfo(token.sessionToken);
      API.post("XXURL", "", options);

````

With getProfileInfo looking like:


      const getProfileInfo = async user => {
      let url = XXXXXXXX
      console.log(user);
      const data = await fetch(url, {
        method: "POST",
        headers: {
          "content-type": "application/json",
          Authorization: user
        },
        mode: "cors"
      })
        .then(response => {
          console.log(response);
          return response.json();
        })
        .then(data => {
          return data;
        })
        .catch(error => {
          return error;
        });
      return data;

So - how do I pass in my user's info from AWS-amplify, into my API, on the react front end side - so it can authorize them, then run my lambda function where I take their user information and look up their profile in my DynamoDB?

My API gateway, has the token assigned to the value of Authorization when setting up my authorizer.

Also, I have template mappings set up for my API that look like this:

```
    {
    "context" : {
        "sub" : "$context.authorizer.claims.sub",
        "email" : "$context.authorizer.claims.email"
    }
    }
```

But still nothing but Unauthorized is returned. So what am I doing wrong?

Upvotes: 2

Views: 3787

Answers (1)

mariux
mariux

Reputation: 3117

If you actually have a valid JWT in user in your getProfileInfo() then try to use

headers: {
  ...
  Authorization: 'Bearer ' + user    
}

maybe you also want to verify that you have a valid token on a site like jwt.io

Upvotes: 4

Related Questions