fix(auth): honour JWT tenant_id claim in middleware

POST /auth/switch-tenant mints an access token whose `tenant_id` claim
points to the target tenant, but the middleware previously discarded
that claim entirely:

    user, err := userService.ValidateToken(ctx, token)  // returned only *User
    targetTenantID := user.TenantID                     // always the home tenant

The session therefore stayed scoped to the user's home tenant despite
the supposedly fresh token, making the new endpoint a no-op once
the request hit any tenant-scoped query.

This change widens the contract:
- UserService.ValidateToken now returns (user, activeTenantID, error)
  where activeTenantID is the JWT's `tenant_id` claim, falling back to
  user.TenantID when the claim is absent (backward compatibility with
  pre-RBAC tokens still in the wild).
- middleware/auth.go uses activeTenantID as the default target before
  applying any X-Tenant-ID header override, and recomputes
  crossTenantSwitch from `activeTenantID != user.TenantID` so the
  resolveTenantRole branches stay correct for switch-tenant sessions.
- The non-middleware /auth/validate handler in handler/auth.go absorbs
  the new return value (it only cares about user identity).

Tests:
- internal/application/service/user_jwt_test.go pins the JWT->tenant-id
  projection (`tenantIDFromClaims`) — claim present beats fallback,
  zero/negative/string claims fall back, int64/uint64 are accepted for
  test-built tokens.

Required for PR 2 multi-tenant integration tests, where a single user
needs to switch between Owner-in-A and Viewer-in-B sessions and observe
distinct authority on each side.
This commit is contained in:
wizardchen
2026-05-13 20:40:17 +08:00
committed by lyingbug
parent f3d1210577
commit af23483433
5 changed files with 143 additions and 14 deletions
+8 -4
View File
@@ -89,12 +89,16 @@ func Auth(
authHeader := c.GetHeader("Authorization")
if authHeader != "" && strings.HasPrefix(authHeader, "Bearer ") {
token := strings.TrimPrefix(authHeader, "Bearer ")
user, err := userService.ValidateToken(c.Request.Context(), token)
user, jwtTenantID, err := userService.ValidateToken(c.Request.Context(), token)
if err == nil && user != nil {
// JWT Token认证成功
// 检查是否有跨租户访问请求
targetTenantID := user.TenantID
crossTenantSwitch := false
// 默认 target = JWT 里的 tenant_id(来自登录或 /auth/switch-tenant),
// 兼容 ValidateToken 的 fallback:claim 缺失时 jwtTenantID == user.TenantID。
targetTenantID := jwtTenantID
if targetTenantID == 0 {
targetTenantID = user.TenantID
}
crossTenantSwitch := targetTenantID != user.TenantID
tenantHeader := c.GetHeader("X-Tenant-ID")
if tenantHeader != "" {
// 解析目标租户ID