What is JWT? A brief understanding of JWT

不言
Release: 2023-04-04 09:30:01
forward
5647 people have browsed it

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!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template