Sessions in token based authentication

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

    I have recently finished a react web portal where we have used JWT to initiate, maintain and expire user's session.

    1. Upon login, sending user credentials to login API. Upon success, get the token back from back-end API. Back-end maintains the token generation and expiration.
    2. Store the token in react state (we use redux store) and in session storage (in case page is refreshed, we can get it back from session storage).
    3. (Optional) Start a per second counter in session storage (to check how long user is idle)
    4. After login, every API call requires the token to be sent in header. API calls are made using fetch. If API call is successful, we get the token back from back-end and we replace it with existing token (stay fresh).
    5. All API calls are 'fetch'ed via a generic customFetch function. Idea is to have a generic fetch to see if back-end response is 401 (access denied). If it is 401, the token is expired or invalid (user is trying to access something without login). In this case, we throw user out of portal, back to login/home page (displaying the error that access is denied).
    6. (Optional) If user is idle for too long (checking the second counter > 900 i.e. 15 min), we show warning to user that session is about to expire, gives user a choice to continue. If user clicks continue, we call an API to retrieve user's profile again, thus making sure that token is still valid. If API is not successful, we log user out and send back to login/home page. The second counter sets back to 1 just before any API call is made (user is active and doing something).
    7. Needless to say that before sending user to login/home page by any of the above scenarios, we clear the session storage and reset the state (redux store).
    8. In case of any refresh happens, we retrieve token from session storage and dispatch initial actions to build the state (redux store) again. If any of the actions (API) fail, we display the message to user that session is expired or invalid and you need to login thus sending user back to login/home page.

    Code snippets

    Assume that you have retrieved the token from login API call:

    set token in session storage and state (redux store)

    window.sessionStorage.setItem('partyToken', token)
    store.dispatch({type: 'profile/setToken', payload: { token }})
    

    retrieval token from session storage or state (redux store)

    const token = window.sessionStorage.getItem('token')
    const token = store.getState().profile && store.getState().profile.token
    

    Of course you can define a common function where you can set/refresh the token after every API call. Similar for retrieval because you need the token before you make API call.

    0 讨论(0)
  • 2020-12-28 16:41

    For encryption and decryption you can use in built laravel's Crypt Model

    use Illuminate\Support\Facades\Crypt;

    What we do for generating APIs token is will take array of required fields.

    Let's create data

    $data = [
        'user_id' => $user->id,
        'time_stemp' => \Carbon::now() // Carbon is laravel's time model(class) for managing times
        'expire_on' => \Carbon::now()->addDays(2); //here i'm setting token expires time for 2 days you can change any
    ];
    
    $data = serialize($data);
    

    then encrypt your data with Crypt

    $accessToken = Crypt::encrypt($data);
    

    Now send to front end in response and save in local storage or cookie anything no need for time here will check on server only.

    Now in every request pass that token and on server side create one middle ware that will parse your data and if your token time is less then expire time then move forward else send error 403 or anything you want.

    How to parse data on server side

    Create middleware using command : php artisan make:middleware ApiAuth then is handle part

    //Accesstoken you passed in $headers or in $request param use whatever you like
    $searilizerData = Crypt::decrypt($headers['AccessToken']);
    $data = unserialize($searilizerData);
    //check if expire_on is less then current server time
    if($data['expire_on] <= \Curbon::now()){
       next(); // let them contuine and access data
    } else {
          throw new Exception ("Your token has expired please regenerate your token",403);
    }
    

    Hope this will help :)

    0 讨论(0)
提交回复
热议问题