JWT 认证机制解析.md

2018-04-19  本文已影响0人  程序员子我

JWT 介绍

JWT: JSON WEB TOKEN

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA

认证机制

Token 认证机制

原理

unsignedToken = encodeBase64Url(header) + '.' + encodeBase64Url(payload)
signature = algorithm(unsignedToken)
JWT = unsignedToken + '.' + signature

结构

Header

{
  "typ":"JWT",  
  "alg":"HS256"  // 签名算法。
}

Payload

{
  “iss”:"jpush",       // 签发人
  "sub":"auth-server",  // 主题
  "aud":"cyril",      // 接收人
  "exp":1523844170761,     // 过期时间(重要)
  "nbf":1523844070761,     // 生效时间
  “iat”:1523844070000,     //  签发时间
  "jti":"7dedcff8d6fb48cf92a01d1ae036dd98", // jti 标识id
}
{
  “key”:"value"
}

Signature

注意点

io.jsonwebtoken / jjwt / 0.6.0

    // 创建token
    String token=Jwts.builder()
            .setHeaderParam("typ", "JWT")
            .setPayload(JSON.toJSONString(tokenPayload)) 
            .signWith(SignatureAlgorithm.HS256, TOKEN_SECRET_KEY)
            .compact();

    // 验证token
    try {
        Jws<Claims> claims = Jwts.parser()
            .requireSubject("Joe")
            .require("hasMotorcycle", true)
            .setSigningKey(key)
            .parseClaimsJws(compactJws);
    } catch (MissingClaimException e) {

    } catch (IncorrectClaimException e) {

    } catch (ExpiredJwtException e) {
    }
上一篇下一篇

猜你喜欢

热点阅读