I’m looking for a way to implement a persistent session of the authenticated user using React that runs on different server than Phoenix.
My initial idea would be making a JWT based authentication, after successful authenticated the server replies with a JWT signed token. The client then will store this token in a localstorage then in a custom PrivateRoute component (a component where it will check for a existing token in the localstorage then redirects to the protected route if exist and redirect to login page if it does not exist). But I think this would not be secure and I’m asking if there are ways to have persistent session of user.
With this flow I always perform a request like /me endpoint whether the request has the token in its header on the client side to know that it does not need to go back again to the login page?
Thanks I have understood now the way for the server to check if the user is authenticated or not. Is there for a user let say maintain a authenticated user even though a web app is open in another tab or refreshes the current tab?
Refresh is ok, because client has the token in localstorage, but identity is shared for tabs of the same browser. You can have two identities when opening tabs in different browsers.
If credential is valid, the server will respond with a Phoenix Token
Then the client receives the token, stores it in a localStorage then add this token in request header
The server will now know if the user is authenticated or not by checking the header
To maintain a persistent authenticated user in the app, I will check if there a token stored in the localStorage if not then redirect the user to the login page.
It’s generally a bad idea to store sensitive data in LocalStorage. If you use the same domain then I would let the backend set a httpOnly cookie, otherwise I would only keep the token in memory, and use something like OAuth2 auth code flow with PKCE.