From 37027e40dcd92fedd0363cbbe21d3bea7b06067e Mon Sep 17 00:00:00 2001 From: kenneth <1185230223@qq.com> Date: Fri, 8 Apr 2022 16:12:04 +0800 Subject: [PATCH] add gin/frame authjwt module --- pkg/gin/frame/auth_jwt.go | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 pkg/gin/frame/auth_jwt.go diff --git a/pkg/gin/frame/auth_jwt.go b/pkg/gin/frame/auth_jwt.go new file mode 100644 index 0000000..822732e --- /dev/null +++ b/pkg/gin/frame/auth_jwt.go @@ -0,0 +1,54 @@ +package frame + +import ( + "errors" + "fmt" + "net/http" + "strings" + + "github.com/gin-gonic/gin" + "github.com/zhang2092/gohelpers/pkg/token" +) + +const ( + authorizationHeaderKey = "authorization" + authorizationTypeBearer = "bearer" + authorizationPayloadKey = "authorization_payload" +) + +// AuthJWT creates a gin middleware for authorization +func AuthJWT(tokenMaker token.Maker) gin.HandlerFunc { + return func(c *gin.Context) { + authorizationHeader := c.GetHeader(authorizationHeaderKey) + + if len(authorizationHeader) == 0 { + err := errors.New("authorization header is not provided") + WrapContext(c).Error(http.StatusUnauthorized, err.Error()) + return + } + + fields := strings.Fields(authorizationHeader) + if len(fields) < 2 { + err := errors.New("invalid authorization header format") + WrapContext(c).Error(http.StatusUnauthorized, err.Error()) + return + } + + authorizationType := strings.ToLower(fields[0]) + if authorizationType != authorizationTypeBearer { + err := fmt.Errorf("unsupported authorization type %s", authorizationType) + WrapContext(c).Error(http.StatusUnauthorized, err.Error()) + return + } + + accessToken := fields[1] + payload, err := tokenMaker.VerifyToken(accessToken) + if err != nil { + WrapContext(c).Error(http.StatusUnauthorized, err.Error()) + return + } + + c.Set(authorizationPayloadKey, payload) + c.Next() + } +}