Token validation is a common Web authentication method, where it is not discussed in its specific implementation
I need to implement token validation in Golang, the web framework is gin (of course it doesn't matter to the framework)
Steps are as follows
- From
request
gettingtokenstring
- will be translated into
tokenstring
未解密的token对象
- will be
未解密的token对象
decrypted to get解密后的token对象
解密后的token对象
take parameters from the inside
First, obtain the decrypted token
The function obtains the tokenstring from the request, and turns to the unencrypted token object, and decrypts the token object after decryption.
import github.com/dgrijalva/jwt-go/request
request.ParseFromRequest(req *http.Request, extractor Extractor, keyFunc jwt.Keyfunc)
req
is the HTTP request
extractor
is an implemented Extractor接口
object, the function that the interface needs to implement is to ExtractToken(*http.Request) (string, error)
extract tokenstring from the HTTP request
keyFunc
is a function that needs to accept an "unencrypted token" and returns Secretkey bytes and error messages
func GetToken(r *http.Request) (token *jwt.Token, err error) { //由request获取token t := T{} // t是已经实现extract接口的对象,对request进行处理得到tokenString并生成为解密的token // request.ParseFromRequest的第三个参数是一个keyFunc,具体的直接看源代码 // 该keyFunc参数需要接受一个“未解密的token”,并返回Secretkey的字节和错误信息 // keyFunc被调用并传入未解密的token参数,返回解密好的token和可能出现的错误 // 若解密是正确的,那么返回的token.valid = true return request.ParseFromRequest(r, t, func(token *jwt.Token) (interface{}, error) { return []byte(Secretkey), nil })}
Ii. (information obtained from payload) gets the value corresponding to the parameter (key) from the token object
func GetIdFromClaims(key string, claims jwt.Claims) string { v := reflect.ValueOf(claims) if v.Kind() == reflect.Map { for _, k := range v.MapKeys() { value := v.MapIndex(k) if fmt.Sprintf("%s", k.Interface()) == key { return fmt.Sprintf("%v", value.Interface()) } } } return ""}// 示例 :GetIdFromClaims("username", token.claims) 其中token是已经解密的token
Three, function nesting relations
The following is a list of the Jwt-go library functions called during the JWT parsing process
Func:request. Parsefromrequest (req, extractor, Keyfunc) (*token, error)
Struct:request. Fromrequestparser{req, extractor, Claims=nil, parser=nil}
Func:parser. Parsewithclaims (tokenstring, claims, Keyfunc) (*token, error)
Parser. Parseunverified (tokenstring string, claims claims) (token *token, parts []string, err Error)
/blockquote>