下面是后端用于生成jwt-token的函数(golang写的),会返回jwt-token给前端,里面包含username:
// Sign signs the context with the specified secret.
func Sign(ctx *gin.Context, c Context, secret string) (tokenString string, err error) {
// Load the jwt secret from the Gin config if the secret isn't specified.
if secret == "" {
secret = viper.GetString("jwt_secret")
}
// The token content.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": c.ID,
"username": c.Username,
"nbf": time.Now().Unix(),
"iat": time.Now().Unix(),
})
// Sign the token with the specified secret.
tokenString, err = token.SignedString([]byte(secret))
return
}
问题:
前端javascript接收到jwt-token,怎么解析出jwt-token中的username?
jwt生成的字符串由JWT头、有效载荷和签名几个部分组成,然后编码处理后得到的,,你要解析,首先得解码啊。
关键这个字符串一般用于后端的权限验证,后端可能还会加墨处理,前端需要数据,再封装一个接口即可。
需要username,直接让多个后端返回就可以了啊