Skip to content

Instantly share code, notes, and snippets.

@mattmcdonald-uk
Last active March 13, 2021 21:44
Show Gist options
  • Save mattmcdonald-uk/cce530a90b00bdb3ed05ac4f826dae1c to your computer and use it in GitHub Desktop.
Save mattmcdonald-uk/cce530a90b00bdb3ed05ac4f826dae1c to your computer and use it in GitHub Desktop.
<?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();
}
}
@danialdezfouli
Copy link

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