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.

1 answer

  • answered 2017-06-17 19:30 Matt

    It looks like you are not accessing localStorage correctly.

    Try this instead:

    localStorage.getItem('jwtToken')