tianyuan-api-server/apps/gateway/internal/middleware/authinterceptormiddleware.go
2024-10-02 00:57:17 +08:00

55 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"context"
"errors"
"github.com/zeromicro/go-zero/core/logx"
xhttp "github.com/zeromicro/x/http"
"tianyuan-api/apps/gateway/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))
}
}