Sessions in token based authentication

前端 未结 8 1088
轻奢々
轻奢々 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:40

    You actually don't need any ReactJS or VanillaJS. Just pure HTML and PHP actually. What I do is just store it as a cookie.

    First of all, as you receive the token from Lumen, save it in your user database for specific user. Then set user id and accesstoken as cookies which expire after a certain time with this code:

    setcookie('userid',$userid, time()+(3600 * 24 * 15),"/");
    setcookie('accesstoken',$accesstoken, time()+(3600 * 24 * 15),"/");
    header('Location: /home.php');
    //You can change the 15 in setcookie() to amount of days the cookie will expire in.
    //The "/" in setcookie is important, because it ensures the cookies will be available on every page the user visits on your website.
    //The header function redirects to your home page after log in
    

    Then below is how your home page would look. It checks if accesstoken cookie exists, if it does, it double checks that the token matches the current token in the user database. If it's a match, it shows 'logged in' page. If not, you should show/redirect to login page.

    
    
    
    
    Sup
    
    
    
    
    

    User logged in!

    Do whatever you need to do if user is logged in

    No accesstoken found

    More than likely you will want to show login page here

    and then to logout is simple. The code below removes accesstokens by setting them to expired:

    setcookie("accesstoken", "", time() - 3600);
    setcookie("userid", "", time() - 3600);
    header('Location: /youareloggedout.html');
    

    Remember, that is the BASICS of a functional log in / log out system. If I explained all security measures needed, this post would be even longer. Be sure to do your research. Some topics to start you off are prepared statements and preventing XSS attacks. :)

提交回复
热议问题