jwt token verification

<?php
namespace app\index\controller;

use think\Db;
use think\Session;
use think\Controller;


//跨域处理
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Method:POST,GET,OPTIONS');
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Credentials:true");
header("Access-Control-Allow-Methods:*");
header("Access-Control-Allow-Headers:Content-Type,Access-Token");
header("Access-Control-Expose-Headers:*");

class Message extends Controller{
// head 
Private header static $ = Array (
'ALG' => 'HS256', the signature generation algorithm //
'typ' => 'JWT' // type
);

// used when using the generated message digest HMAC key
Private key static $ = '123456';


/ **
* Get token JWT
* @param Array $ JWT load payload format not necessarily
* [
* 'ISS' => 'jwt_admin', // the issuer JWT
* 'iat' => time () , // issued time
* 'exp' => time ( ) + 7200, // expiration
* 'nbf' => time ( ) + 60, the process does not receive before that time // the Token
* 'Sub' => 'www.admin.com', for the user //
* '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;

// Get jwt algorithm
$ base64decodeheader = json_decode (self :: base64UrlDecode ($ base64header), true); // JSON_OBJECT_AS_ARRAY corresponds to true
IF (empty ($ base64decodeheader [ 'ALG']))
return false;

// signature verification
if (self :: signature ($ base64header $ base64payload, self :: $ key, $ base64decodeheader [ 'alg']) == $ sign). '.'.! {
return to false;
}

$ = payload of json_decode (Self :: base64UrlDecode ($ base64payload), to true);

// issued time is greater than the current time authentication server fails
if (isset ($ payload [ ' iat']) && $ payload [ 'iat ']> time ()) {
return to false;
}

// expiration time server current time authentication failed Xiaoyu
IF (isset ($ payload [ 'exp']) && payload $ [ 'exp'] <Time ()) {
return to false;
}

// not the reception processing of the Token before nbf time
if (isset ($ payload [ ' nbf ']) && payload $ [' NBF ']> Time ()) {
return to false;
}
return $ payload;
}


/ **
* coding base64UrlEncode https://jwt.io/ in base64UrlEncode
* @param string $ input required encoded string
* @return string
* /
Private static function base64UrlEncode (string $ INPUT)
{
return str_replace ( '=', '', strtr (the base64_encode ($ INPUT), '+ /', '-_'));
}

/ **
* base64UrlEncode HTTPS: // jwt.io / decoder implemented in base64UrlEncode
* @param string $ input string to be decoded
* @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));
}

//获取token
public function Token($array){
$token_test = self::getToken($array);
return $token_test;
}

//验证token
public function token_yz($token_test){
//对token进行验证签名
$getPayload_test=self::verifyToken($token_test);
return $getPayload_test;
}

// user logs simple simulation example 
public function the Login () {
$ = Request info () -> param ();

IF (isset ($ info [ 'name']) or isset ($ info [ 'password'])!! ) {
return json_encode (Array (
'code' => 0,
'MSG' => "missing argument"
)); Die ();
}

// verify the existence of
$ user = Db :: table ( " user_login") -> WHERE ([ 'name' => $ info [ 'name'], 'password' => MD5 ($ info [ 'password']), 'is_delete' => 0]) -> Find ();

IF ($ User ) {
// get the generated token (parameter) the effective time (36,600 seconds)
$ token = $ this-> the token (Array ( 'UID' => $ User [ 'ID'], 'name' => $ User [ ' name '],' exp '= > time () + 3600,' nbf '=>time(),'jti'=>md5(uniqid('JWT').time())));

return json_encode(array(
'uid' => $user['id'],
'name' => $ User [ 'name'],
'token' => $ token
)); Die ();
}

return json_encode (Array (
'code' => 0,
'MSG' => "login or password bad "
)); Die ();
}  





Guess you like

Origin www.cnblogs.com/dream-meng/p/11809510.html