JWT can be well applied to restful api mode

What is JWT
JWT (JSON Web Token), as the name implies, 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.

Now, many project models are basically front-end separation and restful api models.  Therefore, the traditional session mode cannot meet the authentication requirements, and jwt appears at this time.  It can be said that the restful api mode is a good application scenario for jwt.

JWT parameter explanation
name Explanation
iss (issuer) The issuer request entity, which can be the information of the user who initiated the request, or 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 time set by nbf, the token cannot be used
iat (issued at) token creation time
jti (JWT ID) Set a unique mark for the current token

Next we look at an example

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

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

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

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

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

//连接redis
function redis()
{
  $redis = new Redis();
  $redis->connect('127.0.0.1');
  return $redis;
}

This example uses jwt to do a simple authentication. A php-jwt encryption package is used. The link is as follows:
https://github.com/firebase/php-jwt, where KEY is the defined private key, which is the sign part in jwt. This must be kept. 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 = 'HS256', $keyId = null, $head = null)
{
  $header = array('typ' => 'JWT''alg' => $alg);
  if ($keyId !== null) {
    $header['kid'] = $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('.', $segments);

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

  return implode('.', $segments);
}


可以看出默认的加密的方式是HS256。这也是说jwt安全的原因。现阶段HS256加密还是很安全的。
这个包里面也支持证书加密。

加密解密的过程这个包已经帮我们完成了。所以我们只需要定义jwt中的 poyload部分就可以了。也就是demo里面的token部分。加密成功会得到一个加密的Jwt字符串,下次前端在请求api的时候需要携带这个jwt字符串作为认证。
在header头里面增加Authorization。在服务端验证的时候回通过取得这个值来验证回话的有效。

下面是poyload的一些常用配置

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

];


里面包含的配置可以自由配置,也可以自己添加一些其他的。这些都是网上大家常用的,可以说是一种约定吧。

注意事项
关于jwt的使用大概就是这些。上面的代码在你使用的时候可能会出现两个问题:
1、命名空间错误
解决:不使用命名空间的话,使用require引入文件。如果使用命名空间出现错误,请检查命名空间的路径。

2、生成的token是一个对象
解决:(string)$token 将token强转成string


Guess you like

Origin blog.51cto.com/15127568/2667069