Token authentication is an important way to verify user identity. It is widely used in golang development. This paper mainly describes token authentication after jwt packet encryption.
The import package:
import (
"github.com/dgrijalva/jwt-go"
)
// GenerateToken generate Token
func GenerateToken(mapClaims jwt.MapClaims, key string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, mapClaims)
return token.SignedString([]byte(key))
}
// validation token
func checkToken(uid int64,token *jwt.Token) bool {
tokens, _ := token.SignedString([]byte(JWTKey))
redisToken, _ := GetMemberToken(uid)
if tokens != redisToken {
return false
}
return true
}
The user login request pulls out token
token, err := request.ParseFromRequest(r, request.AuthorizationHeaderExtractor, func(token *jwt.Token) (interface{}, error) {
return []byte(JWTKey), nil
})
if err == nil && token.Valid {
tokenMap := token.Claims.(jwt.MapClaims)
uidStr := tokenMap["uid"].(string)
uid, _ := strconv.ParseInt(uidStr,10,64)
if !checkToken(uid, token) {
// validation token Is it legal
base.ErrorResponse(w, http.StatusUnauthorized, "Authorization Is Invalid")
return
}
}
token is mainly used to generate, verify, and parse token to obtain the validity of uid and token on user request