4 changed files with 86 additions and 0 deletions
@ -0,0 +1,36 @@ |
|||
<?php |
|||
namespace app\middleware; |
|||
|
|||
use app\service\JWTService; |
|||
use think\Exception; |
|||
use think\Request; |
|||
|
|||
class JWTAuth |
|||
{ |
|||
protected $jwtService; |
|||
|
|||
public function __construct(JWTService $jwtService) |
|||
{ |
|||
$this->jwtService = $jwtService; |
|||
} |
|||
|
|||
public function handle(Request $request, \Closure $next) |
|||
{ |
|||
$token = $request->header('Authorization'); |
|||
|
|||
if (!$token) { |
|||
throw new Exception('Missing token'); |
|||
} |
|||
|
|||
$claims = $this->jwtService->verifyToken($token); |
|||
|
|||
if (empty($claims)) { |
|||
throw new Exception('Invalid token'); |
|||
} |
|||
|
|||
// 将 claims 存储到 request 对象中 |
|||
$request->attributes->set('claims', $claims); |
|||
|
|||
return $next($request); |
|||
} |
|||
} |
|||
@ -0,0 +1,40 @@ |
|||
<?php |
|||
namespace app\service; |
|||
|
|||
use Lcobucci\JWT\Parser; |
|||
use Lcobucci\JWT\Signer\Hmac\Sha256; |
|||
use Lcobucci\JWT\Token; |
|||
use Lcobucci\JWT\Signer\Key\InMemory; |
|||
|
|||
class JWTService |
|||
{ |
|||
private $secret; |
|||
|
|||
public function __construct() |
|||
{ |
|||
$this->secret = config('jwt.secret'); |
|||
} |
|||
|
|||
public function createToken(array $claims): string |
|||
{ |
|||
$signer = new Sha256(); |
|||
$key = InMemory::plainText($this->secret); |
|||
|
|||
$token = (new Token())->withClaim('id', $claims['id'])->withClaim('username', $claims['username']); |
|||
$token = $token->withExpiresAt(time() + config('jwt.token_ttl')); |
|||
|
|||
return (string) $token->sign($signer, $key); |
|||
} |
|||
|
|||
public function verifyToken(string $token): array |
|||
{ |
|||
$parser = new Parser(); |
|||
$token = $parser->parse((string) $token); |
|||
|
|||
if ($token->verify(new Sha256(), InMemory::plainText($this->secret))) { |
|||
return $token->getClaims(); |
|||
} |
|||
|
|||
return []; |
|||
} |
|||
} |
|||
@ -0,0 +1,8 @@ |
|||
<?php |
|||
return [ |
|||
// jwt 配置信息 |
|||
'jwt' => [ |
|||
'secret' => 'WGl$5uco?)NoSX=&!8*_h&qvgV8010zF', |
|||
'token_ttl' => 3600, |
|||
], |
|||
]; |
|||
Loading…
Reference in new issue