Encountering a 401 error while trying to access a protected endpoint on AWS Cognito

Currently, I am dealing with a Cognito user pool that has an application integration for JavaScript lacking a secret key. Interestingly, I can successfully log in using the code snippet below:

  private static async signin(role: UserRole): Promise<string> {
    const user = getUser();

    const cognitoUser = new CognitoUser({
      Username: user.username,
      Pool: "myuserpool"
    });

    const authDetails = new AuthenticationDetails({
      Username: user.username,
      Password: user.password
    });

    return new Promise((resolve, reject): void => {
      cognitoUser.authenticateUser(authDetails, {
        onSuccess: result => {
          this.credentials[role] = result.getIdToken().getJwtToken();
          resolve(this.credentials[role]);
        },
        onFailure: err => {
          console.log(`Failed login to cognito with ${role}: `, err);
          reject(err);
        }
      });
    });
  }

However, when I attempt to make a call to my endpoint using the aws-api-gateway-client, even though the token is attached, it consistently results in a 401 unauthorized response.

The confusing part comes in when I try pasting the same token into the ApiGateway Authorizer testing section, where it returns a 200 ok message. This discrepancy indicates that the token is valid but not functioning correctly in the context of the API Gateway.

EDIT: To provide more clarity, here is the flow....

  • I have a Cognito user pool
  • Successful login to the userpool yields a token
  • I then apply "Authorization": "bearer {token}" on the aws-api-gateway-client request headers
  • The request consistently fails with a 401 Unauthorized status
  • If I use the same token within the test section of the ApiGateway Authorizer, it confirms the validity of the token

Answer №1

In my opinion, omitting the "bearer" part in the header value is unnecessary. Cognito authorizers only require the key/token. Consider using a header like

"Authorization": "<place_token_here>"
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create an object using a combination of different promises

Creating an object from multiple promise results can be done in a few different ways. One common method is using Promise.all like so: const allPromises = await Promise.all(asyncResult1, asyncResult2); allPromises.then([result1, result2] => { return { ...

Guide to refreshing the modal component with updated properties

In my application, I have created a modal component for managing recipes. This modal allows users to save recipes to a list. let modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/> However, I also want to utilize the same m ...

Tips for bringing in specialized document formats in Typescript

For a fun side project, I am in the process of creating a "framework" to easily develop native web components. One aspect of this involves using a webpack loader to parse XML within custom .comp files and export an es2015 class. However, I've encounte ...

Convert JavaBeans sources into a JSON descriptor

I'm in search of a tool or method to analyze standard JavaBeans source code (featuring getters and setters) and create json descriptors using tools like grunt or ant, or any other suitable option. Here's an example: FilterBean.java: package com ...

Retrieve the $scope reference within the $rootScope event handler

Within the .run segment of the primary module in my application, there is an event handler designated for the $locationChangeStart event. Its purpose is to verify the abandonment of any unsaved modifications. The setback lies in the necessity of having a c ...

Retrieve the desired destination URL in the CanActivate guard when lazily loading modules in Angular

I am facing an issue with retrieving the target URL in the canActivate guard. Even though I have set up preloadingStrategy: PreloadAllModules in RouterModule.forRoot, the url property of ActivatedRoute does not contain the path. Here are the contents of bo ...

Ascending to the Peak within a div

<script type="text/javascript"> $(document).ready(function(){ updateContent(); }); function updateContent(){ $('#mainDiv').load('home.php', function(){ scrollToTop(); }); } ...

Identify the position of a mouse click event when dots overlap

Experience this live demo on CodePen by visiting it here. 1) When you click on the grid, a first red point will be added. 2) Click on the grid again to add a second red point. 3) By clicking back on the first red point, you may notice that the coordinat ...

Refreshing the child component based on the child's action and sending information to the parent in a React application

Within my Parent Component, I am utilizing an Ajax call to populate two children Components. C1 requires the data only once, while C2 has the ability to fetch additional data through subsequent Ajax calls and needs to render accordingly. I find it more co ...

Embrace the power of Angular2: Storing table information into

Custom table design Implement a TypeScript function to extract data from an array and populate it into a stylish table. ...

Specify the data type of a nested object in a React component with TypeScript

Interface Button{ buttonTitle: { name?: string; } } What is the best way to specify a type for the buttonTitle property? ...

Hide the accordion panel that is not actively being viewed as another one opens

Looking for a way to collapse an accordion panel when another one opens using vanilla JavaScript? Specifically, the solution needs to work in IE11. I am a JavaScript beginner and would greatly appreciate any help or guidance you can offer. Thank you. va ...

Utilizing the dnd library to incorporate drag and drop functionality

I've encountered an issue with the code snippet below. Although I am able to drag elements, I am unable to drop them. How can I trigger the dropFunction when a drop occurs? Drag code: <div> <a class="button" ng-class= ...

Creating an Ajax Post request for API invocation

I'm currently setting up an Ajax Post request to interact with an API. Here is a mock curl command for reference: curl -X POST \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --h ...

Using Jquery to Retrieve the Content of Head and Body Tags from a String

Here is a string that I currently have: <head> This is the Head </head> <body> <div> <div> <p> Body Content <br /></p> <p>&nbsp; Hello World <br />< ...

Three.js experiencing issues with quaternion rotation malfunctioning after exceeding a rotation angle of around 90 degrees

Trying out two-finger touch events to pinch, rotate, and zoom a THREE.Mesh object using quaternions has been quite an interesting experience. As I delve into this new rotation method, I've noticed an intriguing behavior that puzzles me. When I rotate ...

Get the value of an HTML element

Is there a way to retrieve the value of an HTML element using PHP or JavaScript, especially when the value is dynamically loaded from another source? I have tried using jQuery with the DOM ready event, but often encounter the issue where the element's ...

having difficulty with the design of my google map

Struggling to style my Google Map this week - I have the JSON values but no clue how to add them into the JavaScript. Also, need to move the zoom bar control to the right instead of it being hidden behind site content on the left. Any help would be greatl ...

Unlocking the Potential of JavaScript Proxy: Clearing Out an Array Object

Examining the JavaScript Proxy code snippet below: const queue = new Proxy([], { get: (target, property) => { return target[property]; }, set: (target, property, value) => { target[property] = value; this._pro ...

Advanced Typescript contains a parameter that specifies the type of callback function

Is it possible to create a function that is more typesafe than the current implementation? public addBusinessRule(targetProperty: string, dependentProperties: string[], callback: (dep0: any, dep1: any, ...)): void { // s ...