Babr
Babr

Reputation: 2081

Where should I store JWT token?

I'm developing an app using vue.js and vuex which authenticates to a JSON API server using JWT tokens. So I'm wondering what is the best practice to store JWT token?

If I store it in vuex store, it gets lost after the page refresh, so user needs to login again, which is not very convenient.

And if I store it in the browser's localstorage, It gets deprecated before the next login and then components which assume the authentication token get confused. I have no idea how to deal with this.

Appreciate your hints on this.

Upvotes: 3

Views: 5052

Answers (2)

sawim
sawim

Reputation: 1082

Below is a snapshot from my react project with axios library, where I had a similar problem. When response from server was 401 (Unauthenticated), I requested for a new JWT token using another token (refreshToken) with no expiration date

axios.interceptors.response.use(
    ok => ok,
    err => {
        if(err.response.status === 401) {
            return axios
                    .get('/api/oauth/token/refresh', {
                        headers: {'Authorization': `Bearer ${localStorage.getItem('refreshToken') }`}
                    })
                    .then(({data}) => {
                        // in data is new access token
                        err.config.headers['Authorization']=`Bearer ${data.token}`;
                        return axios(err.config)
                    });

        } 

        throw err
    }
);

Upvotes: 2

Orel Eraki
Orel Eraki

Reputation: 12196

And if I store it in the browser's localstorage, It gets deprecated before the next login and then components which assume the authentication token get confused. I have no idea how to deal with this.

This is not true, localStorage information is saved per Document origin. It the application responsibility to check if the token is still available(not expired) and if not redirect him to the Login page.

You should extend you expiration to how long is reasonable to relogin, and you should think of a decent algorithm to extend his JWT token. e.g Every time a user is doing a request to the server and is left with 1hr you can increase is login for 1day.

Upvotes: 1

Related Questions