JWT的數據結構
典型的,一個JWT看起來如下圖。
改對象為一個很長的字符串,字符之間通過"."分隔符分為三個子串。注意JWT對象為一個長字串,各字串之間也沒有換行符,此處為了演示需要,我們特意分行並用不同顏色表示了。每一個子串表示了一個功能塊,總共有以下三個部分:
JWT的三個部分如下。JWT頭、有效載荷和簽名,將它們寫成一行如下。

第一段字符串 Header ,內部包含算法/token類型 (先轉化為json串,進行 base64url (base64加密后;對特殊字符進行對應替換) 加密)
{
"alg": "HS256", // HS256不可反解
"typ": "JWT"
}
第二段字符串 payload,自定義key:value (先轉化為json串,進行 base64url (base64加密后;對特殊字符進行對應替換) 加密)
PS:請注意,默認情況下JWT是未加密的,任何人都可以解讀其內容,因此不要構建隱私信息字段,存放保密信息,以防止信息泄露。
{
"sub": "1234567890",
"name": "chongchong",
"exp": 123123123123
}
第三段字符串 數字簽名, 1.將第一第二部分密文拼接起來 2.進行 第一部分 alg加密算法加密(加鹽) 3.對加密后的密文進行base64url加密 后生成token發送給客戶端
Decode
1.獲取Token后進行"."切割 成3部分
2.對第二部分payload進行解密 獲取對應的用戶信息 進行邏輯業務判斷
3.把1,2部分拼接再次進行 第一部分 alg加密算法加密(加鹽)獲取密文后與第三部分進行比較 如果相等表示認證通過
第三方包
$ go get github.com/dgrijalva/jwt-go
// 加密
func NewToken() {
key := "秘鑰"
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
// 自定義鍵值對
"foo": "xxx",
"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(key)) // 傳入秘鑰 []byte() 拿到string
if err != nil {
fmt.Println(err)
}
fmt.Println(tokenString)
}
// 解密
func decode() {
// sample token string taken from the New example
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJ4eHgiLCJuYmYiOjE0NDQ0Nzg0MDB9.YXnq53IqsbOVMRJ8vfYFPqbRH2HLM9ezwwQo6TqHBW0"
// Parse takes the token string and a function for looking up the key. The latter is especially
// useful if you use multiple keys for your application. The standard is to use 'kid' in the
// head of the token to identify which key to use, but the parsed token (head and claims) is provided
// to the callback, providing flexibility.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte("秘鑰"), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// 獲取分區內容
fmt.Println(claims["foo"], claims["nbf"])
} else {
fmt.Println(err)
}
}