From 9cc47d6532422fd8773f119510097758e730e9ae Mon Sep 17 00:00:00 2001 From: zyj <18107291228@163.com> Date: Thu, 11 Sep 2025 14:37:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Etoken=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E4=B8=AD=E9=97=B4=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/token_auth.go | 45 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 middleware/token_auth.go diff --git a/middleware/token_auth.go b/middleware/token_auth.go new file mode 100644 index 0000000..9ce04b5 --- /dev/null +++ b/middleware/token_auth.go @@ -0,0 +1,45 @@ +package middleware + +import ( + "context" + grpcClient "go-desk-service/grpc-client" + "go-desk-service/libs" + userpb "go-desk-service/proto/gen" + "net/http" + "time" + + "github.com/gin-gonic/gin" +) + +func TokenAuth() gin.HandlerFunc { + return func(c *gin.Context) { + // 调用当前grpc的token校验接口 + client := grpcClient.GetUserClient() + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + defer cancel() + authHeader := c.GetHeader("Authorization") + if authHeader == "" { + tokenExpired := libs.ErrorCode["TokenExpired"] + c.JSON(http.StatusUnauthorized, gin.H{"code": tokenExpired.Code, "data": tokenExpired.Data, "msg": tokenExpired.Msg}) + c.Abort() + return + } + TokenStatus, err := client.ValidateToken(ctx, &userpb.ValidateTokenRequest{ + AccessToken: authHeader, + }) + if err != nil { + tokenExpired := libs.ErrorCode["TokenExpired"] + c.JSON(http.StatusUnauthorized, gin.H{"code": tokenExpired.Code, "data": tokenExpired.Data, "msg": tokenExpired.Msg}) + c.Abort() + return + } + if !TokenStatus.IsValid { + tokenExpired := libs.ErrorCode["TokenExpired"] + c.JSON(http.StatusUnauthorized, gin.H{"code": tokenExpired.Code, "data": tokenExpired.Data, "msg": tokenExpired.Msg}) + c.Abort() + return + } + c.Set("userID", TokenStatus.UserId) + c.Next() + } +}