Reputation: 831
I have a web application that will handle the authentication with OAuth2. After authentication, web application have the token and can access the resources. However, if the user refreshes the page or closes the browser and comes back later the token is lost and user have to login again. Which is very bad in terms of user experience.
Also, server side code checks if user is logged in and sends the main page of the application only if user is logged in. If he isn't, then it will redirect to login page.
As the OAuth2 token is sent to the server as a header, browser won't send any token when user types the name of the site to the address bar.
I am planning to send access token in cookies. Is this a proper solution?
Upvotes: 3
Views: 2435
Reputation: 580
You might want to set your access token as the default header of every HTTP request you are sending to tour API or Server on the window.ready() or ComponentDidMount() lifecycle hook if you are using React.
Then, having done that, you can start fetching data using your preferred library(like axios) or Fetch when the application is ready.
To do that, you simply save the access token in local storage the first time, and then you retrieve it on window.ready(). You will do that in your App's Container Component or in a script tag in your index.html file.
This solution will not make you able to perform server-side hydration for secured routes though, particularly if your data comes from a stand-alone API. The only way to solve server side hydration when using this kinds of solutions is setting the user access token as a query string parameter in the url, that way the browser can pass it to the server even without executing javascript; but there are obvious security flaws associated with that.
Hope this helps, cheers.
Upvotes: 1