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
I have recently finished a react web portal where we have used JWT to initiate, maintain and expire user's session.
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.
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 :)