How to use Hyperf framework for JWT authentication
How to use the Hyperf framework for JWT authentication
Introduction:
Hyperf is a high-performance coroutine framework based on Swoole, providing rich functions and flexibility scalability. JWT (JSON Web Token) is an open standard for authenticating and transmitting information. In this article, we will introduce how to use JWT authentication in the Hyperf framework and provide specific code examples.
1. Install dependency packages
First, we need to install hyperf/jwt and lcobucci/jwt dependency packages. It can be installed through Composer, open the terminal and run the following command:
composer require hyperf/jwt lcobucci/jwt
2. Configure authentication information
In the Hyperf framework, we need to configure the relevant information required for JWT authentication. Open the config/autoload/jwt.php
file and add the following configuration items:
<?php return [ 'default' => [ 'valid_seconds' => env('JWT_VALID_SECONDS', 3600), // Token有效期 'secret' => env('JWT_SECRET', 'your-secret-key'), // 对称加密密钥 'refresh_ttl' => env('JWT_REFRESH_TTL', 20160), // Token刷新有效期 'password_key' => env('JWT_PASSWORD_KEY', 'password'), // 密码字段名称 'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true), // Token黑名单启用 'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 60), // Token宽限期 'claim' => [], // 自定义Claims ], ];
3. Generate and parse JWT Token
First, we need to generate a JWT Token. Introduce the HyperfJwtJwt
class into the controller and generate Token through the make()
method. The sample code is as follows:
<?php declare(strict_types=1); namespace AppController; use HyperfDiAnnotationInject; use PsrHttpMessageResponseInterface; class AuthController extends AbstractController { /** * @Inject * @var HyperfJwtJwt */ private $jwt; public function login(): ResponseInterface { // 对用户进行验证,验证通过后生成Token $userId = 1; $token = $this->jwt->make(['user_id' => $userId]); return $this->response->json([ 'token' => $token->toString(), 'expires_at' => $token->getClaim('exp'), ]); } }
Next, we need to verify the JWT Token in the middleware and parse out the user information. Introduce the HyperfJwtMiddlewareJwtMiddleware
class into the middleware, and use the handle()
method for verification and parsing. The sample code is as follows:
<?php declare(strict_types=1); namespace AppMiddleware; use HyperfDiAnnotationInject; use HyperfHttpServerContractRequestInterface; use HyperfHttpServerContractResponseInterface as HttpResponse; use HyperfUtilsContext; use HyperfUtilsStr; use HyperfJwtExceptionTokenValidException; use HyperfJwtJwtInterface; use PsrContainerContainerInterface; class JwtMiddleware { /** * @Inject * @var HyperfJwtJwt */ private $jwt; /** * @var JwtInterface */ private $jwtFactory; /** * @var RequestInterface */ private $request; /** * @var HttpResponse */ private $response; public function __construct(ContainerInterface $container, JwtInterface $jwt, RequestInterface $request, HttpResponse $response) { $this->jwtFactory = $jwt; $this->request = $request; $this->response = $response; } public function handle($request, Closure $next) { $token = Str::replaceFirst('Bearer ', '', $this->request->header('Authorization')); // 从Header中获取Token if (empty($token)) { throw new TokenValidException('Token not provided'); } try { $token = $this->jwtFactory->parse($token); // 解析Token $claims = $token->claims(); // 获取Token中的声明 Context::set('user_id', $claims->get('user_id')); // 设置用户ID到上下文 } catch (TokenValidException $e) { throw new TokenValidException('Invalid token', $e->getCode(), $e); } return $next($request); } }
4. Use middleware for authentication
Use middleware in routing for JWT authentication. Open the config/routes.php
file and add the following routing and middleware configuration items:
<?php use AppMiddlewareJwtMiddleware; Router::addGroup('/api', function () { Router::post('/login', 'AppControllerAuthController@login'); // 需要认证的路由 Router::addGroup('/auth', function () { Router::get('/info', 'AppControllerAuthController@info'); }, ['middleware' => [JwtMiddleware::class]]); });
In the above example, AppControllerAuthController@info
requires authentication interface. This interface can only be successfully accessed when carrying a valid JWT Token.
Conclusion:
This article introduces how to use the Hyperf framework for JWT authentication and provides relevant configuration and code examples. Through JWT authentication, we can achieve higher security and user verification functions in the Hyperf framework. I hope this article will be helpful to you when using the Hyperf framework for JWT authentication.
The above is the detailed content of How to use Hyperf framework for JWT authentication. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
