zoukankan      html  css  js  c++  java
  • JWT使用

    JWT使用

    标签(空格分隔): php

    安装

    composer require lcobucci/jwt
    

    使用




    <?php
    namespace appcommonauth;
    
    use LcobucciJWTBuilder;
    use LcobucciJWTParser;
    use LcobucciJWTSignerHmacSha256;
    use LcobucciJWTValidationData;
    
    class JwtAuth
    {
    private static $instance;
    
    private $token;
    
    private $decodeToken;
    
    private $iis = 'web.tp5.cn';
    
    private $aud = 'web.tp5.cn';
    
    private $uid;
    
    private $configId;
    
    private $secret = 'web.tp5.cn';
    
    private function __construct() {}
    
    public static function getInstance()
    {
        if (!self::$instance) self::$instance = new self();
        return self::$instance;
    }
    
    private function __clone() {}
    
    public function setUid($uid)
    {
        $this->uid = $uid;
        return $this;
    }
    
    public function setConfigId($configId)
    {
        $this->configId = $configId;
        return $this;
    }
    
    public function getToken()
    {
        return (string)$this->token;
    }
    
    public function setToken($token)
    {
        $this->token = $token;
        return $this;
    }
    
    public function encode()
    {
        $time = time();
        $this->token = (new Builder())->setHeader('alg', 'HS256')
                ->setIssuedAt($this->iis)
                ->setAudience($this->aud)
                ->setIssuedAt($time)
                ->setExpiration($time + 120)
                ->set('uid', $this->uid)
                ->set('configId', $this->configId)
                ->sign(new Sha256(), $this->secret)
                ->getToken();
        return $this;
    }
    
    public function decode()
    {
        if (!$this->decodeToken) {
            $this->decodeToken = (new Parser())->parse((string) $this->token);
            $this->uid = $this->decodeToken->getClaim('uid');
            $this->configId = $this->decodeToken->getClaim('configId');
        }
        return $this->decodeToken;
    }
    
    public function verify()
    {
        return $this->decode()->verify(new Sha256(), $this->secret);
    }
    
    public function validate()
    {
        $data = new ValidationData();
        $data->setIssuer($this->iis);
        $data->setAudience($this->aud);
        return $this->decode()->validate($data);
    }
  • 相关阅读:
    dev c++ 字符间隔大 build with c++11
    What does -> mean in Python function definitions?
    input something to stdin, especially there is "$" in the uname
    control gpu memory
    调研打标(标签)的实现方式
    分页设计思考
    模糊查询的几种实现方式
    Error creating bean with name '***': Injection of resource dependencies failed,Bean named 'redisService' is expected to be of type
    Could not write JSON: No serializer found for class
    神奇BUG
  • 原文地址:https://www.cnblogs.com/yanweifeng/p/10943705.html
Copyright © 2011-2022 走看看