当前位置:网站首页>Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction

Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction

2022-07-04 00:42:00 Game programming

1. introduce php-jwt package

composer require firebase/php-jwt

2. Code
Controller files :app\business\Jwt.php

<?phpnamespace app\busines;use Firebase\JWT\JWT;use Firebase\JWT\Key;class JWT{    public function add(){       // Modify your key as needed         $key = "example_key";        // Encrypt data , You can customize deletion         $payload = array(        "iss" => "http://example.org",        "aud" => "http://example.com",        "iat" => 1356999524,        "nbf" => 1357000000,        "uid" => $uid      );        /**        * IMPORTANT:        * You must specify supported algorithms for your application. See        * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40        * for a list of spec-compliant algorithms.        */        $jwt = JWT::encode($payload, $key, 'HS256');        return $jwt;        $decoded = JWT::decode($jwt, new Key($key, 'HS256'));        // It's not necessary         print_r($decoded);        $decoded_array = (array) $decoded;    }}

Use... In wechat applets jwt--token
be based on token( token ) User authentication steps :
1、 Users enter their login information
2、 The server verifies whether the information is correct , And return the signed token
3、token Stored on the client , For example, being local storage or cookie in ( The applet is stored in the cache )
4、 After that HTTP Requests will token Add to the request header

// Take it out of the cache tokenconst token = wx.getStorageSync('token') wx.request({      url: '',      data:{      },      // request header Head carrying token      header: {        'token':  token      },      success:(res)=>{        console.log(res);        this.setData({          bargain:res.data.data        })      }    })

5、 Server decoding JWT, And if the token is valid , Then accept the request
6、 Once the user logs off , The token will be destroyed on the client , The key to not having to interact with the server is , Tokens are stateless . The back-end server does not need to save tokens or current session The record of .

Applet header add to touken There are two ways

1、

header:{              // Wechat applet is stored token            'Authorization': token //token It is extracted from the cache           },

obtain

$token = $_SERVER['HTTP_AUTHORIZATION'];

2、

header: {        'token':  token, // request header Head carrying token      }

obtain

$token = $_SERVER['HTTP_TOKEN'];

The following code can be ignored
thinkphp6 jwt application token Middleware validation _ Zhongzhong's blog -CSDN Blog
TP6 Study - jwt + Wechat applet verification token_ Mr. Feng -CSDN Blog
Integrate JWT- Realization token User authentication mechanism · tp6 - ThinkPHP6.0 Enterprise best practices · Look at the clouds

<?phpnamespace app\lib;use Firebase\JWT\ExpiredException;use Firebase\JWT\JWT as JWTUtil;use Firebase\JWT\Key;use think\Exception;class JWT{    /**     *  according to json web token Set the rule generation token     * @return \think\response\Json     */    public static function createjwt($user_id)    {        //jwt Issuing key for , verification token It needs to be used         $key = md5(env('TOKEN.key'));        // The issuance of time         $time = time();        // Expiration time         $expire = $time + 14400;        $token = array(            "user_id" => "$user_id",            // Issuing organization             "iss" => env('TOKEN.iss'),            // Issued by             "aud" => env('TOKEN.aud'),            "iat" => $time,            "nbf" => $time,            "exp" => $expire        );        return json(JWTUtil::encode($token, $key,'HS256'));    }    /**     *  verification token     * @return \think\response\Json     */    public static function verifyjwt($jwt)    {        // see token Is it overdue ( It will be manually expired in the logic of log out )//        $deleteToken=cache("delete_token")?:[];//        if (in_array($jwt, $deleteToken)) {//            throw new ExpiredException("token Be overdue ","400");//        }        if (!empty(cache('delete_token')) && in_array($jwt, cache("delete_token"))) {            throw new ExpiredException("token Be overdue ","400");        }        //jwt Issuing key for , verification token It needs to be used         $key = md5(env('TOKEN.key'));        try {            $jwtAuth = json_encode(JWTUtil::decode($jwt, new Key($key,'HS256')));            $authInfo = json_decode($jwtAuth, true);            if (!$authInfo['user_id']) {                throw new Exception(' user ID non-existent ','500');            }            // Check the signature and return to             return json($authInfo);        } catch (ExpiredException $e) {            throw new Exception('token Be overdue ','500');        } catch (\Exception $e) {            throw new Exception($e->getMessage(),'500');        }    }    // Get... From the requested information token token     public static function getRequestToken()    {        if (empty($_SERVER['HTTP_AUTHORIZATION'])) {            return false;        }        $header = $_SERVER['HTTP_AUTHORIZATION'];        $method = 'bearer';        // Remove token There may be bearer identification         return trim(str_ireplace($method, '', $header));    }}

3. modify public/.htaccess file , adopt apache rewrite , Handle HTTP In the request Authorization Field
( Don't deal with ,php Can't receive HTTP_AUTHORAZATION Field information )

RewriteCond %{HTTP:Authorization} ^(.+)$RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

4. route :app\api\route\api.php

<?phpuse think\facade\Route;Route::rule("jwt","jwt/createjwt","get");Route::rule("verifyjwt","jwt/verifyjwt","post");

5. front end : Deposit in

$token=JWT::createjwt($loginData['u_id'])->getData();

6. front end : Take out 、 The destruction

public function login(){    // Take out Token value ( In the header)    // Empty token   Empty the token Deposited in the cache , When used again , Will read the cache for judgment     $token=JWT::getRequestToken();    //try {        // check token        //$data=app\lib\JWT::verifyjwt($token);    //}catch (\Exception $exception){        //return fail($exception->getMessage());    //}    // Check to see if there is delete_token This key     $delete_token = cache('delete_token') ?: [];    // Put this token Value in delete_token Array     $delete_token[] = $token;    // Push the array back into the cache     cache('delete_token', $delete_token, 86400);    // Destroy succeeded     return success(' Destroy succeeded ');}

7. Verify success

// Take out token$token=JWT::getRequestToken(); try {       // check token       $data=JWT::verifyjwt($token);     }catch (\Exception $exception){      return fail($exception->getMessage());     }dd($data);

8. The effect is shown in the figure

ThinkPHP6 Integrate JWT Methods and generation and removal destruction details - The first 1 Zhang
ThinkPHP6 Integrate JWT Methods and generation and removal destruction details - The first 2 Zhang

author : Yuan rises and falls

this paper [ ThinkPHP6 Integrate JWT Methods and generation and removal destruction details ] Included in Game programming ️ - PHP, A game development favorite ~

If the picture is not displayed for a long time , Please use Chrome browser .

原网站

版权声明
本文为[Game programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202142008103230.html

随机推荐