Browse Source

jwt服务

master
xyiege 1 year ago
parent
commit
f2ba91ced9
  1. 2
      app/api/middleware.php
  2. 36
      app/api/middleware/JWTAuth.php
  3. 40
      app/api/service/JWTService.php
  4. 8
      config/jwt.php

2
app/api/middleware.php

@ -10,5 +10,7 @@ return [
// Csrf安全校验 // Csrf安全校验
// \app\api\middleware\CsrfMiddleware::class, // \app\api\middleware\CsrfMiddleware::class,
// jwt 中间件
\app\api\middleware\JWTAuth::class,
]; ];

36
app/api/middleware/JWTAuth.php

@ -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);
}
}

40
app/api/service/JWTService.php

@ -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 [];
}
}

8
config/jwt.php

@ -0,0 +1,8 @@
<?php
return [
// jwt 配置信息
'jwt' => [
'secret' => 'WGl$5uco?)NoSX=&!8*_h&qvgV8010zF',
'token_ttl' => 3600,
],
];
Loading…
Cancel
Save