jhefreyzz
How to implement persistent session in SPA with Phoenix as API
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.
Thank you.
Marked As Solved
kokolegorille
I have two pipelines…
pipeline :api do
plug :accepts, ["json"]
end
pipeline :api_auth do
plug(AppApiWeb.Plugs.VerifyHeader, realm: "Bearer")
end
scope "/api/v1", AppApiWeb do
pipe_through :api
post("/registration", RegistrationController, :create)
post("/authentication", AuthenticationController, :create)
# Secure API
pipe_through(:api_auth)
...
I wrote a plug to check if token is present in the request and extract it if needed. This allows to define which route is protected, or not.
Protected route requires this token to be decoded, and ensure who You are.
Also Liked
kokolegorille
The check should not be done on the client, but on the server…
This is my flow for SPA. get a Phoenix Token (not a JWT!) when successful authentication. Then store in localstorage.
Then, add this token in the header for each requests.
The token is decoded server side, and guarantee your identity.
There is no session with api.
kokolegorille
Some prefers to persists it in cookies instead. And storage is different when using mobile (eg. React Native).
But I use localstorage…
danschultzer
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.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








