In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to use token to verify identity with gin framework in golang". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Jwt
The principle of jwt is similar to that of session, and its purpose is to solve the statelessness in rest api.
Because of the rest interface, permission verification is required. However, the user name and password cannot be passed in every request, so the method of token is generated.
Process:
Users access the auth interface to get token
The server verifies the user name, password and other information passed in by the user, and after confirming that it is correct, it generates a token. This token is actually a key in a data structure similar to map (jwt data structure).
The exact thing should be: the user's information is actually saved in token, but it is encrypted. No wonder token can still be used when the server is rebooted, because the data is stored in the long string token.
The user accesses the interface that requires permission authentication and passes in token.
The server verifies the token: according to its own token key, it determines whether the token is correct (whether it has been tampered with by others), and then parses the information in the token from the token. The parsed information may be saved in context.
1. Use the open source jwt-go1.token utility class here
Package handlerimport ("awesomeProject/utils"github.com/dgrijalva/jwt-go"github.com/gin-gonic/gin"time") / / user information class As a parameter to generate token, type UserClaims struct {ID string `json: "userId" `Name string `json: "name" `Phone string `json: "phone" `/ jwt-go provides standard claim jwt.StandardClaims} var (/ / custom token key secret = [] byte ("16849841325189456f487") / / No check token noVerify = [] interface {} {"/ login") under this route "/ ping"} / / token validity time (nanosecond) effectTime = 2 * time.Hour) / / generate tokenfunc GenerateToken (claims * UserClaims) string {/ / set token validity period You can also use redis to store the token in redis and set the expiration time. If token does not expire, the expiration time of redis will be refreshed automatically. / / 2) in this way, it is convenient to renew token, and if you do not log in for a long time, forced login / / this example simply sets the validity period of token, but only provides a method to refresh token. There is no logic for renewal claims.ExpiresAt = time.Now (). Add (effectTime). Unix () / generate token sign, err: = jwt.NewWithClaims (jwt.SigningMethodHS256, claims) .SignedString (secret) if err! = nil {/ / because the project is connected to unified exception handling, the use of panic will not terminate the program. You can handle errors / / access unified exceptions in the original way. For more information, please see https://blog.csdn.net/u014155085/article/details/106733391 panic (err)} return sign} / / verify that tokenfunc JwtVerify (c * gin.Context) {/ / filter whether to verify token if utils.IsContainArr (noVerify, c.Request.RequestURI) {return} token: = c.GetHeader ("token") if token = "" {panic ("token not exist!")} / / verify token And stored in the request c.Set ("user", parseToken (token))} / / parse Tokenfunc parseToken (tokenString string) * UserClaims {/ / parse token token, err: = jwt.ParseWithClaims (tokenString, & UserClaims {}, func (token * jwt.Token) (interface {}, error) {return secret, nil}) if err! = nil {panic (err)} claims Ok: = token.Claims. (* UserClaims) if! ok {panic ("token is valid")} return claims} / / Update tokenfunc Refresh (tokenString string) string {jwt.TimeFunc = func () time.Time {return time.Unix (0,0)} token, err: = jwt.ParseWithClaims (tokenString, & UserClaims {}, func (token * jwt.Token) (interface {}, error) {return secret, nil}) if err! = nil {panic (err)} claims Ok: = token.Claims. (* UserClaims) if! ok {panic ("token is valid")} jwt.TimeFunc = time.Now claims.StandardClaims.ExpiresAt = time.Now (). Add (2 * time.Hour). Unix () return GenerateToken (claims)} 2. Use the middleware
Func main () {router: = gin.Default () router.Use (handler.JwtVerify) router.GET ("/ ping", controller.Ping) router.GET ("/ login", controller.Login) router.GET ("/ userInfo", controller.UserInfo) router.Run (": 8888") / / listen and serve on 0.0.0.0 gin.Default 8080 (for windows "localhost:8080")} 3. Controller partial code
Package controllerimport ("awesomeProject/handler"awesomeProject/utils"github.com/dgrijalva/jwt-go"github.com/gin-gonic/gin"net/http") func Ping (c * gin.Context) {c.JSON (http.StatusOK, utils.ResultT ("this is ping"))} func Login (c * gin.Context) {c.JSON (http.StatusOK, utils.ResultT (gin.H {"token": handler.GenerateToken (& handler.UserClaims {ID: "001") Name: "Zhang San", Phone: "1890023", StandardClaims: jwt.StandardClaims {},})} func UserInfo (c * gin.Context) {user, _: = c.Get ("user") claims: = user. (* handler.UserClaims) c.JSON (http.StatusOK) Utils.ResultT (claims.Phone))} "how to use token to authenticate identity when gin framework in golang is connected to jwt" is introduced here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.