golang jwt验证

匿名 (未验证) 提交于 2019-12-03 00:37:01
  • 安装
    go get “github.com/dgrijalva/jwt-go”

  • 登陆

// Create a new token object, specifying signing method and the claims // you would like it to contain. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{     "foo": "bar",     "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(), })  // Sign and get the complete encoded token as a string using the secret tokenString, err := token.SignedString(hmacSampleSecret)  fmt.Println(tokenString, err)
  • 验证
    在调用Parse时,会进行加密验证,同时如果提供了exp,会进行过期验证;
    如果提供了iat,会进行发行时间验证;如果提供了nbf,会进行发行时间验证.
hmacSampleSecret := []byte("my_secret_key")  // sample token string taken from the New example tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU"  // Parse takes the token string and a function for looking up the key. The latter is especially // useful if you use multiple keys for your application.  The standard is to use 'kid' in the // head of the token to identify which key to use, but the parsed token (head and claims) is provided // to the callback, providing flexibility. token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {     // Don't forget to validate the alg is what you expect:     if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {         return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])     }      // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")     return hmacSampleSecret, nil })  if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {     fmt.Println(claims["foo"], claims["nbf"]) } else {     fmt.Println(err) }
文章来源: golang jwt验证
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!