JWT Validation Middleware

Source: Internet
Author: User
"' golang//------------------------------------------------------JWT Middleware 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")//custom struct-body parameter type customclaims struct {User string ' form: "ph One ' Level string ' form: ' Type ' ' Hotelid string ' form: ' hotel_id ' ' hotelname string ' form: ' Hotelname ' ' UserName string ' Form: "username" ' JWT. standardclaims}//JWT Verifies the 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. (strin g)//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 Strin g) (*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 Call (gin)----------------- -------------------------------------//Generate JWT: = middleware. NEWJWT () token, err: = JWT. creatEtoken (CLAIMS) if err! = nil {C.json (gin. h{"status": 206, "MSG": Err. Error ()}) Return}c.setcookie ("claims", token, 80000, "/", "", false, True) C.json (gin. h{"status": $, "MSG": "}"//parse//Public get 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/get Failed")) RETURN}JWT: = middleware. NEWJWT () customclaims, err = JWT. Parsetoken (claims) if customclaims = = Nil {err = errors. New ("JWT is nil")}return}//Router Verify admin: = App. Group ("/admin", middleware. Adminjwtauth ()) app. Use (middleware. Jwtauth ()) "268 reads  

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.