jwt
由三部分组成:
header
头部alg
: (algorithm) 算法typ
: (type) 类型cty
: (content type) 内容类型kid
: (key ID) 密钥 IDx5u
: (X.509 URL) X.509 地址x5c
: (X.509 certificate chain) X.509 证书链crit
: (critical) 关键alg
和 type
,例如json复制代码{
"alg": "HS256",
"typ": "JWT"
}
payload
负载iss
: (issuer) 签发人exp
: (expiration time) 过期时间sub
: (subject) 主题aud
: (audience) 受众nbf
: (Not Before) 生效时间iat
: (Issued At) 签发时间jti
: (JWT ID) 编号user
: 用户信息复制代码{
"exp": 1718254332,
"iat": 1718167932,
"user": {
"email": "jack@gmial.com",
"username": "jack22ssss22"
}
}
signature
签名,这个签名不能泄漏,否则会被篡改完整的 jwt
就是把这三部分组合起来 HMACSHA256(base64UrlEncode(Header).base64UrlEncode(Payload).Signature)
HS256
是一种对称加密算法,使用秘密密钥对每条消息进行签名和验证
复制代码func GenerateJWTHS256(username, email string) (string, error) {
key := []byte("secret")
tokenDuration := 24 * time.Hour
now := time.Now()
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user": map[string]string{
"username": username,
"email": email,
},
"iat": now.Unix(),
"exp": now.Add(tokenDuration).Unix(),
})
return t.SignedString(key)
}
复制代码func VerifyJWTHS256(token string) (*jwt.MapClaims, bool, error) {
var claim jwt.MapClaims
claims, err := jwt.ParseWithClaims(token, &claim, func(t *jwt.Token) (interface{}, error) {
return []byte("secret"), nil
})
if err != nil {
return nil, false, err
}
if claims.Valid {
return &claim, true, nil
}
return nil, false, nil
}
RS256
是一种非对称加密算法,使用私钥加密明文,公钥解密密文
复制代码apt install openssl
在当前目录下生成一个 2048
位的私钥文件 private.pem
bash
复制代码openssl genrsa -out private.pem 2048
复制代码openssl rsa -in private.pem -outform PEM -pubout -out public.pem
复制代码var privateKey *rsa.PrivateKey
var publicKey *rsa.PublicKey
func init() {
var err error
var bytes []byte
bytes, err = os.ReadFile("/root/uccs/realworld/private.pem")
if err != nil {
panic(err)
}
privateKey, err = jwt.ParseRSAPrivateKeyFromPEM(bytes)
if err != nil {
panic(err)
}
bytes, err = os.ReadFile("/root/uccs/realworld/public.pem")
if err != nil {
panic(err)
}
publicKey, err = jwt.ParseRSAPublicKeyFromPEM(bytes)
if err != nil {
panic(err)
}
}
复制代码func GenerateJWTRS256(username, email string) (string, error) {
tokenDuration := 24 * time.Hour
now := time.Now()
t := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"user": map[string]string{
"username": username,
"email": email,
},
"iat": now.Unix(),
"exp": now.Add(tokenDuration).Unix(),
})
return t.SignedString(privateKey)
}
复制代码func VerifyJWTRS256(token string) (*jwt.MapClaims, bool, error) {
var claim jwt.MapClaims
claims, err := jwt.ParseWithClaims(token, &claim, func(t *jwt.Token) (interface{}, error) {
return publicKey, nil
})
if err != nil {
return nil, false, err
}
if claims.Valid {
return &claim, true, nil
}
return nil, false, nil
}