Home PHP Framework ThinkPHP Detailed explanation of how to use JWT in thinkphp6.0.7

Detailed explanation of how to use JWT in thinkphp6.0.7

Dec 15, 2021 pm 02:51 PM
jwt

The following thinkphp framework tutorial column will introduce to you how to use JWT in thinkphp6.0.7. I hope it will be helpful to friends in need!

Super detailed explanation of using JWT in thinkphp6.0.7 (including code)

What is JWT

JWT is the abbreviation of json web token. It encrypts user information into the token, and the server does not save any user information. The server verifies the correctness of the token by using the saved key. As long as it is correct, the verification is passed. Token-based authentication can replace the traditional cookie session authentication method.

Session-based login authentication

In traditional user login authentication, because http is stateless, the session method is used. If the user logs in successfully, the server will guarantee a session, and of course will give the client a sessionId. The client will save the sessionId in a cookie, and each request will carry this sessionId.

Cookie session mode is usually stored in memory, and the service will face session sharing problems from single service to multiple services. As the number of users increases, the overhead will increase. This is not the case with JWT. It only requires the server to generate a token, the client to save the token, each request to carry the token, and the server to authenticate and parse it.

JWT consists of three parts: header.payload.signature

Header part:

1

2

3

4

  {

      "alg""HS256",

      "typ""JWT"

    }

Copy after login

1

2

对应base64UrlEncode编码为:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

说明:该字段为json格式。alg字段指定了生成signature的算法,默认值为 HS256,typ默认值为JWT

Copy after login

payload part:

1

2

3

4

5

    {

      "sub""1234567890",

      "name""John Doe",

      "iat": 1516239022

    }

Copy after login

1

2

对应base64UrlEncode编码为:eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ

说明:该字段为json格式,表明用户身份的数据,可以自己自定义字段,很灵活。sub 面向的用户,name 姓名 ,iat 签发时间。例如可自定义示例如下:

Copy after login

1

2

3

4

5

6

7

8

9

  {

        "iss""admin",           //该JWT的签发者

        "sub""www.admin.com",   //面向的用户

        “aud”: "zhangsan",        //接收jwt的一方

        "iat": 1535967430,        //签发时间

        "exp": 1535974630,        //过期时间

        "nbf": 1535967430,        //该时间之前不接收处理该Token 

        "jti""9f10e796726e332cec401c569969e13e"   //该Token唯一标识

    }

Copy after login

signature part:

1

2

3

4

5

    HMACSHA256(

      base64UrlEncode(header) + "." +

      base64UrlEncode(payload),

      123456

    )

Copy after login

1

2

3

4

对应的签名为:keH6T3x1z7mmhKL1T3r9sQdAxxdzB6siemGMr_6ZOwU

 

最终得到的JWT的Token为(header.payload.signature):eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.keH6T3x1z7mmhKL1T3r9sQdAxxdzB6siemGMr_6ZOwU

说明:对header和payload进行base64UrlEncode编码后进行拼接。通过key(这里是123456)进行HS256算法签名。

Copy after login

JWT usage process

1

2

3

4

5

6

7

初次登录:用户初次登录,输入用户名密码

密码验证:服务器从数据库取出用户名和密码进行验证

生成JWT:服务器端验证通过,根据从数据库返回的信息,以及预设规则,生成JWT

返还JWT:服务器的HTTP RESPONSE中将JWT返还

带JWT的请求:以后客户端发起请求,HTTP REQUEST

HEADER中的Authorizatio字段都要有值,为JWT

服务器验证JWT

Copy after login

jwt version

There is jwt in php Multiple versions: I chose the latest version. Don't ask why, when you buy electronic products, you always buy new ones instead of old ones. Looking at the picture, you can see that version 4.1.0 supports more parameters. The specific parameters will be explained below

Detailed explanation of how to use JWT in thinkphp6.0.7
Installing jwt

1. Use composer to install

composer require lcobucci/jwt

2. Download from github

Click here to jump to the github address:https://github.com/lcobucci/jwt

Dependency

1

2

PHP 5.5+

OpenSSL扩展

Copy after login

Use

Parameter explanation

Explain the meaning of the above parameters before using:
Name explanation
iss (issuer) issuer Request entity, can be a request initiator The user's information can also be the issuer of jwt
sub (Subject) Set the subject, similar to the subject when sending an email
aud (audience) The party receiving the jwt
exp (expire) token expiration time
nbf (not before) The current time is before the nbf setting time, the token cannot be used
iat (issued at) token creation time
jti (JWT ID) Set a unique identifier for the current token

