JWT 之dingo/api

JWT (json web token)


dingo/api 以经内置了jwt

基本术语

  • header (头部)

    申明加密算法,JWT最后是通过base64编码
    
  • payload (载荷)

    过期时间,用户数据
    JWT 最后是通过 Base64 编码,可被翻译回原来的样子
    
  • signature (签名)

    由服务器进行的签名,保证了 token 不被篡改。
    
    ```
        {
            "typ":"JWT",
            "alg":"HS256"
        }
        {
            "iss":"http://larbbs.test",
            "iat":1515733500,
            "exp":1515737100,
            "nbf":1515733500,
            "jti":"c3U4VevxG2ZA1qhT",
            "sub":1,
            "prv":"23bd5c8949f600adb39e701c400872db7a5976f7"
        }
        signature
    ```
    

    在dingo中使用jwt

    • auth.php api配置jwt驱动
    • dingo api配置auth项,指向Dingo\Api\Auth\Provider\JWT
    • 安装tymon/jwt-auth

    jwt载荷术语

    • Tymon\JWTAuth\Providers\JWTAuthServiceProvide
    • Tymon\JWTAuth\PayloadFactory JWTFactory 门面
    • 配置

          Secret Key - secret
          Token time to live - ttl
          Refresh time to live - refresh_ttl
      
          Hashing algorithm - algo
          User model path - user
          User identifier - identifier
      
          Required claims - required_claims
          Blacklist enabled - blacklist_enabled
      
          Providers
          User - providers.user
          JWT - providers.jwt
          Authentication - providers.auth
          Storage - providers.storage

      payload 说明

      • sub
        Subject 保存token的标识,默认值为user的id
      • iat
        Issued At token发行的unix时间戳
      • exp
        Expiry 过期时间
      • nbf
        Not Before 最早可被使用的token时间点
      • iss
        Issuer 默认请求的url地址
      • jti
        JWT id token的唯一标识,通常由发行时间与sub MD5求值所得
        -aud
        Audience 接收者参数非必选项

    生成token

        // 用户证书(凭证)
        $credentials = $request->only('email', 'password');
        $token = JWTAuth::attempt($credentials)
    
        // 用户对象
        $user = User::first();
        $token = JWTAuth::fromUser($user);
    
        // 自定义第二个参数,该参数在解码token时会用到
        $customClaims = ['foo' => 'bar', 'baz' => 'bob'];
        JWTAuth::attempt($credentials, $customClaims);
        // or
        JWTAuth::fromUser($user, $customClaims);
    
        // 自定义token
        $customClaims = ['foo' => 'bar', 'baz' => 'bob'];
        $payload = JWTFactory::make($customClaims);
        $token = JWTAuth::encode($payload);
    
        // 支持链式调用
        $payload = JWTFactory::sub(123)->aud('foo')->foo(['bar' => 'baz'])->make();
        $token = JWTAuth::encode($payload);
    

    认证(验证)authentication

  • header头内传递token

        ```Authorization
            Authorization: Bearer {yourtokenhere}
        ```
        *warning  对于apache而言非base64编码内容会被丢弃,修复如下*
        ```fix
            RewriteEngine On
            RewriteCond %{HTTP:Authorization} ^(.*)
            RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
        ```
    2.
    
  • 查询字符串传递

        ```
            http://api.mysite.com/me?token={yourtokenhere}
    
            // 从请求中解析token
            JWTAuth::setToken('foo.bar.baz');
            $token = JWTAuth::getToken();
            $user = JWTAuth::parseToken()->authenticate(); 
    
        ```
    3. 
    
  • 事件

        ```
            // fired when the token could not be found in the request
            Event::listen('tymon.jwt.absent');
    
            // fired when the token has expired
            Event::listen('tymon.jwt.expired');
    
            // fired when the token is found to be invalid
            Event::listen('tymon.jwt.invalid');
    
            // fired if the user could not be found (shouldn't really happen)
            Event::listen('tymon.jwt.user_not_found');
    
            // fired when the token is valid (User is passed along with event)
            Event::listen('tymon.jwt.valid');
        ```
    
  • 中间件

        - GetUserFromToken  
            检查header和query字符串,解码,同样事件会被触发
        - RefreshToken
            使旧的token无效,并返回下一次响应,仅对当一请求有效
        - 注册
        ```
            protected $routeMiddleware = [
                'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
                'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
            ];
        ```
    

猜你喜欢

转载自blog.csdn.net/u011584949/article/details/80958142
jwt