中文版
JWT的加密解密原理,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 or ECDSA.
Although JWTs can be encrypted to also provide secrecy between parties, we will focus on signed tokens. Signed tokens can verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.
Here are some scenarios where JSON Web Tokens are useful:
Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.
Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn’t been tampered with.
In its compact form, JSON Web Tokens consist of three parts separated by dots (.
), which are:
Therefore, a JWT typically looks like the following.
xxxxx.yyyyy.zzzzz
Let’s break down the different parts.
The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.
For example:
{
"alg": "HS256",
"typ": "JWT"
}
Then, this JSON is Base64Url encoded to form the first part of the JWT.
The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.
Registered claims: These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), and others.
Notice that the claim names are only three characters long as JWT is meant to be compact.
Public claims: These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.
Private claims: These are the custom claims created to share information between parties that agree on using them and are neither registered or public claims.
An example payload could be:
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
The payload is then Base64Url encoded to form the second part of the JSON Web Token.
Do note that for signed tokens this information, though protected against tampering, is readable by anyone. Do not put secret information in the payload or header elements of a JWT unless it is encrypted.
To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
The signature is used to verify the message wasn’t changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.
The output is three Base64-URL strings separated by dots that can be easily passed in HTML and HTTP environments, while being more compact when compared to XML-based standards such as SAML.
The following shows a JWT that has the previous header and payload encoded, and it is signed with a secret.
If you want to play with JWT and put these concepts into practice, you can use jwt.io Debugger to decode, verify, and generate JWTs.
In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned. Since tokens are credentials, great care must be taken to prevent security issues. In general, you should not keep tokens longer than required.
You also should not store sensitive session data in browser storage due to lack of security.
Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following:
Authorization: Bearer
This can be, in certain cases, a stateless authorization mechanism. The server’s protected routes will check for a valid JWT in the Authorization
header, and if it’s present, the user will be allowed to access protected resources. If the JWT contains the necessary data, the need to query the database for certain operations may be reduced, though this may not always be the case.
Note that if you send JWT tokens through HTTP headers, you should try to prevent them from getting too big. Some servers don’t accept more than 8 KB in headers. If you are trying to embed too much information in a JWT token, like by including all the user’s permissions, you may need an alternative solution, like Auth0 Fine-Grained Authorization.
If the token is sent in the Authorization
header, Cross-Origin Resource Sharing (CORS) won’t be an issue as it doesn’t use cookies.
The following diagram shows how a JWT is obtained and used to access APIs or resources:
/oauth/authorize
endpoint using the authorization code flow.Do note that with signed tokens, all the information contained within the token is exposed to users or other parties, even though they are unable to change it. This means you should not put secret information within the token.
Let’s talk about the benefits of JSON Web Tokens (JWT) when compared to Simple Web Tokens (SWT) and Security Assertion Markup Language Tokens (SAML).
As JSON is less verbose than XML, when it is encoded its size is also smaller, making JWT more compact than SAML. This makes JWT a good choice to be passed in HTML and HTTP environments.
Security-wise, SWT can only be symmetrically signed by a shared secret using the HMAC algorithm. However, JWT and SAML tokens can use a public/private key pair in the form of a X.509 certificate for signing. Signing XML with XML Digital Signature without introducing obscure security holes is very difficult when compared to the simplicity of signing JSON.
JSON parsers are common in most programming languages because they map directly to objects. Conversely, XML doesn’t have a natural document-to-object mapping. This makes it easier to work with JWT than SAML assertions.
Regarding usage, JWT is used at Internet scale. This highlights the ease of client-side processing of the JSON Web token on multiple platforms, especially mobile.
Comparison of the length of an encoded JWT and an encoded SAML
If you want to read more about JSON Web Tokens and even start using them to perform authentication in your own applications, browse to the JSON Web Token landing page at Auth0 by Okta.
每个 JWT 都由 Header、Payload、Signature 3 部分组成,同时用点进行拼接,形式如下:
Header.Payload.Signature
Header 部分是一个经过 Base64 编码后的 JSON 对象。对象的内容通常包括 2 个字段,形式如下:
{
"typ": "JWT",
"alg": "HS256"
}
其中,typ(全称为 type)指明当前的 Token 类型为 JWT,alg(全称为 algorithm)指明当前的签名算法是 HS256。
Payload 部分也是一个经过 Base64 编码后的 JSON 对象,对象的属性可以划分成 3 部分:保留字段、公共字段、私有字段。
保留字段是 JWT 内部声明,具有特殊作用的字段,包括
公共字段和私有字段都是用户可以任意添加的字段,区别在于公共字段是一些约定俗成,被普遍使用的字段,而私有字段更符合实际的应用场景。
当前已有的公共字段可以从 JSON Web Token Claims 中找到。
Payload 的结构形式如下:
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
Signature 部分是 JWT 根据已有的字段生成的,它的计算方式是使用 Header 中定义的算法,使用用户定义的密钥,对经过 Base64 编码后的 Header 和 Payload 组成的字符串进行加密,形式如下:
HMACSHA256(base64(header) + '.' + base64(payload))
业界普遍认可的应用场景主要有以下几种:
数据数据篡改指的是数据在传输过程中被截获,修改的行为。
JWT 本身可以使用加密算法对传输内容进行签名,即使数据被截获,也很难同时篡改签名和传输内容。
鉴权指的是验证用户是否有访问系统的权利。
部分人使用 JWT 来取代传统的 Session + Cookie,理由是:
基于 JWT 的鉴权一般处理逻辑是:
基于 JWT 的鉴权方案也存在一些争议:
JWT 规范的详细说明请见「参考」部分的链接。这里主要说明一下 JWT 最常见的几种签名算法(JWA):HS256(HMAC-SHA256) 、RS256(RSA-SHA256) 还有 ES256(ECDSA-SHA256)。
这三种算法都是一种消息签名算法,得到的都只是一段无法还原的签名。区别在于消息签名与签名验证需要的 「key」不同。
对于单体应用而言,HS256 和 RS256 的安全性没有多大差别。
/auth
,与普通的业务接口/home
/auth
接口,接收到请求后,判断该用户是否存在,如果存在会基于jwt,秘钥,生成一个指定时间有效的token响应给调用方/home
,该接口绑定了一个jwtAuthMiddleware中间件, 接收到请求后,先执行中间件,通过jwt校验用户token是否合法有效,如果不合法则拒绝,或重定向到登入页import (
"encoding/base64"
"errors"
"fmt"
"github.com/golang-jwt/jwt/v5"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
const TokenExpireDuration = time.Hour * 2
var Secret = []byte("秘钥吗?")
type UserInfo struct {
UserName string `json:"user_name" form:"user_name"`
PassWord string `json:"pass_word" form:"pass_word"`
}
type MyClaims struct {
UserName string
jwt.StandardClaims
}
//登录鉴权函数
func authHandler(c *gin.Context) {
//1.接收请求中的用户信息
user := &UserInfo{}
err := c.ShouldBindJSON(user)
if err != nil {
c.JSON(200, gin.H{"code": 2001, "msg": "invalid params"})
return
}
//2.模拟校验判断该用户是否存在
if user.UserName != "aaa" || user.PassWord != "123qwd" {
c.JSON(200, gin.H{"code": 2002, "msg": "鉴权失败"})
return
}
//3.存在,通过jwt,生成token签名,并响应
cla := MyClaims{
user.UserName,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(), // 过期时间
Issuer: "lx-jwt", // 签发人
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, cla)
//进行签名生成对应的token
tokenString, _ := token.SignedString(Secret)
c.JSON(200, gin.H{"code": 0, "msg": "success", "data": gin.H{"token": tokenString}})
return
}
//中间件,认证token合法性
func jwtAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHandler := c.Request.Header.Get("authorization")
if authHandler == "" {
c.JSON(200, gin.H{"code": 2003, "msg": "请求头部auth为空"})
c.Abort()
return
}
// 前两部门可以直接解析出来
jwt := strings.Split(authHandler, ".")
cnt := 0
for _, val := range jwt {
cnt++
if cnt == 3 {
break
}
msg, _ := base64.StdEncoding.DecodeString(val)
fmt.Println("val ->", string(msg))
}
//调用下方自己实现的token解析函数,并且在判断token是否过期
mc, err := ParseToken(authHandler)
if err != nil {
fmt.Println("err = ", err.Error())
c.JSON(http.StatusOK, gin.H{
"code": 2005,
"msg": "无效的Token",
})
c.Abort()
return
}
// 将当前请求的username信息保存到请求的上下文c上
c.Set("username", mc.UserName)
c.Next() // 后续的处理函数可以用过c.Get("username")来获取当前请求的用户信息
}
}
// parse token
func ParseToken(tokenString string) (*MyClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
return Secret, nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(*MyClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New("invalid token")
}
func main() {
r := gin.Default()
//1.登入鉴权接口,调用authHandler,对用户信息进行校验,校验通过通过jwt生成的token并返回
r.POST("/auth", authHandler)
//2.普通接口,该接口注册了一个jwtAuthMiddleware中间件
//在中间件中会获取用户token,基于jwt校验是否合法,合法放行,否则拒绝
r.GET("/home", jwtAuthMiddleware(), homeHandler)
r.Run(":8080")
}
//普通业务接口
func homeHandler(c *gin.Context) {
username := c.MustGet("username").(string)
c.JSON(http.StatusOK, gin.H{
"code": 2000,
"msg": "success",
"data": gin.H{"username": username},
})
}