PHP code example of aliirfaan / laravel-simple-jwt
1. Go to this page and download the library: Download aliirfaan/laravel-simple-jwt library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use aliirfaan\LaravelSimpleJwt\Services\JwtHelperService; // jwt helper service
class JwtTestController extends Controller
{
/**
* Include our service using dependency injection
*/
public function index(Request $request, JwtHelperService $jwtHelperService)
{
// jwt flow
// payload
$tokenPayload = array(
'customer_id' => 1234,
);
// in a middleware
$token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJMYXJhdmVsX2Jsb2ciLCJhdWQiOiJodHRwOlwvXC9sb2NhbGhvc3RcL2Jsb2ciLCJpYXQiOjE2MTIxODAyMTEsImRhdGEiOnsiY3VzdG9tZXJfaWQiOjEyMzR9LCJleHAiOjE2MTIxODExMTF9.uqFln2iQVRvaYvKDTGEG29SrT1flj9JEvFBg2zO3whM';
$verifyJwt = $jwtHelperService->verifyJwtToken($token);
if ($verifyJwt['errors'] == true) {
} else {
//get your token claims
$tokenClaims = (array) $verifyJwt['result'];
//dd($tokenClaims);
}
// refresh token flow. Using refresh flow is optional and depends on your use case
$modelType = 'customer'; // your model type name you want, should be unique so that you can sent refresh tokens to multiple types of model
$modelId = 253; // your model id
$refreshToken = '798798-543543-5435432543'; // the refresh token sent by consumer/client, will be null for new logins
$deviceId = 1536-452; // your device id if you are using devic_id column
$refreshTokenResult = processRefreshToken($modelType, $modelId, $refreshToken, $deviceId);
dd($refreshTokenResult);
}
}
namespace App\Http\Middleware;
use Closure;
use aliirfaan\LaravelSimpleJwt\Services\JwtHelperService;
class SimpleJwtVerifyExample
{
protected $jwtServiceInstance;
public function __construct(JwtHelperService $jwtHelperService)
{
$this->jwtHelperService = $jwtHelperService;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
// get token from header bearer token
$token = $request->bearerToken();
$verifyToken = $this->jwtHelperService->verifyJwtToken($token);
if ($verifyToken['errors'] == true) {
}
// passed token validate, continue with request
$tokenClaims = (array) $verifyToken['result'];
$request->attributes->add(['token_claims' => $tokenClaims]);
} catch (\Exception $e) {
//
}
return $next($request);
}
}
config\auth.php
'guards' => [
'api' => [
'driver' => 'simple-jwt-guard',
'provider' => 'user',
'profile' => 'default', // the jwt profile you want to use for the provider
'jwt_class' => null // if you have implemented your own jwt service that implements JwtServiceInterface
]
],