Tips for properly sending a JWT token

When working on my angular application, I encountered an issue while trying to send a jwt token as a header for request authorization. The error 500 was triggered due to the jwt token being sent in an incorrect format. Here is how I am currently sending it:

Bearer {"id_token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY1MDMxMTg0MH0.zWxESmFkM_nE8LEqIfFwSb-nEG593qaYnS1IFjd9qdYbOZJmMSXirfW3S68lQ0PBJcNop-OGtB6JJjtNJprDIQ"}

What I actually need is:

Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY1MDMxMTg0MH0.zWxESmFkM_nE8LEqIfFwSb-nEG593qaYnS1IFjd9qdYbOZJmMSXirfW3S68lQ0PBJcNop-OGtB6JJjtNJprDIQ

I attempted the following, but encountered an "undefined can not read property of trim" error:

token.split(" ")[1].trim()

I would appreciate some guidance on where I may be going wrong. Below is my interceptor code that handles sending the header:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor() {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (!request.url || (request.url.startsWith('http') && !(environment.rootUrl && request.url.startsWith(environment.rootUrl)))) {
      return next.handle(request);
    }
    const token =
      localStorage.getItem('token') ||
      sessionStorage.getItem('token');

    if (token) {
      console.log(token)
      request = request.clone({
        setHeaders: {
          Authorization: 'Bearer ' + token.split(" ")[1].trim()
        },
      });

    }
    return next.handle(request);
  }
}

EDIT: Added the method which saves the token:

 authenticateUser(login: LoginModel){
    this.http = new HttpClient(this.handler)
    return this.http.post(environment.rootUrl + 'api/authenticate', {
      username: login.username,
      password: login.password,
    }).subscribe({
      next: (data) => {
       localStorage.setItem('token', JSON.stringify(data))
        this.router.navigate(['/dashboard'])

      }, error: (error) => {
        this.isAuthenticated = false
      }
    })

console.log:

{"id_token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTY1MDMxNzk0OH0.YACaabpkEWEkG6a65GspdLL9Ds50rQNBAou9f1X-mq2NMeSsNRZoabuMK3WcNAd_8t3q-yeDkNPYbMQkFD8B2g"}
  }

EDIT2:

console log of data:

{id_token: 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiO…nSYP5PctcyXIQ_RuoaQQ72w5bf2YO943WoRhTQTER-y0LH6iw'}

Answer №1

When receiving an API response in the form of a JSON Object, it is necessary to parse the JSON in order to extract certain information. The following code snippet demonstrates how to retrieve the id_token key from the JSON response:

localStorage.setItem('token', JSON.parse(data).id_token)

On the other hand, if the API response is in the form of a string rather than a JSON Object, attempting to use JSON.parse() will result in an error. In this case, the code below should be used to access the id_token key:

localStorage.setItem('token', data.id_token)

It is important to note that the method of parsing the API response depends on whether it is in the form of a string or a JSON Object. Both scenarios have been addressed in the provided code snippets.

It is unnecessary to use token.split for this purpose. Instead, the token can be directly included in the Authorization header as shown below:

Authorization: 'Bearer ' + token

This approach should effectively resolve any issues related to accessing and using the token from the API response.

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

The intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

execute the angular service within the "then(function(){})" block

I have a specific requirement where I need to capture a screenshot of a view when the user clicks on a button, send it back to the backend to save as a PDF in the database, and then allow the user to download the same image. Currently, I am utilizing the D ...

Context API is failing to work in components that use children when the version is v16.6.0 or higher

Currently, I am utilizing the latest context API of React (v16.6.0 or higher) by specifying the public static contextType inside the component that consumes the context. Everything works smoothly unless the component declaring the Provider directly include ...

How to retrieve the value of a table row by clicking with the mouse using jQuery?

I am having an issue with my table data display. Each row in the table is assigned a unique ID, which corresponds to the value of the tr-tag. My goal is to log this ID in the console when a table row is clicked. Here is the table: $.getJSON(`http://local ...

Using CodeIgniter framework for processing form submissions asynchronously using AJAX

I'm currently facing a challenge where I need to save data submitted from a form to my mysql database, and then update the div element with the latest posted item at the beginning of the list in the div. At this point, my main focus is on receiving a ...

Tips on extending the response wait time for an API request using Observable RxJS in Angular

I have a Java Spring Boot backend application and an Angular frontend. In my front end, I am using a REST API to delete a file on the server but I keep getting a 404 error even though the service has been consumed and finished correctly. I suspect that th ...

The data submitted from the form did not successfully get inserted into the database row

Currently, I am working on integrating a new product into my products database using ajax with php and mysql PDO. The form is located in a separate HTML file and gets loaded into a Bootstrap modal when the "add product" button is clicked. Below you can fi ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

Issue with VueJS instance: Unable to prevent default behavior of an event

Is there a way to disable form submission when the enter key is pressed? Take a look at the different methods I've attempted along with the code and demo example provided below. SEE PROBLEM DEMO HERE Intended outcome: When you focus on the input, pr ...

Limiting the data obtained from the API to extract only the desired values

Using an API, I am retrieving customer information and displaying it in the console. The code snippet used for this operation is: if (this.readyState === 4) { console.log('Body:', this.responseText); } }; This returns a JSON object with v ...

Setting up a Webpack configuration to compile modules within the node_modules directory

My webpack and babel configuration is causing some issues. I installed my component repository (es6 module without webpack configuration) as a node_module, but it's not working - I'm getting an 'Unexpected token import' error because Ba ...

Bring in properties from a separate file in Vue3

Currently, I am utilizing Vue3 along with the options API. Within my setup, there are various Vue components that rely on a shared prop defined as: exercise: { type: Object as PropType<Exercise>, required: true, }, To streamline this pro ...

What is the best method to retrieve checked checkbox values and the selected dropdown value using AngularJS?

My code is set up to capture checked checkbox values and selected dropdown value when the submit button is pressed. It successfully retrieves the checked checkbox values, but I'm having trouble getting the selected offer from the dropdown. For example ...

Exploring the power of promise chaining within AWS Lambda

I'm feeling a bit confused about how Promise chaining works in AWS Lambda. exports.handler = async(event) => { firstMethod = () => { return new Promise(function(resolve, reject){ setTimeout(function() { ...

Filtered Owl Carousel

Hello everyone. Just wanted to mention that our English may not be perfect. I managed to filter with owl carousel by tweaking some codes I found online. It's working now, but I'd love for it to have an animated effect while filtering, like a fad ...

Can we implement attribute selectors in Material-UI while utilizing makeStyles?

Is it possible to extract all the div elements with specific Mui class names such as access-MuiPickersCalendarHeader-switchHeader, access-MuiPickersDay-day? My components are styled using StylesProvider which adds "access" as a prefix to the original Mater ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

Encountering a no-loops/no-loops eslint error in node.js code while attempting to utilize the for and for-of loops

While working on my nodejs application, I have encountered an issue with es-lint giving linting errors for using 'for' and 'for-of' loops. The error message states error loops are not allowed no-loops/no-loops. Below is the snippet of c ...

Each $.each function varies based on the type of object it is iterating

I have encountered an issue with my $.each statement. When it is written like this: $.each($(".permissions"), function (index, element) { ... }).promise().done(function () {...}); everything works fine. However, when I change the $.each statement to: ...

execute a function once an asynchronous function has finished running

I have observed the practice of calling functions in succession using promises, and I have an async function with observables. fetchData() { this.generatePayload() this.dataService .getData(this.payload) .subscribe( (data: any ...