Home Backend Development PHP Tutorial What is JWT? A brief understanding of JWT

What is JWT? A brief understanding of JWT

Oct 10, 2018 pm 05:09 PM
jwt php

This article brings you what is JWT? A simple understanding of JWT has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I have never taken a good look at jwt until I had to do web verification two days ago. A friend recommended jwt to me. Only then did I discover that jwt has been widely used by everyone. It seems I'm a little out. Haha, take advantage of the world to take a good look at this.

JWT (JSON Web Token), as the name suggests, is a token that can be transmitted on the Web. This token is formatted in JSON format. It is an open source standard (RFC 7519) that defines a compact, self-contained way to securely transmit information in JSON format between different entities.

Since many projects now have front-end and back-end separation, restful api mode. Therefore, the traditional session mode cannot meet the authentication requirements. At this time, the role of jwt comes. It can be said that restful api authentication is a good application scenario of jwt.

The following is a small demo

<?php
require_once &#39;src/JWT.php&#39;;
header(&#39;Content-type:application/json&#39;);
//定义Key
const KEY = &#39;dasjdkashdwqe1213dsfsn;p&#39;;

$user = [
    &#39;uid&#39;=>&#39;dadsa-12312-vsd1s1-fsds&#39;,
    &#39;account&#39;=>&#39;daisc&#39;,
    &#39;password&#39;=>&#39;123456&#39;
];
$redis = redis();
$action  =  $_GET[&#39;action&#39;];
switch ($action)
{
    case &#39;login&#39;:
        login();
        break;
    case &#39;info&#39;:
        info();
        break;

}
//登陆,写入验证token
function login()
{
    global  $user;
    $account = $_GET[&#39;account&#39;];
    $pwd = $_GET[&#39;password&#39;];
    $res = [];
    if($account==$user[&#39;account&#39;]&&$pwd==$user[&#39;password&#39;])
    {
        unset($user[&#39;password&#39;]);
        $time = time();
        $token = [
            &#39;iss&#39;=>&#39;http://test.cc&#39;,//签发者
            &#39;iat&#39;=>$time,
            &#39;exp&#39;=>$time+60,
            &#39;data&#39;=>$user
        ];
        $jwt = \Firebase\JWT\JWT::encode($token,KEY);
        $res[&#39;code&#39;] = 200;
        $res[&#39;message&#39;] = &#39;登录成功&#39;;
        $res[&#39;jwt&#39;] = $jwt;

    }
    else
    {
        $res[&#39;message&#39;]= &#39;用户名或密码错误&#39;;
        $res[&#39;code&#39;] = 401;
    }
    exit(json_encode($res));
}





function info()
{
   $jwt = $_SERVER[&#39;HTTP_AUTHORIZATION&#39;] ?? false;
   $res[&#39;code&#39;] = 200;
   if($jwt)
   {
        $jwt = str_replace(&#39;Bearer &#39;,&#39;&#39;,$jwt);
        if(empty($jwt))
        {
            $res[&#39;code&#39;] = 401;
            $res[&#39;msg&#39;] = &#39;You do not have permission to access.&#39;;
            exit(json_encode($res));
        }
        try{
            $token = (array) \Firebase\JWT\JWT::decode($jwt,KEY, [&#39;HS256&#39;]);
            if($token[&#39;exp&#39;]<time())
            {
                $res[&#39;code&#39;] = 401;
                $res[&#39;msg&#39;] = &#39;登录超时,请重新登录&#39;;
            }
            $res[&#39;data&#39;]= $token[&#39;data&#39;];
        }catch (\Exception $E)
        {
            $res[&#39;code&#39;] = 401;
            $res[&#39;msg&#39;] = &#39;登录超时,请重新登录.&#39;;
        }
   }
   else
   {
       $res[&#39;code&#39;] = 401;
       $res[&#39;msg&#39;] = &#39;You do not have permission to access.&#39;;
   }
    exit(json_encode($res));
}



//连接redis
function redis()
{
    $redis = new  Redis();
    $redis->connect(&#39;127.0.0.1&#39;);
    return $redis;
}
Copy after login

This dmeo uses jwt to perform a simple authentication. A php-jwt encryption package is used. https://github.com/firebase/php-jwt

where KEY is the defined private key, which is the sign part in jwt. This must be saved.
The header part of the php-jwt package has been completed for us. The encryption code is as follows

    */
    public static function encode($payload, $key, $alg = &#39;HS256&#39;, $keyId = null, $head = null)
    {
        $header = array(&#39;typ&#39; => &#39;JWT&#39;, &#39;alg&#39; => $alg);
        if ($keyId !== null) {
            $header[&#39;kid&#39;] = $keyId;
        }
        if ( isset($head) && is_array($head) ) {
            $header = array_merge($head, $header);
        }
        $segments = array();
        $segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
        $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
        $signing_input = implode(&#39;.&#39;, $segments);

        $signature = static::sign($signing_input, $key, $alg);
        $segments[] = static::urlsafeB64Encode($signature);

        return implode(&#39;.&#39;, $segments);
    }
Copy after login

It can be seen that the default encryption method is HS256. This is also the reason why jwt is safe. At this stage, HS256 encryption is still very secure.
This package also supports certificate encryption.

This package has completed the encryption and decryption process for us. So we only need to define the poyload part in jwt. That is the token part in the demo. If the encryption is successful, an encrypted JWT string will be obtained. The front end needs to carry this JWT string as authentication next time when requesting the API.
Add Authorization in the header. During server-side verification, this value is obtained to verify the validity of the reply.

The following are some common configurations of poyload

 $token   = [
            #非必须。issuer 请求实体,可以是发起请求的用户的信息,也可是jwt的签发者。
            "iss"       => "http://example.org",
            #非必须。issued at。 token创建时间,unix时间戳格式
            "iat"       => $_SERVER[&#39;REQUEST_TIME&#39;],
            #非必须。expire 指定token的生命周期。unix时间戳格式
            "exp"       => $_SERVER[&#39;REQUEST_TIME&#39;] + 7200,
            #非必须。接收该JWT的一方。
            "aud"       => "http://example.com",
            #非必须。该JWT所面向的用户
            "sub"       => "jrocket@example.com",
            # 非必须。not before。如果当前时间在nbf里的时间之前,则Token不被接受;一般都会留一些余地,比如几分钟。
            "nbf"       => 1357000000,
            # 非必须。JWT ID。针对当前token的唯一标识
            "jti"       => &#39;222we&#39;,
            # 自定义字段
            "GivenName" => "Jonny",
            # 自定义字段
            "name"   => "Rocket",
            # 自定义字段
            "Email"     => "jrocket@example.com",
         
        ];
Copy after login

The configurations contained in it can be configured freely, or you can add some others by yourself. These are commonly used by everyone on the Internet, and it can be said to be a kind of agreement.

The above is the detailed content of What is JWT? A brief understanding of JWT. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1251
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles