jwt

Posted huliangqing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jwt相关的知识,希望对你有一定的参考价值。

class BaseApi extends Controller
{
    protected $userId = 0;
    protected $userName = ‘‘;
    protected $noLoginAction = [];
    protected $endTIme = 30000000;

    public function _initialize()
    {
        parent::_initialize();
        $sign = Request::instance()->header(‘sign‘); 
        $token = Request::instance()->header(‘token‘); 
        $requestTime = Request::instance()->header(‘requestTime‘); 
        if(!$sign || !$requestTime ){
            $this ->error(‘sign or requestTime not found‘);
        }
        if(md5($requestTime) != $sign){
            $this ->error(‘Sign verification failed‘);
        }
        if($requestTime < (time()-$this ->endTIme)){
            $this ->error(‘request timeout‘);
        }

        $controller = Request::instance()->controller() ;
        $action = Request::instance()->action() ;
         
        //token : eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9tbC5jbiIsImF1ZCI6Imh0dHA6XC9cL21sLmNuIiwiaWF0IjoxNTg1NjY4NzIxLCJuYmYiOjE1ODU2Njg3MjEsImV4cCI6MTU5NDMwODcyMSwiZGF0YSI6IntcInVzZXJfaWRcIjoxLFwidXNlcl9uYW1lXCI6XCJ0ZXN0TmFtZVwifSJ9.XrfKRfCGIxmc4A5BF2fSwqqhLVC86jhxWh9yjvOzw_A

         
        if(!in_array($action , $this ->noLoginAction )){
            if(!$token) $this ->error(‘Please login again‘,‘‘,300);
        }

        if($token){
            $token_info = $this ->checkToken($token);
            $user_info = json_decode($token_info[‘data‘] ,true);
            $this ->userId = $user_info[‘user_id‘];
            $this ->userName = $user_info[‘user_name‘];
            $member_state=db(‘member‘)->where(‘member_id‘,$this->userId)->value(‘member_state‘);
            if($member_state==0){
            	$this->success(‘该用户以被禁用‘,[],201);
            }
        }

    }


    /**
     * 操作成功返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param int   $code   错误码,默认为1
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function success($msg = ‘Request success‘, $data = [], $code = 200, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param int   $code   错误码,默认为0
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function error($msg = ‘Request error‘, $data = [], $code = 400, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码,默认为0
     * @param string $type   输出类型,支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = [], $code = 0, $type = null, array $header = [])
    {
        header(‘Access-Control-Allow-Origin:*‘);  // 设为星号,表示同意任意跨源请求。也可配置特定的域名可访问 如:  https://www.xxxx.com
        header(‘Access-Control-Allow-Methods:OPTIONS,POST,GET‘); // 允许请求的类型
        header(‘Access-Control-Allow-Headers:Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin‘);
        header(‘Access-Control-Expose-Headers:Content-Length,Content-Range‘);


        $result = [
            ‘code‘ => $code,
            ‘msg‘  => $msg,
            ‘time‘ => Request::instance()->server(‘REQUEST_TIME‘),
            ‘data‘ => $data,
        ];
        // 如果未设置类型则自动判断
        $type     = ‘json‘;
        if (isset($header[‘statuscode‘]))
        {
            $code = $header[‘statuscode‘];
            unset($header[‘statuscode‘]);
        }
        else
        {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    public function setToken($userId , $userName){
        $key = config(‘jwt.key‘);
        $time = time();
        $data = json_encode(array(
            ‘user_id‘=>$userId,
            ‘user_name‘=>$userName,
        ));
        $set_token = array(
            "iss" => "http://ml.cn",
            "aud" => "http://ml.cn",
            ‘iat‘ => $time, //签发时间
            ‘nbf‘ => $time, //在什么时间之后该jwt才可用
            ‘exp‘ => $time + 86400*100, //过期时间
            "data" => $data,
        );
        $token = JWT::encode($set_token , $key);
        return $token;
    }

    public function checkToken($token){
        //        $token = ‘eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9tbC5jbiIsImF1ZCI6Imh0dHA6XC9cL21sLmNuIiwiaWF0IjoxNTg1MDIyMzYxLCJuYmYiOjE1ODUwMjIzNjEsImV4cCI6MTU5MzY2MjM2MSwiZGF0YSI6IntcInVzZXJfaWRcIjoxLFwidXNlcl9uYW1lXCI6XCJ0ZXN0VXNlclwifSJ9.qO2I2fz-oi9SLMCyNXbPTDcOUSsc-NY0tExySreUDRI‘;
         $data = $this ->_readJwtToken($token);
        return $data;
    }
    protected function _readJwtToken($jwt){

        $key = config(‘jwt.key‘);

        try {

            JWT::$leeway = 60;//当前时间减去60,把时间留点余地

            $decoded = JWT::decode($jwt, $key, [‘HS256‘]); //HS256方式,这里要和签发的时候对应

            $arr = (array)$decoded;

            return  $arr;

        } catch(FirebaseJWTSignatureInvalidException $e) {  //签名不正确

            $this ->error(‘Please login again‘,‘‘,300);

        }catch(FirebaseJWTBeforeValidException $e) {  // 签名在某个时间点之后才能用

            $this ->error(‘Please login again‘,‘‘,300);

        }catch(FirebaseJWTExpiredException $e) {  // token过期

            $this ->error(‘Please login again‘,‘‘,300);

        }catch(Exception $e) {  //其他错误

            $this ->error(‘Please login again‘,‘‘,300);

        }

    }

    

}

?>

以上是关于jwt的主要内容,如果未能解决你的问题,请参考以下文章

OkHttpInterceptor 从 kotlin 拦截器导航到登录片段

AttributeError: ‘str‘ object has no attribute ‘decode‘解决方法

《代码实例》jwt参与用户凭证方式,生成jwt,security整合jwt

放置jwt.sign代码时出现JWT错误

我已经在 Spring Boot 代码中实现了 JWT 令牌安全性。如何在我的代码中的任何地方获取 jwt 令牌?需要保存审核

Jwt 代码在 .NET Core 2 上不起作用