Sessions in token based authentication

前端 未结 8 1240
轻奢々
轻奢々 2020-12-28 15:54

I am building an app in PHP Lumen which returns a token upon login. I am not sure how to proceed beyond this.

How am I supposed to maintain a session using these to

8条回答
  •  余生分开走
    2020-12-28 16:36

    I'll write down a quick todo and best practices, as there are many ways to do it with code.

    Backend

    • (POST) login route {email, password} it will create a token. You can use JWT (Json Web Token) The token will be returned to the client. Inside the token, you can store some basic details: user id, username, token expiration, user type etc. https://jwt.io/

    Client

    • login request, pass {email, password}.

      On success, get the token and store it locally, localstorage is preferred, but cookie is possible as well.

    • on each page load with your react app, you should have a function check for that token, it will decrypt it, and get the details for further use.

      I mean get the username, user id etc. More important if you will want to add it, is the "expiration", if the token was expired you redirect the user to login page, OR you can re-request for a new token, it really depends on your app.

    • logout, is quite simple... simply remove the token from the client side and redirect to login page.

    • Make sure that for "authenticated" pages, you check that the token exists, and even further you can check the user type.

    ** for client side decoding of JWT, you can use: https://www.npmjs.com/package/jwt-client

提交回复
热议问题