iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
⚡

3 Pitfalls of Keycloak Multi-Portal Authentication [Part 5]

に公開

Architecture

Saru consists of four portals: System, Provider, Reseller, and Consumer. Each operates on a different subdomain but shares a single Keycloak realm.

system.saru.local   (port 3001)  →  Keycloak
provider.saru.local (port 3002)  →  (single realm,
reseller.saru.local (port 3003)  →   4 clients)
consumer.saru.local (port 3004)  →

Basic Keycloak + Auth.js integration is well-covered by existing tutorials. This article addresses the issues that those tutorials often leave out.

Problem

Expecting future needs, I wanted to share sessions across subdomains, so I configured it as follows:

cookies: {
  sessionToken: {
    options: {
      domain: '.saru.local',  // Share across subdomains
    },
  },
}

Result: When I logged in to the System Portal, the same session appeared in the Provider Portal. However, it was the wrong user context. The System administrator's token was being used in the Provider Portal.

Why it happens

Auth.js uses cookie names like authjs.session-token (or __Secure-authjs.session-token over HTTPS). By setting domain: '.saru.local', all subdomains share the same cookie. Whichever portal sets the cookie first wins, and subsequent logins on other portals read the same cookie.

Note: Cookie names vary depending on the Auth.js version and configuration (e.g., next-auth.session-token in older versions). Check the actual cookie name in browser DevTools.

system.saru.local   → authjs.session-token set (domain=.saru.local)
provider.saru.local → reads same cookie → Wrong context!

Solution

Use portal-prefixed cookie names:

// packages/auth/src/config.ts

export function getAuthConfig({ portal }: { portal: PortalType }) {
  return {
    cookies: {
      sessionToken: {
        name: `authjs.${portal}-session-token`,  // e.g., authjs.system-session-token
        options: {
          domain: COOKIE_DOMAIN,
        },
      },
      callbackUrl: {
        name: `authjs.${portal}-callback-url`,
      },
      csrfToken: {
        name: `authjs.${portal}-csrf-token`,
      },
      // Prefix state/pkceCodeVerifier as well if using OAuth flows
    },
    // ...
  };
}

Note: Auth.js uses additional cookies (state, pkceCodeVerifier) for OAuth flows. If multiple portals perform logins simultaneously, prefixing these will prevent intermittent authentication failures.

Now, each portal has its own session:

system.saru.local   → authjs.system-session-token
provider.saru.local → authjs.provider-session-token  ✓

Lesson learned

If you don't need sharing across subdomains, omit the domain field. Cookies default to being host-only, which avoids this problem.

Pitfall 2: Custom Claims Missing from Tokens

Problem

The backend requires tenant context: account_id, account_type, and capabilities. I stored these as Keycloak user attributes, but they were missing from the token.

// Expected in profile
profile.account_id      // undefined
profile.capabilities    // undefined

Why it happens

Keycloak does not automatically include user attributes in tokens. Protocol Mappers are required. Furthermore, there are a few things to watch out for.

Solution

Step 1: Create Protocol Mappers

For each attribute, create a mapper in Keycloak:

Setting Value
Mapper Type User Attribute
User Attribute account_id
Token Claim Name account_id
Add to ID token ON
Add to access token ON (if API validates access token)
Add to userinfo ON

Important: If you add the mapper to a Client Scope, ensure that the scope is assigned to the client (either as default or optional). Otherwise, the mapper will not execute.

Step 2: Handle Multivalued Attributes Correctly

I initially stored capabilities (an array of strings) as a JSON string:

// Incorrect! Storing a string literal
{ "attributes": { "capabilities": "[\"CONSUME\", \"PROVIDE\"]" } }

Keycloak's "Multivalued" mapper expects individual values, not a JSON string. Important: Ensure "Multivalued" is set to ON in the mapper settings.

// Correct: Keycloak Admin API user update payload
{ "attributes": { "capabilities": ["CONSUME", "PROVIDE"] } }

The Keycloak Admin API accepts arrays directly within the attributes map:

// When syncing capabilities from the app via Admin API
userUpdate := map[string]interface{}{
    "attributes": map[string][]string{
        "capabilities": {"CONSUME", "PROVIDE"},  // Array, not JSON string
    },
}

Step 3: Custom Scopes (Easily Overlooked)

When requesting scope: 'openid roles account_info', custom scopes like account_info must exist in Keycloak. Standard OIDC only provides openid, profile, and email.

Note: roles is not a standard OIDC scope but a Keycloak client scope with a role mapper. If the default client scope includes a role mapper, roles might be included in the token even without explicitly requesting the roles scope. However, if you explicitly request roles as a scope, ensure the roles client scope is assigned to the client.

