Golang Jwt-go for token authentication

Source: Internet
Author: User
Tags key string sprintf

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

  1. From request gettingtokenstring
  2. will be translated into tokenstring未解密的token对象
  3. will be 未解密的token对象 decrypted to get解密后的token对象
  4. 解密后的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)

  1. reqis the HTTP request
  2. extractoris 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
  3. keyFuncis 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>
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.