jwt 驗證中介軟體

來源:互聯網
上載者:User
```golang// ------------------------------------------------------ JWT 中介軟體middleware--------------------------------------------------------------package middlewareimport ("net/http""time""github.com/dgrijalva/jwt-go""github.com/gin-gonic/gin""github.com/pkg/errors")type JWT struct {SigningKey []byte}var (TokenExpired error = errors.New("Token is expired")TokenNotValidYet error = errors.New("Token not active yet")TokenMalformed error = errors.New("That's not even a token")TokenInvalid error = errors.New("Couldn't handle this token:")SignKey string = "hlms_yeeuu")// 自訂結構體參數type CustomClaims struct {User string `form:"phone"`Level string `form:"type"`HotelId string `form:"hotel_id"`HotelName string `form:"hotelName"`UserName string `form:"username"`jwt.StandardClaims}// JWT驗證func JWTAuth() gin.HandlerFunc {return func(c *gin.Context) {token, err := c.Cookie("claims")if err != nil {c.Redirect(302, "/login")return}j := NewJWT()// token := t.(string)// claims, err := j.ParseToken(token)claims, err := j.ParseToken(token)if err != nil {if err == TokenExpired {if token, err = j.RefreshToken(token); err == nil {c.JSON(http.StatusOK, gin.H{"error": 0, "message": "refresh token", "token": token})return}}c.Redirect(302, "/login")return}c.Set("claims", claims)c.Next()return}}func NewJWT() *JWT {return &JWT{[]byte(GetSignKey()),}}func GetSignKey() string {return SignKey}func SetSignKey(key string) string {SignKey = keyreturn SignKey}// parsefunc (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) {token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {return j.SigningKey, nil})if err != nil {if ve, ok := err.(*jwt.ValidationError); ok {if ve.Errors&jwt.ValidationErrorMalformed != 0 {return nil, TokenMalformed} else if ve.Errors&jwt.ValidationErrorExpired != 0 {// Token is expiredreturn nil, TokenExpired} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {return nil, TokenNotValidYet} else {return nil, TokenInvalid}}}if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {return claims, nil}return nil, TokenInvalid}func (j *JWT) RefreshToken(tokenString string) (string, error) {jwt.TimeFunc = func() time.Time {return time.Unix(0, 0)}token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {return j.SigningKey, nil})if err != nil {return "", err}if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {jwt.TimeFunc = time.Nowclaims.StandardClaims.ExpiresAt = time.Now().Add(1 * time.Hour).Unix()return j.CreateToken(*claims)}return "", TokenInvalid}// createfunc (j *JWT) CreateToken(claims CustomClaims) (string, error) {token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)return token.SignedString(j.SigningKey)}//------------------------------------------------------JWT調用(gin)------------------------------------------------------// 產生jwt := middleware.NewJWT()token, err := jwt.CreateToken(claims)if err != nil {c.JSON(200, gin.H{"status": 206, "msg": err.Error()})return}c.SetCookie("claims", token, 80000, "/", "", false, true)c.JSON(200, gin.H{"status": 200, "msg": ""})// 解析//公用的擷取cookiefunc GetJWT(c *gin.Context) (customclaims *middleware.CustomClaims, err error) {claims, err := c.Cookie("claims")if err != nil {fmt.Println(errors.Wrap(err, "utils/GetJWT/擷取失敗"))return}jwt := middleware.NewJWT()customclaims, err = jwt.ParseToken(claims)if customclaims == nil {err = errors.New("JWT為nil")}return}// router 驗證admin := app.Group("/admin", middleware.AdminJWTAuth())app.Use(middleware.JWTAuth())```268 次點擊  
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.