-1

Im learning about JWT, but i dont know how to manage the tokens (ACCESS token and REFRESH token) in the front end for making HTTP requests.

An example, when i log in in my page, i make a login request to the server that gives me an ACCESS token and a REFRESH token (that a save in the cookies and in the user data base). Now, for make some other HTTP request that needs to be authenticated, how can i transfer the ACCESS token to the Authorization Header of the request? Just put it on a variable? it is safe?

Also consider that my web site have multi-pages, how can i pass the token over the diferents pages?

Another strategy that cames to my mind is to use the refresh token that i have on my Cookies (once that i logged in) to make a new access token, but i dont know how is the standard manage of this.

Sorry if im not being clear...

Thank you!!

  • https://stackoverflow.com/q/1336126/4722345 – JBallin Oct 20 '22 at 23:47
  • Usually setting `Authorization: `Bearer ${accessToken}` in the request headers is the way to go, but auth depends on server implementation, i'd suggest reading the doc of the said server if it doesn't work. We usually use sessions to pass data through pages. – Hollyol Oct 21 '22 at 15:50
  • @Hollyol What do you mean with "sessions"?? Session storage?? Can i pass the access token to te session storage? – Uriel Espada Oct 21 '22 at 21:34
  • @Hollyol jwt is a replacement for session, toy don't combine the two – Konrad Oct 22 '22 at 13:52
  • Jwt is usually combined with spa, so if you don't have spa, you should rather use session – Konrad Oct 22 '22 at 13:53

1 Answers1

0

I'm assuming you're using axios,

You could create your apiInstance like this

export const apiInstance = axios.create({
  baseURL: YOUR_BASE_URL,
  responseType: 'json',
  headers: {
    //Content-Type: 'CONTENT_TYPE',
    // you dont need to pre-define all headers
  },
})

To save the access token for further use

apiInstance.defaults.headers.common['Authorization'] = `Bearer ${token_here}`

Then every time you want to make a request you just use apiInstance.get/put/patch etc. The access token is saved and reusable. If it expires, you're gonna have to refresh it, in which case you need to have your refresh token saved somewhere, local storage is not recommended but could work as a start.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Robin
  • 1
  • 1
  • Thanks. I dont know about axios but i ll give it a check. One other question, when i want to refresh the token, i do it just when expires the access token or in every request? And how can i implement that? Did i put a modal in the page that requires the confirmation of the client that still there? – Uriel Espada Oct 21 '22 at 10:06