Last active
March 13, 2021 21:44
-
-
Save mattmcdonald-uk/cce530a90b00bdb3ed05ac4f826dae1c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; | |
use Tymon\JWTAuth\Exceptions\JWTException; | |
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware; | |
class AuthenticateAndRenew extends BaseMiddleware | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* | |
* @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException | |
* | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$this->checkForToken($request); | |
$this->auth->setRefreshFlow(); | |
try { | |
if (! $subject = $this->auth->parseToken()->authenticate()) { | |
throw new UnauthorizedHttpException('jwt-auth', 'User not found'); | |
} | |
} catch (JWTException $e) { | |
throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode()); | |
} | |
$response = $next($request); | |
return $this->setAuthenticationHeader($response, $this->refreshTokenWithCustomClaims($subject)); | |
} | |
/** | |
* Create a refreshed token with updated custom claims. | |
* | |
* @param mixed $subject | |
* @return string | |
*/ | |
protected function refreshTokenWithCustomClaims($subject) | |
{ | |
return $this->auth->parseToken()->customClaims($subject->fresh()->getJWTCustomClaims())->refresh(); | |
} | |
} |
The authentication is handled the same way as in the BaseMiddleware, it just stores a reference so the returned subject to the custom claims can be refreshed.
I have created a middleware to check pwu:
even though I think jwt must check claims changes itself
when I change pwu, auth keeps working (seems a bug in laravel-jwt)!
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
class AdminCheckMiddleware extends BaseMiddleware
{
public function handle($request, Closure $next)
{
$this->checkForToken($request);
$subject = $this->auth->parseToken()->authenticate();
if ($subject && $subject->isAdmin()) {
if ($this->auth->getClaim('pwu') === $subject->terminated_at) {
return $next($request);
} else {
$this->auth->logout();
}
}
return abort(Response::HTTP_UNAUTHORIZED, 'unauthorized:panel');
}
}
```
and what's the usage of $this->setRefreshFlow()
?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in case the token expires this middleware also helps to verify if the token is valid or not?