Sessions in token based authentication

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

提交回复
热议问题