golang jwt+token验证的实现
Token验证是验证用户身份的重要方式,在golang开发中具有广泛应用,文中主要阐述了利用jwt包加密后的token验证。
导入包:
import ( "github.com/dgrijalva/jwt-go" ) // GenerateToken 生成Token func GenerateToken(mapClaims jwt.MapClaims, key string) (string, error) { token := jwt.NewWithClaims(jwt.SigningMethodHS256, mapClaims) return token.SignedString([]byte(key)) } // 验证token func checkToken(uid int64,token *jwt.Token) bool { tokens, _ := token.SignedString([]byte(JWTKey)) redisToken, _ := GetMemberToken(uid) if tokens != redisToken { return false } return true }
用户登录请求取出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) { // 验证token 是否合法 base.ErrorResponse(w, http.StatusUnauthorized, "Authorization Is Invalid") return } }
token主要是生成,验证,以及用户请求时解析token得出用户uid和token的有效性
相关推荐
kiven 2020-09-11
wolfjin 2020-09-10
HMHYY 2020-06-28
苦咖啡flask 2020-06-18
playis 2020-06-16
xuanwenchao 2020-06-14
sqliang 2020-06-14
TesterJingel 2020-06-10
RocketJ 2020-06-09
powderhose 2020-06-08
rongxionga 2020-06-08
Burgesszheng 2020-06-07
huangyx 2020-05-29
RuoShangM 2020-05-14
数据库之扑朔迷离 2020-05-06
huanghong 2020-05-03