How to implement JWT in PHP

I am using PHP 7.3.4, no nonsense, just enter the code, create a new jwt.php, copy and paste as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

<?php /**

 * PHP实现jwt

 */

class Jwt {

  

    //头部

    private static $header=array(

        &#39;alg&#39;=>'HS256'//生成signature的算法

        'typ'=>'JWT'    //类型

    );

  

    //使用HMAC生成信息摘要时所使用的密钥

    private static $key='123456';

  

  

    /**

     * 获取jwt token

     * @param array $payload jwt载荷   格式如下非必须

     * [

     *  'iss'=>'jwt_admin',  //该JWT的签发者

     *  'iat'=>time(),  //签发时间

     *  'exp'=>time()+7200,  //过期时间

     *  'nbf'=>time()+60,  //该时间之前不接收处理该Token

     *  'sub'=>'www.admin.com',  //面向的用户

     *  'jti'=>md5(uniqid('JWT').time())  //该Token唯一标识

     * ]

     * @return bool|string

     */

    public static function getToken(array $payload)

    {

        if(is_array($payload))

        {

            $base64header=self::base64UrlEncode(json_encode(self::$header,JSON_UNESCAPED_UNICODE));

            $base64payload=self::base64UrlEncode(json_encode($payload,JSON_UNESCAPED_UNICODE));

            $token=$base64header.'.'.$base64payload.'.'.self::signature($base64header.'.'.$base64payload,self::$key,self::$header['alg']);

            return $token;

        }else{

            return false;

        }

    }

  

  

    /**

     * 验证token是否有效,默认验证exp,nbf,iat时间

     * @param string $Token 需要验证的token

     * @return bool|string

     */

    public static function verifyToken(string $Token)

    {

        $tokens explode('.'$Token);

        if (count($tokens) != 3)

            return false;

  

        list($base64header$base64payload$sign) = $tokens;

  

        //获取jwt算法

        $base64decodeheader = json_decode(self::base64UrlDecode($base64header), JSON_OBJECT_AS_ARRAY);

        if (empty($base64decodeheader['alg']))

            return false;

  

        //签名验证

        if (self::signature($base64header '.' $base64payload, self::$key$base64decodeheader['alg']) !== $sign)

            return false;

  

        $payload = json_decode(self::base64UrlDecode($base64payload), JSON_OBJECT_AS_ARRAY);

  

        //签发时间大于当前服务器时间验证失败

        if (isset($payload['iat']) && $payload['iat'] > time())

            return false;

  

        //过期时间小宇当前服务器时间验证失败

        if (isset($payload['exp']) && $payload['exp']  time())

            return false;

  

        return $payload;

    }

  

 

    /**

     * base64UrlEncode   https://jwt.io/  中base64UrlEncode编码实现

     * @param string $input 需要编码的字符串

     * @return string

     */

    private static function base64UrlEncode(string $input)

    {

        return str_replace('='''strtr(base64_encode($input), '+/''-_'));

    }

  

    /**

     * base64UrlEncode  https://jwt.io/  中base64UrlEncode解码实现

     * @param string $input 需要解码的字符串

     * @return bool|string

     */

    private static function base64UrlDecode(string $input)

    {

        $remainder strlen($input) % 4;

        if ($remainder) {

            $addlen = 4 - $remainder;

            $input .= str_repeat('='$addlen);

        }

        return base64_decode(strtr($input'-_''+/'));

    }

  

    /**

     * HMACSHA256签名   https://jwt.io/  中HMACSHA256签名实现

     * @param string $input 为base64UrlEncode(header).".".base64UrlEncode(payload)

     * @param string $key

     * @param string $alg   算法方式

     * @return mixed

     */

    private static function signature(string $input, string $key, string $alg 'HS256')

