Home > Enterprise >  What is the correct application architecture to work with bearer tokens?
What is the correct application architecture to work with bearer tokens?

Time:12-25

I want to work with an API that uses OAuth 2.0

In short, I need to obtain an access token which I will have to include in every subsequent request so the server can confirm my identity.

How would the architecture look like doing this in an application? Can anybody recommend an article?

Currently I am inefficiently fetching a new Token from the API on every request in order to perform the request.

Is there a best practice to save a bearer token and reuse it until it expired?

I want to use Vue.js for my application.

CodePudding user response:

As you said, requesting a new token on every request has no sense.

The best approach, once logged-in, is to store the returned token in your localStorage, so no matter if the user refreshes the browser, the app will grab the Bearer from the storage.

Once you accomplish that, you should attach the current valid Bearer token in every axios request. IE:

axios.defaults.headers = {
    common: {
        'X-Requested-With': 'XMLHttpRequest',
        'Access-Control-Allow-Origin': '*',
        'Authorization': 'Bearer ajsyHjdjkakl;ds......'
    }
}

FYI, there are many packages that help you to handle this, otherwise, be prepared to face some headaches. I personally use this once since time ago: https://websanova.com/docs/vue-auth/home

  • Related