45 lines
1.6 KiB
Go
45 lines
1.6 KiB
Go
package handler
|
||||
|
|
|
|||
|
|
import (
|
|||
|
|
"context"
|
|||
|
|
"net/http"
|
|||
|
|
"strings"
|
|||
|
|
|
|||
|
|
tokenx "bj_power_mes/common/token"
|
|||
|
|
"bj_power_mes/internal/svc"
|
|||
|
|
|
|||
|
|
"github.com/zeromicro/go-zero/rest"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// AdminJwtAuth MES 后台 JWT 鉴权中间件(2026-11-24 替换 go-zero rest.WithJwt)。
|
|||
|
|
// go-zero 1.8.3 的 rest.WithJwt 用本机时间严格校 exp、无 leeway,后台机器时钟漂一点就 401;
|
|||
|
|
// 这里改用 tokenx.Parse——按签发方服务器时间验 exp + 10 分钟容差,并把 claims 注入 context,
|
|||
|
|
// 保持与 go-zero 原生 WithJwt 一致(userId/name/username/roleCode 等 key 不变,下游 handler 无感)。
|
|||
|
|
func AdminJwtAuth(svcCtx *svc.ServiceContext) rest.Middleware {
|
|||
|
|
return func(next http.HandlerFunc) http.HandlerFunc {
|
|||
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|||
|
|
auth := r.Header.Get("Authorization")
|
|||
|
|
if !strings.HasPrefix(auth, "Bearer ") {
|
|||
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
claims, err := tokenx.Parse(svcCtx.Config.Auth.AccessSecret, strings.TrimPrefix(auth, "Bearer "))
|
|||
|
|
if err != nil || claims == nil {
|
|||
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
ctx := r.Context()
|
|||
|
|
ctx = context.WithValue(ctx, "userId", claims.UserId)
|
|||
|
|
ctx = context.WithValue(ctx, "username", claims.Username)
|
|||
|
|
ctx = context.WithValue(ctx, "name", claims.Name)
|
|||
|
|
ctx = context.WithValue(ctx, "roleId", claims.RoleId)
|
|||
|
|
ctx = context.WithValue(ctx, "roleCode", claims.RoleCode)
|
|||
|
|
ctx = context.WithValue(ctx, "roleName", claims.RoleName)
|
|||
|
|
if claims.Sid != "" {
|
|||
|
|
ctx = context.WithValue(ctx, "sid", claims.Sid)
|
|||
|
|
}
|
|||
|
|
next(w, r.WithContext(ctx))
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|