來源:blog.csdn.net/weixin_44912855 最近微信群里一個網友分享了他京東一面的過程,我這裡分享給大家其中一道面試題。 京東一面」子線程如何獲取父線程ThreadLocal的值 子線程如何獲取父線程ThreadLocal的值 想要子線程獲取父線程中 ThreadLocal 中 ...
JWT校驗
配置文件
package config
type JWT struct {
SigningKey string `json:"signingKey" yaml:"signing-key"` // jwt簽名
ExpiresTime int64 `json:"expiresTime" yaml:"expires-time"` // 過期時間
Issuer string `json:"issuer" yaml:"issuer"` // 簽發者
}
工具結構體
package pkg
import (
"errors"
"time"
"catering/global"
"catering/model/system/request"
"github.com/dgrijalva/jwt-go"
)
type JWT struct {
SigningKey []byte
}
var (
ErrTokenExpired = errors.New("token is expired")
ErrTokenNotValidYet = errors.New("token not active yet")
ErrTokenMalformed = errors.New("that's not even a token")
ErrTokenInvalid = errors.New("couldn't handle this token")
)
func NewJWT() *JWT {
return &JWT{
[]byte(global.Config.JWT.SigningKey),
}
}
//生成claims
func (j *JWT) CreateClaims(baseClaims request.BaseClaims) request.CustomClaims {
claims := request.CustomClaims{
BaseClaims: baseClaims,
StandardClaims: jwt.StandardClaims{
NotBefore: time.Now().Unix() - 1000, // 簽名生效時間
ExpiresAt: time.Now().Unix() + global.Config.JWT.ExpiresTime, // 過期時間 7天 配置文件
Issuer: global.Config.JWT.Issuer, // 簽名的發行者
},
}
return claims
}
// 創建一個token
func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
//對token進行簽名加密
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(j.SigningKey)
}
// CreateTokenByOldToken 舊token 換新token 用concurrency_control對token進行加鎖避免併發問題(加鎖粒度為oldToken)
func (j *JWT) CreateTokenByOldToken(oldToken string, claims request.CustomClaims) (string, error) {
v, err, _ := global.Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
return j.CreateToken(claims)
})
return v.(string), err
}
// 解析 token
func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
return j.SigningKey, nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, ErrTokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
// Token is expired
return nil, ErrTokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, ErrTokenNotValidYet
} else {
return nil, ErrTokenInvalid
}
}
}
if token != nil {
if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
return claims, nil
}
return nil, ErrTokenInvalid
} else {
return nil, ErrTokenInvalid
}
}
使用
登錄獲取token
func (b *BaseApi) Login(c *gin.Context) {
var l systemReq.Login
msg, err := valid.BindAndValid(c, &l)
if err != nil {
response.FailWithMessage(msg, c)
return
}
if store.Verify(l.CaptchaId, l.Captcha, true) {
u := &system.SysUser{Username: l.Username, Password: l.Password}
if err, user := userService.Login(u); err != nil {
global.Log.Error("登陸失敗! 用戶名不存在或者密碼錯誤!", zap.Error(err))
response.FailWithMessage("用戶名不存在或者密碼錯誤", c)
} else {
//登錄成功,生成token
b.tokenNext(c, *user)
}
} else {
response.FailWithMessage("驗證碼錯誤", c)
}
}
// 登錄以後簽發jwt
func (b *BaseApi) tokenNext(c *gin.Context, user system.SysUser) {
j := pkg.NewJWT()
//新建claims
claims := j.CreateClaims(systemReq.BaseClaims{
UUID: user.UUID,
ID: uint(user.ID),
NickName: user.NickName,
Username: user.Username,
AuthorityId: user.AuthorityId,
})
//生成token
token, err := j.CreateToken(claims)
if err != nil {
global.Log.Error("獲取token失敗!", zap.Error(err))
response.FailWithMessage("獲取token失敗", c)
return
}
//生成session
session, err := global.SESSION.Get(c.Request, "SessionId")
if err != nil {
fmt.Println(err)
}
session.Values["token"] = token
//把session數據存放到cookie併在response的head中返回
session.Save(c.Request, c.Writer)
//返回token
response.OkWithDetailed(systemRes.LoginResponse{
User: user,
Token: token,
ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
}, "登錄成功", c)
return
}
在中間件中進行校驗
package middleware
import (
"strconv"
"time"
"catering/pkg"
"catering/global"
"catering/model/common/response"
"github.com/gin-gonic/gin"
)
func JWTAuth() gin.HandlerFunc {
return func(c *gin.Context) {
// 我們這裡jwt鑒權取頭部信息 x-token 登錄時回返回token信息
token := c.Request.Header.Get("x-token")
if token == "" {
response.FailWithDetailed(gin.H{"reload": true}, "未登錄或非法訪問", c)
c.Abort()
return
}
// 獲取session
session, _ := global.SESSION.Get(c.Request, "SessionId")
t := session.Values["token"]
//判斷session和對session中的token進行比對
if tk, ok := t.(string); !ok {
response.FailWithDetailed(gin.H{"reload": true}, "授權已過期", c)
c.Abort()
return
} else if tk != token {
response.FailWithDetailed(gin.H{"reload": true}, "授權已過期", c)
c.Abort()
return
}
j := pkg.NewJWT()
// parseToken 解析token包含的信息
// 判斷該token是否已經到達有效期
claims, err := j.ParseToken(token)
if err != nil {
if err == pkg.ErrTokenExpired {
response.FailWithDetailed(gin.H{"reload": true}, "授權已過期", c)
c.Abort()
return
}
response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
c.Abort()
return
}
//把解析出來的用戶數據存入上下文中,方便後續的調用
c.Set("claims", claims)
c.Next()
}
}
用法
//獲取用戶動態路由,返回包括系統菜單詳情列表
func (a *AuthorityMenuApi) GetMenu(c *gin.Context) {
//其中pkg.GetUserAuthorityId是通過上下文獲取,也就是ctx.Get("claims")
if err, menus := menuService.GetMenuTree(pkg.GetUserAuthorityId(c)); err != nil {
global.Log.Error("獲取失敗!", zap.Error(err))
response.FailWithMessage("獲取失敗", c)
} else {
if menus == nil {
menus = []system.SysMenu{}
}
response.OkWithDetailed(systemRes.SysMenusResponse{Menus: menus}, "獲取成功", c)
}
}
// pakcage pkg
// 從Gin的Context中獲取從jwt解析出來的用戶角色id
func GetUserAuthorityId(c *gin.Context) string {
if claims, exists := c.Get("claims"); !exists {
if cl, err := GetClaims(c); err != nil {
return ""
} else {
return cl.AuthorityId
}
} else {
waitUse := claims.(*systemReq.CustomClaims)
return waitUse.AuthorityId
}
}