You need to create Client Scopes for custom scopes like account_info in Keycloak and assign them to the client. Scopes that do not exist or are unassigned are silently ignored, resulting in the expected claims not being included in the token.

Lesson learned

Test the token content early. Decode the token locally (e.g., jwt-cli, browser DevTools, or a local script) and verify that the claims are present before writing the frontend code.

Security warning: Do not paste production tokens into online decoders like jwt.io, as these are third-party services. Use local tools for actual tokens.

Pitfall 3: Token Exposure in Session

Problem

Since I call the API directly, I needed an access token on the client side:

// Session callback - Exposing token to the client
async session({ session, token }) {
  return {
    ...session,
    accessToken: token.accessToken,  // Exposed to client JS
  };
}

Prerequisite: For token.accessToken to exist, it must be saved in the jwt callback during sign-in (e.g., token.accessToken = account.access_token). The refreshToken should be handled similarly.

This works, but there are security trade-offs that I didn't fully consider at first.

Why it's a risk

Having accessToken in the session makes it accessible from any JavaScript on the page:

const { data: session } = useSession();
console.log(session.accessToken);  // Possible from any script

If there is an XSS vulnerability, an attacker can steal the token.

Trade-offs

Approach Pros Cons
Token Exposure Simple, direct API calls from the browser Potential token theft via XSS
BFF Pattern Tokens remain server-side, client only calls the BFF Increased complexity, all traffic via Next.js

Note: "Proxying all calls" is essentially the BFF pattern. The key question is whether the client holds the bearer token.

Saru's Choice

We accept the risk but have implemented multi-layered defenses:

  1. Strict CSP: Limits executable scripts (not perfect, but reduces the attack surface).
  2. Short Expiration: Tokens expire in 5 minutes (limits the damage window if stolen).
  3. Refresh Token Rotation: Issues a new refresh token with every refresh (requires "Revoke Refresh Token" to be enabled in Keycloak realm/client settings).

Honest assessment: These mitigations reduce risk but do not eliminate it. If an XSS vulnerability exists, it means full account compromise for the duration of the token's validity. If refresh tokens are also exposed in the session, an attacker can extend access beyond the 5-minute window. We accept this trade-off in the context of a B2B SaaS with trusted users and no user-generated content.

// Token refresh with refresh token rotation
return {
  accessToken: refreshedTokens.access_token,
  refreshToken: refreshedTokens.refresh_token ?? token.refreshToken,
  expiresAt: Math.floor(Date.now() / 1000) + refreshedTokens.expires_in,
};

Lesson learned

There is no universal "correct answer." Understand your threat model. For a B2B SaaS with trusted users, token exposure with mitigations is acceptable. For consumer apps with user-generated content (XSS risk), consider a BFF.

Bonus: Error Handling for Token Refresh

Another thing I stumbled upon: how to properly handle refresh failures.

// Note: client_secret is for confidential clients (server-side).
// For public clients (SPA), use PKCE without client_secret.
async function refreshAccessToken(token: JWT): Promise<JWT> {
  const response = await fetch(tokenEndpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token: token.refreshToken as string,
      client_id: clientId,
      client_secret: clientSecret,  // Confidential clients only
    }),
  });

  // Defensive: Some error responses might not be JSON
  let refreshedTokens;
  try {
    refreshedTokens = await response.json();
  } catch {
    return { ...token, error: 'TokenRefreshFailed' };
  }

  if (!response.ok) {
    // Don't just throw, return an error state
    const error = refreshedTokens.error;
    const errorDesc = refreshedTokens.error_description || '';

    // Check for user-related errors
    if (errorDesc.includes('deleted') || errorDesc.includes('disabled')) {
      return { ...token, error: 'UserDeleted' };
    }
    // invalid_grant covers expired/revoked refresh tokens
    if (error === 'invalid_grant') {
      return { ...token, error: 'TokenRefreshFailed' };
    }
    return { ...token, error: 'TokenRefreshFailed' };
  }

  // Defensive: expires_in might be missing in edge cases
  const expiresIn = refreshedTokens.expires_in ?? 300; // Default 5 minutes

  return {
    ...token,
    accessToken: refreshedTokens.access_token,
    refreshToken: refreshedTokens.refresh_token ?? token.refreshToken,
    expiresAt: Math.floor(Date.now() / 1000) + expiresIn,
  };
}

Handling in the app:

const { data: session } = useSession();

if (session?.error === 'TokenRefreshFailed') {
  // Force re-login instead of displaying a confusing error
  signIn('keycloak');
}

Summary

Pitfall Solution
Cookie Conflict Portal-prefixed cookie names
Missing Claims Protocol Mappers + correct attribute format
Token Exposure Accept trade-offs and mitigate, or use BFF

The basics of Keycloak + Auth.js are well-documented. These edge cases are what take time to debug. I hope this article helps save you that time.

Discussion