How to pass in the token for authorization in between React pages (in a Django Knox setup)?

1.2k views Asked by At

I have 2 components/pages. One is the login page and one is the user customization page. I want the user customization page to be token authorized so you can only see it after you login.

I am using a Django + React setup with Django Knox being used as the authorization tokens.

I now have a workflow using this.props that passes the token from the login component to the main app.js and then to the user customization component. But I guess during the routing/switching between pages, my token is lost. How do I maintain this token?

1

There are 1 answers

2
bilo-io On BEST ANSWER

So, basically trying to persist your token, without having to refetch it when (for example) the page is reloaded or, as you mentioned, when navigating between different pages in your application.

There are various ways to store the token, without much work, one such example being sessionStorage

// API response
const token = response.data.token

// write to storage
sessionStorage.setItem('myTokenName', token)

// read from storage
sessionStorage.getItem('myTokenName')

// delete from storage
sessionStorage.remove('myTokenName')

With plain JS:

  • sessionStorage
  • localStorage
  • cookies

NOTE: Each has it's purpose and limitations

With additional libraries for state management, although this requires more work, and is not necessary to fix your issue.

  • Redux
  • Apollo (assumes you're using GraphQL)