DWQA QuestionsHow to use laravel jwt(Lcobucci\JWT) auth in laravel 5.7?
kundan roy asked 3 years ago

solution:
step1: create jwtMiddleware
<?php

namespace App\Http\Middleware;
use Auth;
use Input;
use Closure;
use JWTAuth;
use Exception;
use Illuminate\Http\Request;
use Lcobucci\JWT\ValidationData;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Parser;
use App\Http\Controllers\Utility\Utils;
class JwtToken
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
try {
$getAuth = null;
$getAuth = $request->header(‘authorization’);
if ($getAuth !== null) {
/*
* Extract the token from the Bearer
*/
list($jwt) = sscanf($getAuth, ‘Bearer %s’);
}
if(!isset($jwt) || $jwt == ”) {
$errorResponse = [
‘code’ => 403,
‘status’ => ‘failed’,
‘message’ => “Forbidden Token”
];
return \Response::json($errorResponse);
}
$signer = new Sha256();
$token = (new Parser())->parse($jwt);
$data = new ValidationData();
if (
$token->verify($signer, env(‘SHA_KEY’)) === false
) {
$errorResponse = [
‘code’ => 403,
‘status’ => ‘failed’,
‘message’ => “Invalid Token signature”
];
return \Response::json($errorResponse);
}
if(
$token->validate($data) === false
) {
$errorResponse = [
‘code’ => 403,
‘status’ => ‘failed’,
‘message’ => “Invalid Token”
];
return \Response::json($errorResponse);
}
return $next($request);
} catch (Exception $exception) {
Utils::printData($exception->getMessage());
exit();
}
}
}

 
step2: add jwtmiddleware class in kernel

‘JwtTokenv’  =>  \App\Http\Middleware\JwtToken::class,

step3: Now use route like this
 
Route::group(
[
‘prefix’ => v1
],
function () use (v1) {
 
Route::group([‘middleware’ => [‘JwtToken’]], function () use ($version) {
Route::post(‘/AppConfig/get’, ‘[email protected]’);
});
// if route not found
Route::any(‘{any}’, function () {
$data = [
‘code’ => 400,
‘status’ => ‘failed’,
‘message’ => ‘Bad request’,
];
return \Response::json($data);
});
}
);