什么是JWT

What is JSON Web Token?

中文版
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.

When should you use JSON Web Tokens?

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.

What is the JSON Web Token structure?

In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:

  • Header
  • Payload
  • Signature

Therefore, a JWT typically looks like the following.

xxxxx.yyyyy.zzzzz

Let’s break down the different parts.

Header

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.

Payload

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.

Signature

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.

Putting all together

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. 什么是JWT_第1张图片

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.

什么是JWT_第2张图片

How do JSON Web Tokens work?

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:

什么是JWT_第3张图片

  1. The application or client requests authorization to the authorization server. This is performed through one of the different authorization flows. For example, a typical OpenID Connect compliant web application will go through the /oauth/authorize endpoint using the authorization code flow.
  2. When the authorization is granted, the authorization server returns an access token to the application.
  3. The application uses the access token to access a protected resource (like an API).

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.

Why should we use JSON Web Tokens?

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.

什么是JWT_第4张图片
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

Header 部分是一个经过 Base64 编码后的 JSON 对象。对象的内容通常包括 2 个字段,形式如下:

{
  "typ": "JWT",
  "alg": "HS256"
}

其中,typ(全称为 type)指明当前的 Token 类型为 JWT,alg(全称为 algorithm)指明当前的签名算法是 HS256

Payload

Payload 部分也是一个经过 Base64 编码后的 JSON 对象,对象的属性可以划分成 3 部分:保留字段、公共字段、私有字段。

保留字段是 JWT 内部声明,具有特殊作用的字段,包括

  • iss(全称为 issuer),指明 JWT 是由谁签发的
  • sub(全称为 subject),指明 JWT 的主题(也可理解为面向用户的类型)
  • aud(全称为 audience),指明 JWT 希望谁签收
  • exp(全称为 expiration time),指明 JWT 的过期时间,过期时间需大于签发时间
  • nbf(全称为 not before time),指明 JWT 在哪个时间点生效
  • iat(全称为 issued at time),指明 JWT 的签发时间
  • jti(全称为 JWT ID),指明 JWT 唯一 ID,用于避免重放攻击

公共字段和私有字段都是用户可以任意添加的字段,区别在于公共字段是一些约定俗成,被普遍使用的字段,而私有字段更符合实际的应用场景。

当前已有的公共字段可以从 JSON Web Token Claims 中找到。

Payload 的结构形式如下:

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Signature

Signature 部分是 JWT 根据已有的字段生成的,它的计算方式是使用 Header 中定义的算法,使用用户定义的密钥,对经过 Base64 编码后的 Header 和 Payload 组成的字符串进行加密,形式如下:

HMACSHA256(base64(header) + '.' + base64(payload))

三、应用场景

业界普遍认可的应用场景主要有以下几种:

防止传输数据篡改

数据数据篡改指的是数据在传输过程中被截获,修改的行为。

JWT 本身可以使用加密算法对传输内容进行签名,即使数据被截获,也很难同时篡改签名和传输内容。

鉴权

鉴权指的是验证用户是否有访问系统的权利。

部分人使用 JWT 来取代传统的 Session + Cookie,理由是:

  • 服务器开销小。使用 Session + Cookie 需要服务器缓存用户数据,而使用 JWT 则是直接将用户数据下发给客户端,每次请求附带一并发送给服务器。
  • 扩展性好。服务器不缓存用户数据的好处是可以很方便的进行横向扩容
  • 适用于单点登录。JWT 很适合做跨域情况下的单点登录
  • 适用于搭配 RESTFul API 使用。基于 RESTFul 架构设计的 API 需遵循 RESTFul 的无状态原则,而基于 JWT 的鉴权恰恰是把状态转移到了客户端

基于 JWT 的鉴权一般处理逻辑是:

什么是JWT_第5张图片

基于 JWT 的鉴权方案也存在一些争议:

  • 服务器签发 JWT 后,并不能主动注销,若存在恶意请求则很难制止。其实可以通过 Token 黑名单的方式去解决。
  • JWT 减少了服务器的开销,却增加了带宽的开销,JWT 生成的 Token 在体积上比 SessionID 大很多,意味着每次请求相比之前要携带更多的数据量。这个确实是这样,所以应该尽量只在 JWT 内放必要的数据。
  • JWT 在鉴权方面并非完全优于 Session-Cookie,举个例子,SessionID 也可以通过签名的方式来防止篡改。

什么是HS256

JWT 规范的详细说明请见「参考」部分的链接。这里主要说明一下 JWT 最常见的几种签名算法(JWA):HS256(HMAC-SHA256) 、RS256(RSA-SHA256) 还有 ES256(ECDSA-SHA256)。

这三种算法都是一种消息签名算法,得到的都只是一段无法还原的签名。区别在于消息签名签名验证需要的 「key」不同。

  1. HS256 使用同一个「secret_key」进行签名与验证(对称加密)。一旦 secret_key 泄漏,就毫无安全性可言了。
    • 因此 HS256 只适合集中式认证,签名和验证都必须由可信方进行。
    • 传统的单体应用广泛使用这种算法,但是请不要在任何分布式的架构中使用它!
  2. RS256 是使用 RSA 私钥进行签名,使用 RSA 公钥进行验证。公钥即使泄漏也毫无影响,只要确保私钥安全就行。
    • RS256 可以将验证委托给其他应用,只要将公钥给他们就行。
  3. ES256 和 RS256 一样,都使用私钥签名,公钥验证。算法速度上差距也不大,但是它的签名长度相对短很多(省流量),并且算法强度和 RS256 差不多。

对于单体应用而言,HS256 和 RS256 的安全性没有多大差别。

jwt小例子

  1. 在gin框架jwt的运用例子
  2. 内部提供了登入鉴权的接口/auth,与普通的业务接口/home
  3. 前端携带用户信息首先请求/auth接口,接收到请求后,判断该用户是否存在,如果存在会基于jwt,秘钥,生成一个指定时间有效的token响应给调用方
  4. 在进行其它业务时,例如调用/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},
	})
}

你可能感兴趣的:(java,golang从入门到入门,java,网络,服务器)