tianyuan-api-server/apps/admin/internal/middleware/authinterceptormiddleware.go

55 lines
1.4 KiB
Go
Raw Normal View History

2024-10-02 00:57:17 +08:00
package middleware
import (
"context"
"errors"
"github.com/zeromicro/go-zero/core/logx"
xhttp "github.com/zeromicro/x/http"
"tianyuan-api/apps/admin/internal/config"
jwtx "tianyuan-api/pkg/jwt"
"net/http"
"time"
)
type AuthInterceptorMiddleware struct {
Config config.Config
}
func NewAuthInterceptorMiddleware(c config.Config) *AuthInterceptorMiddleware {
return &AuthInterceptorMiddleware{
Config: c,
}
}
func (m *AuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 从 Cookie 中获取 JWT
cookie, err := r.Cookie("Authorization")
if err != nil {
xhttp.JsonBaseResponseCtx(r.Context(), w, errors.New("用户未登录"))
return
}
tokenStr := cookie.Value
// 验证并解析 JWT
userId, err := jwtx.ParseJwtToken(tokenStr, m.Config.AuthJWT.AccessSecret)
if err != nil {
// 设置过期的 Cookie 来删除无效的 Token
http.SetCookie(w, &http.Cookie{
Name: "Authorization",
Value: "",
Path: "/",
HttpOnly: true,
Expires: time.Unix(0, 0), // 过期时间设置为过去
})
logx.Error("Invalid JWT: ", err)
xhttp.JsonBaseResponseCtx(r.Context(), w, errors.New("未经授权的访问"))
return
}
// 将 userId 存入 context供后续逻辑使用
ctx := context.WithValue(r.Context(), "userId", userId)
next(w, r.WithContext(ctx))
}
}