Home  >  Article  >  PHP Framework  >  How to use ThinkPHP6 for JWT authentication?

How to use ThinkPHP6 for JWT authentication?

王林
王林Original
2023-06-12 12:18:102485browse

JWT (JSON Web Token) is a lightweight authentication and authorization mechanism that uses JSON objects as security tokens to securely transmit user identity information between multiple systems. ThinkPHP6 is an efficient and flexible MVC framework based on PHP language. It provides many useful tools and functions, including JWT authentication mechanism. In this article, we will introduce how to use ThinkPHP6 for JWT authentication to ensure the security and reliability of web applications.

  1. Installing and Configuring the JWT Extension

First, we need to install the JWT extension in our application. It can be installed by adding dependencies in the composer.json file:

{
    "require": {
        "firebase/php-jwt": "^5.0.0"
    }
}

Then run the following command to install it:

composer install

After the installation is complete, we need to configure JWT in the configuration file. Create the jwt.php file in the config directory and add the following content:

<?php
return [
    'key' => 'your-secret-key',
    'alg' => 'HS256',
    'exp' => 7200, // token过期时间,单位秒
];

where "key" is a string used to generate the signature key of the JWT token, and "alg" is the JWT signature algorithm Name, we can choose algorithms such as "HS256", "HS512", "RS256", etc. "exp" is the expiration time of the JWT token, calculated in seconds.

  1. Implementing JWT authentication controller

Next, we need to create a JWT authentication controller to implement JWT authentication. Create the AuthController.php file in the app/controller directory and add the following content:

<?php
namespace appcontroller;

use FirebaseJWTJWT;
use thinkacadeDb;

class AuthController
{
    public function login()
    {
        //在这里处理用户登陆逻辑
        //...
        
        //登陆成功后生成JWT token并返回给客户端

        $secretKey = config('jwt.key'); // 获取JWT生成签名的密钥
        $alg = config('jwt.alg'); // 获取JWT加密算法
        $payload = [
            'sub' => $user->id, // 存储用户ID
            'exp' => time() + config('jwt.exp'), // 设定过期时间
        ];
        $jwt = JWT::encode($payload, $secretKey, $alg); // 生成JWT令牌
        return ['token' => $jwt]; // 返回JWT Token给客户端
    }

    public function dashboard()
    {
        //检查请求中的JWTToken是否有效,并返回用户信息

        $jwtToken = request()->header('Authorization'); // 获取JWT Token
        if (!$jwtToken) {
            // 如果token不存在,直接返回错误信息
            return ['msg' => '未验证身份,请先登录'];
        }
        $jwtInfo = JWT::decode($jwtToken, config('jwt.key'), [config('jwt.alg')]); // 使用JWT解密Token
        $userId = $jwtInfo->sub; // 获取token中存储的用户ID,用来查询用户信息
        $user = Db::table('users')->where('id', $userId)->find(); // 查询用户信息
        if (!$user) {
            // 用户不存在,直接返回错误信息
            return ['msg' => '用户不存在'];
        }
        // 返回用户信息
        return ['username' => $user['username'], 'email' => $user['email']];
    }
}

In the above controller code, we have implemented two functions: one is user login, the other is to obtain user information . During the login process, we generate a JWT token and return it to the client for authentication in subsequent requests. In the dashboard method, we check whether the Authorization header of the request contains the JWT token, and use the JWT to decrypt the token and verify whether the user's identity is valid.

  1. Add JWT authentication middleware

Finally, we need to add a JWT authentication middleware to the application to protect the API interface that requires authentication. Create the JwtAuth.php file in the app/middleware directory and add the following content:

<?php
namespace appmiddleware;

use FirebaseJWTJWT;
use thinkacadeConfig;

class JwtAuth
{
    public function handle($request, Closure $next)
    {
        //检查请求中的JWTToken是否有效

        $jwtToken = $request->header('Authorization'); // 获取JWT Token
        if (!$jwtToken) {
            // 如果token不存在,直接返回错误信息
            return response(['msg' => '未授权的API请求!'], 401);
        }
        try {
            $jwtInfo = JWT::decode($jwtToken, Config::get('jwt.key'), [Config::get('jwt.alg')]); // 使用JWT解密Token
            $request->jwtInfo = $jwtInfo; // 将解密后的JWT信息存储在请求对象中,后续控制器可以使用
            return $next($request); // 继续后续请求处理
        } catch (Exception $e) {
            // JWT Token过期或者解密失败,返回错误信息
            return response(['msg' => 'JWT Token无效或已过期!'], 401);
        }
    }
}

In the above code, we checked whether the Authorization header of the request contains a valid JWT token. If the JWT token is invalid or has expired, we return an Unauthorized HTTP response, otherwise we continue subsequent request processing and store the JWT token's information in the request object for use by subsequent controllers.

Finally, we need to use JWT authentication middleware in the application's routing to protect the API interface that requires authentication. For example, we add the following code in the routes/api.php file:

<?php
use appmiddlewareJwtAuth;

// 需要JWT认证的API接口
Route::get('dashboard', 'AuthController@dashboard')->middleware(JwtAuth::class);

In the above code, we have protected the dashboard method using the JwtAuth middleware to ensure that there are only requests with valid JWT tokens to access it.

Conclusion

In this article, we introduced how to use ThinkPHP6 for JWT authentication to ensure the security and reliability of web applications. We first installed and configured the JWT extension, then implemented the JWT authentication controller and JWT authentication middleware, and finally used the JWT authentication middleware in the routing of the application to protect the API interfaces that require authentication. Through these steps, we can easily implement the JWT authentication mechanism in ThinkPHP6 applications to ensure the security and reliability of web applications.

The above is the detailed content of How to use ThinkPHP6 for JWT authentication?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn