import "github.com/fwhezfwhez/jwt" func Login(c *gin.Context){ ...(验证身份正确) //获取token管理对象 token := jwt.GetToken() //添加令牌关键信息 token.AddPayLoad("userName", user.UserName).AddPayLoad("role", "admin").AddHeader("typ", "JWT").AddHeader("alg", "HS256") //添加令牌期限 exp:=time.Now().Add(1*time.Hour) token.AddPayLoad("exp", strconv.FormatInt(exp.Unix(), 10)) //获取令牌,并添加进reponse的header里 jwts, _, erre := token.JwtGenerator(consts.Secret) if erre != nil { fmt.Println("token生成出错") return } fmt.Println("生成的jwt是:", jwts) c.Writer.Header().Add("x-auth-token", jwts) ... }
客户端_发送login请求
var Token string func main(){ ... var content = fmt.Sprintf("userName=admin&password=123456") t1 := time.Now() resp, err := http.Post(host+"v1/POST/user/login", "application/x-www-form-urlencoded", strings.NewReader(content)) Token =resp.Header.Get("x-auth-token") t2 := time.Now() fmt.Println(t2.Sub(t1)) if err != nil { panic(err) } helpRead(resp) ... }
客户端_请求其他功能获取列表
... t1 := time.Now() //resp, err := http.Get(host + "v1/GET/mediums/list") client := &http.Client{} req, err := http.NewRequest("GET", "http://localhost:8087/v1/GET/mediums/list",nil) req.Header.Add("x-auth-token", Token) resp, err := client.Do(req) t2 := time.Now() fmt.Println(t2.Sub(t1)) if err != nil { panic(err) } helpRead(resp) ...
服务端_令牌校验
func main(){ ... router := gin.Default() //Login不需要令牌验证,所以写中间件前面 router.POST(consts.LoginURL, userControl.Login) router.Use(Validate()) //后续的监听都需要通过Validate()的验证 router.GET(consts.GetMediumsURL, mediumControl.GetMediums) router..... ... } func Validate()gin.HandleFunc{ return func(c *gin.Context) { if JWTToken := c.Request.Header.Get("x-auth-token");JWTToken!=""{ token :=jwt.GetToken() legal,err:=token.IsLegal(JWTToken,consts.Secret) if err!=nil{ fmt.Println(err) c.Abort() c.JSON(200,consts.ResponseTokenValidateError) return } if !legal{ c.Abort() c.JSON(200,consts.ResponseTokenValidateWrong) return } c.Next() }else{ c.JSON(200, consts.ResponseTokenNotFound) c.Abort() return } } }
更多golang知识请关注golang教程栏目。
以上就是golang jwt前端怎么验证的详细内容,更多请关注其它相关文章!