    {

        $alg_config=array(

            'HS256'=>'sha256'

        );

        return self::base64UrlEncode(hash_hmac($alg_config[$alg], $input$key,true));

    }

}

  

    //***********测试和官网是否匹配begin****************************

    $payload=array('sub'=>'1234567890','name'=>'John Doe','iat'=>1516239022);

    $jwt=new Jwt;

    $token=$jwt->getToken($payload);

    echo "<pre class="brush:php;toolbar:false">";

    echo $token;

     

    //对token进行验证签名

    $getPayload=$jwt->verifyToken($token);

    echo "<br><br>";

    var_dump($getPayload);

    echo "<br><br>";

    //测试和官网是否匹配end

     

     

    //自己使用测试begin

    $payload_test=array('iss'=>'admin','iat'=>time(),'exp'=>time()+7200,'nbf'=>time(),'sub'=>'www.admin.com','jti'=>md5(uniqid('JWT').time()));;

    $token_test=Jwt::getToken($payload_test);

    echo "<pre class="brush:php;toolbar:false">";

    echo $token_test;

     

    //对token进行验证签名

    $getPayload_test=Jwt::verifyToken($token_test);

    echo "<br><br>";

    var_dump($getPayload_test);

    echo "<br><br>";

    //自己使用时候end

Copy after login

The above is the detailed content of Detailed explanation of how to use JWT in thinkphp6.0.7. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JWT and JWE for API authentication and encryption in PHP How to use JWT and JWE for API authentication and encryption in PHP Jun 17, 2023 pm 02:42 PM

With the development of the Internet, more and more websites and applications need to provide API interfaces for data interaction. In this case, API authentication and encryption become very important issues. As a popular authentication and encryption mechanism, JWT and JWE are increasingly used in PHP. Well, this article will explain how to use JWT and JWE for API authentication and encryption in PHP. Basic concepts of JWT JWT stands for JSONWe

How to use ThinkPHP6 for JWT authentication? How to use ThinkPHP6 for JWT authentication? Jun 12, 2023 pm 12:18 PM

JWT (JSONWebToken) 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

OAuth in PHP: Create a JWT authorization server OAuth in PHP: Create a JWT authorization server Jul 28, 2023 pm 05:27 PM

OAuth in PHP: Creating a JWT authorization server With the rise of mobile applications and the trend of separation of front-end and back-end, OAuth has become an indispensable part of modern web applications. OAuth is an authorization protocol that protects users' resources from unauthorized access by providing standardized processes and mechanisms. In this article, we will learn how to create a JWT (JSONWebTokens) based OAuth authorization server using PHP. JWT is a type of

Analysis of secure JWT token generation and verification technology in PHP Analysis of secure JWT token generation and verification technology in PHP Jul 01, 2023 pm 06:06 PM

Analysis of Secure JWT Token Generation and Verification Technology in PHP With the development of network applications, user authentication and authorization are becoming more and more important. JsonWebToken (JWT) is an open standard (RFC7519) for securely transmitting information in web applications. In PHP development, it has become a common practice to use JWT tokens for user authentication and authorization. This article will introduce secure JWT token generation and verification technology in PHP. 1. Basic knowledge of JWT in understanding how to generate and

A complete guide to implementing login authentication in Vue.js (API, JWT, axios) A complete guide to implementing login authentication in Vue.js (API, JWT, axios) Jun 09, 2023 pm 04:04 PM

Vue.js is a popular JavaScript framework for building dynamic web applications. Implementing user login authentication is one of the necessary parts of developing web applications. This article will introduce a complete guide to implementing login verification using Vue.js, API, JWT and axios. Creating a Vue.js Application First, we need to create a new Vue.js application. We can create a Vue.js application using VueCLI or manually. Install axiosax

In-depth analysis of the principles and usage of JWT (JSON Web Token) In-depth analysis of the principles and usage of JWT (JSON Web Token) Jan 10, 2023 am 10:55 AM

This article brings you relevant knowledge about JWT. It mainly introduces what is JWT? What is the principle and usage of JWT? For those who are interested, let’s take a look below. I hope it will be helpful to everyone.

How SpringBoot combines JWT to implement login permission control How SpringBoot combines JWT to implement login permission control May 20, 2023 am 11:01 AM

First we need to import the jwt package used: io.jsonwebtokenjjwt0.8.0com.auth0java-jwt3.2.0 1. Prepare LoginUser (store login user information) and JwtUserLoginUser.javapublicclassLoginUser{privateIntegeruserId;privateStringusername;privateStringpassword;privateStringrole;generate getters and setters ...}JwtUser.javaimp

Golang development: Implementing JWT-based user authentication Golang development: Implementing JWT-based user authentication Sep 20, 2023 am 08:31 AM

Golang development: Implementing JWT-based user authentication With the rapid development of the Internet, user authentication has become a crucial part of web applications. The traditional cookie-based authentication method has gradually been replaced by the JWT (JSONWebToken)-based authentication method. JWT is a lightweight authentication standard that allows the server to generate an encrypted token and send the token to the client. The client puts the token into Authori when sending a request.

See all articles