关于JWT鉴权方案

作者: 分类: php 时间: 2022-02-06 评论: 暂无评论

git:https://github.com/lcobucci/jwt

composer require lcobucci/jwt 3.4.6

jwt鉴权配置confi.php

  
'jwt_expire_time'        => 3600*24*10,                //token过期时间 默认10天
'jwt_secrect'            => '86L$1Q1@*##hgh!#@BG',    //签名秘钥
'jwt_iss'                => 'HDGHWDDAW@#8dj29009',    //发送端
'jwt_aud'                => '66dGzhw@dj@3#2ddaQ@',    //接收端
'jwt_refresh_expire_time'=> 3600*24*30,                //refresh_token过期时间 默认30天

Jwt.php 模块

 <?php 

namespace app\api\controller;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;

class Jwt{
    

private static $instance = null;

private $token;
private $decodeToken;
private $iss;  //发送数据端
private $aud;      //数据接收
private $uid; //用户UID
private $secrect;
private $expTime;


public static function getInstance(){
    if(is_null(self::$instance)){
        self::$instance = new self();
    }
    return self::$instance;
}

private function __construct(){
    
}

public function getToken(){
    return (string)$this->token;
}

public function setToken($token){
    $this->token = $token;
    return $this;
}

public function setUid($uid){
    $this->uid = $uid;
    return $this;
}    

public function getUid(){
    return $this->uid;
}

public function setExpTime($expTime){
    $this->expTime = $expTime;
    return $this;        
}    

public function setIss($iss){
    $this->iss = $iss;
    return $this;
}

public function setAud($aud){
    $this->aud = $aud;
    return $this;
}

public function setSecrect($secrect){
    $this->secrect =md5($this->uid.$secrect);
    return $this;
}

public function encode(){
    $time = time();
    $this->token = (new Builder())->setHeader('alg','HS256')
        ->setIssuer($this->iss)
        ->setAudience($this->aud)
        ->setIssuedAt($time)
        ->setExpiration($time+$this->expTime)
        ->set('uid',$this->uid)
        ->sign(new Sha256(),$this->secrect)
        ->getToken();
    
    return $this;
}


public function decode(){
    
    try{
        $this->decodeToken = (new Parser())->parse((string) $this->token); // Parses from a string
        $this->uid = $this->decodeToken->getClaim('uid');
        return $this->decodeToken;
    }catch (RuntimeException $e){
        throw new \Exception($e->getMessage());
    }
    
}
    
public function validate(){
    $data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
    $data->setIssuer($this->iss);
    $data->setAudience($this->aud);
    $data->setId($this->uid);
    
    return $this->decode()->validate($data);
}


public function verify(){
    return $this->decode()->verify(new Sha256(),$this->secrect);
}

}

生成token

$jwt = Jwt::getInstance();
    $jwt->setIss(config('my.jwt_iss'))
           ->setAud(config('my.jwt_aud'))
            ->setSecrect(config('my.jwt_secrect'))
            ->setExpTime(config('my.jwt_expire_time'))
            ->setUid($uid);
    $token = $jwt->encode()->getToken();
      

中间件鉴权

<?php
namespace app\api\middleware;
use app\api\controller\Jwt;
class JwtAuth
{
    public function handle($request, \Closure $next)
    {
        $token = $request->header('Authorization');
        if (!$token) {
            return json(['status' => config('my.jwtExpireCode'), 'msg' => '请重新登录']);
        }
        if (count(explode('.', $token)) <> 3) {
            return json(['status' => config('my.jwtExpireCode'), 'msg' => '请重新登录']);
        }
        $jwt = Jwt::getInstance();
        $uid = $jwt->decode()->getClaim('uid');
        $jwt->setIss(config('my.jwt_iss'))
            ->setAud(config('my.jwt_aud'))
            ->setUid($uid)
            ->setSecrect(config('my.jwt_secrect'))
            ->setToken($token);

        if ($jwt->decode()->getClaim('exp') < time()) {
            return json(['status' => config('my.jwtExpireCode'), 'msg' => '请重新登录']);
        }
        if ($jwt->validate() && $jwt->verify()) {
            $request->uid = $uid;
            return $next($request);
        } else {
            return json(['status' => config('my.jwtExpireCode'), 'msg' => '请重新登录']);
        }

    }
}
标签: none

订阅本站(RSS)