From f2ba91ced90a35d3237b7e94017b4f837ff77240 Mon Sep 17 00:00:00 2001 From: "453530270@qq.com" Date: Mon, 7 Oct 2024 20:50:14 +0800 Subject: [PATCH] =?UTF-8?q?jwt=E6=9C=8D=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/middleware.php | 2 ++ app/api/middleware/JWTAuth.php | 36 ++++++++++++++++++++++++++++++ app/api/service/JWTService.php | 40 ++++++++++++++++++++++++++++++++++ config/jwt.php | 8 +++++++ 4 files changed, 86 insertions(+) create mode 100644 app/api/middleware/JWTAuth.php create mode 100644 app/api/service/JWTService.php create mode 100644 config/jwt.php diff --git a/app/api/middleware.php b/app/api/middleware.php index 3edd6fb..576c8bd 100644 --- a/app/api/middleware.php +++ b/app/api/middleware.php @@ -10,5 +10,7 @@ return [ // Csrf安全校验 // \app\api\middleware\CsrfMiddleware::class, + // jwt 中间件 + \app\api\middleware\JWTAuth::class, ]; \ No newline at end of file diff --git a/app/api/middleware/JWTAuth.php b/app/api/middleware/JWTAuth.php new file mode 100644 index 0000000..436cfee --- /dev/null +++ b/app/api/middleware/JWTAuth.php @@ -0,0 +1,36 @@ +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); + } +} \ No newline at end of file diff --git a/app/api/service/JWTService.php b/app/api/service/JWTService.php new file mode 100644 index 0000000..cab5cb7 --- /dev/null +++ b/app/api/service/JWTService.php @@ -0,0 +1,40 @@ +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 []; + } +} \ No newline at end of file diff --git a/config/jwt.php b/config/jwt.php new file mode 100644 index 0000000..70a5f5c --- /dev/null +++ b/config/jwt.php @@ -0,0 +1,8 @@ + [ + 'secret' => 'WGl$5uco?)NoSX=&!8*_h&qvgV8010zF', + 'token_ttl' => 3600, + ], +]; \ No newline at end of file