package svc import ( "errors" "fmt" "fusenapi/server/home-user-auth/internal/config" "net/http" "github.com/golang-jwt/jwt" "github.com/zeromicro/go-zero/core/stores/sqlx" ) type ServiceContext struct { Config config.Config MysqlConn sqlx.SqlConn } func NewServiceContext(c config.Config) *ServiceContext { return &ServiceContext{ Config: c, MysqlConn: sqlx.NewMysql(c.SourceMysql), } } func (svcCxt *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { AuthKey := r.Header.Get("Authorization") if AuthKey == "" { return nil, nil } token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) { // 检查签名方法是否为 HS256 if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } // 返回用于验证签名的密钥 return []byte(svcCxt.Config.Auth.AccessSecret), nil }) if err != nil { return nil, errors.New(fmt.Sprint("Error parsing token:", err)) } // 验证成功返回 if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { return claims, nil } return nil, errors.New(fmt.Sprint("Invalid token", err)) }