user7559874
user7559874

Reputation:

How to persist JWT token throughout session until user logout?

I'm working on authentication with JWT for a simple React/Rails Api that makes requests to Giphy api.

I receive a token after a successful login, and it works because I have the 'Bearer thatlongstringwithnumbersandletters' in my Authorization headers in the Developer Tools's Network tab. However, when I refresh a page, I lose the token.

In my app.js file:

handleLogin(params){
    // debugger
    console.log('params', params)
    let URL = 'http://localhost:3000/api/v1/auth'
    axios.post(URL, {
      username: params.username,
      password: params.password
    })
    .then(res => {  //console.log('app', res.data)
      const token = res.data.token
      //console.log('Store in localStorage: ', token)
      localStorage.setItem('jwtToken', token)
      setAuthorizationToken(token)
      // this.history.push('/puns')
    })
  }

In my setAuthorizationToken.js file:

import axios from 'axios'

const setAuthorizationToken = (token) => {
  if(token){
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
  } else {
    delete axios.defaults.headers.common['Authorization']
  }
  console.log('Authorization is SET')
}

export default setAuthorizationToken

Then, what I thought the token would be persisted throughout user session is by placing a callback in the index.js (parent of app.js) By placing this in the parent, I can have the token be saved throughout.

import setAuthorizationToken from './components/auth/setAuthorizationToken'

setAuthorizationToken(localStorage.jwtToken);

ReactDOM.render((
  <Router>
    <App />
  </Router>
), document.getElementById('root'));

How can I get the token to be persisted? Any help is appreciated, thank you.

Upvotes: 1

Views: 2245

Answers (2)

puri
puri

Reputation: 3

Store in sessionStorage:

sessionStorage.setItem('access_token', access_token);

then use token:

sessionStorage.getItem('access_token');

Upvotes: 0

Matt
Matt

Reputation: 35251

It looks like you are not accessing localStorage correctly.

Try this instead:

localStorage.getItem('jwtToken')

Upvotes: 2

Related Questions