How can I get the JWT token after authenticating?

Asked

Viewed 914 times

1

I have a spring-boot Rest API which, when a user authenticates the api returns the jwt token, I noticed in the browser that the token appears in Response Header > Authentication and in tests with Postman it shows in Body.

How can I get this token to store in the browser’s Local Storage by Reactjs ?

My code that makes the requisitions is like this:

import { ACCESS_TOKEN, API_BASE_URL } from '../constants';

export function request (options) {
    const headers = {
        'Content-Type': 'application/json',
    }

    if(localStorage.getItem(ACCESS_TOKEN)) {
        headers.append('Authorzation', 'Bearer ' + localStorage.getItem(ACCESS_TOKEN))

    }

    return fetch(API_BASE_URL+options.url, {
        method: options.method,
        headers: headers,
        body: options.body
    })
    .then(function(response){ 

        // Falta pegar o token e gravar na local estorage

        if(!response.ok) {
            return Promise.reject(json);
        }
        return json;

    });
};

1 answer

1

To add to localStorage just use setItem(KEY, VALUE). I don’t know what structure of your Sponse, but it would look something like this:

localStorage.setItem(ACCESS_TOKEN, response.value.jwt);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.