Skip to main content

Masquerade Authentication

Introduction

Masquerade authentication enables authorized staff members to temporarily impersonate users for customer support and troubleshooting purposes. Unlike standard login which uses email/password credentials, masquerade auth creates authenticated sessions using pre-generated masquerade tokens, providing staff with secure access to user accounts.

Key Characteristics
  • Session-based: Creates standard authenticated sessions with authMethod for tracking
  • Secure token handling: Tokens are invalidated on error and require fresh authentication

Getting started

Before you begin

Configuration

Basic Configuration

lib/auth/config.ts
import { createAuthConfig } from "@krakentech/blueprint-auth";

export const authConfig = createAuthConfig({
appRoutes: {
dashboard: { pathname: "/dashboard" },
home: { pathname: "/" },
login: { pathname: "/login" },
masquerade: {
// Extract the user ID and token from the URL path.
getMasqueradeParams({ url }) {
const segments = url.pathname.split("/").filter(Boolean);
const [route, userId] = segments;
const masqueradeToken = segments.at(-1);

if (
segments.length >= 3 &&
route === "masquerade" &&
userId &&
masqueradeToken
) {
return { userId, masqueradeToken };
}
},
// Pathname where masquerade URLs are handled
pathname: "/masquerade",
// Redirect after authentication without a dedicated masquerade page.
customSuccessResponse({ url }, { redirect }) {
return redirect(new URL("/dashboard", url.origin));
},
},
},
});

Advanced Configuration (with custom redirects)

lib/auth/config.ts
import { createAuthConfig } from "@krakentech/blueprint-auth";

export const authConfig = createAuthConfig({
appRoutes: {
dashboard: { pathname: "/dashboard" },
home: { pathname: "/" },
login: { pathname: "/login" },
masquerade: {
getMasqueradeParams({ url }) {
const segments = url.pathname.split("/").filter(Boolean);
const [route, userId] = segments;
const masqueradeToken = segments.at(-1);

if (
segments.length >= 3 &&
route === "masquerade" &&
userId &&
masqueradeToken
) {
return { userId, masqueradeToken };
}
},
pathname: "/masquerade",

// Optional: Custom redirect on success
customSuccessResponse({ url }, { redirect }) {
// Example: redirect to dashboard home page
return redirect(new URL("/dashboard", url.origin));
},

// Optional: Custom error handling
customErrorResponse({ url, errorCode }, { redirect }) {
return redirect(new URL(`/login?code=${errorCode}`, url.origin));
},
},
},
});

Configuration Options

OptionTypeRequiredDescription
pathnamestringRoute where masquerade auth is handled
getMasqueradeParams(options: { url: NextURL }) => { userId: string | null | undefined; masqueradeToken: string | null | undefined } | undefinedExtracts userId and masqueradeToken from URL
customSuccessResponse(options: { url: NextURL }, helpers: { redirect, rewrite }) => NextResponse | undefined | Promise<NextResponse | undefined>Override redirect after successful authentication
customErrorResponse(options: { url: NextURL; errorCode: ErrorCode }, helpers: { redirect, rewrite }) => NextResponse | undefined | Promise<NextResponse | undefined>Override redirect on authentication failure

Middleware

middleware.ts
import { createAuthMiddleware } from "@krakentech/blueprint-auth/middleware";
import { authConfig } from "@/lib/auth/config";

export const middleware = createAuthMiddleware(authConfig);

export const config = {
matcher: ["/", "/((?!api|_next|_vercel|.*\\..*).*)"],
};

See matcher coverage for the recommended pattern and exclusions.

Masquerade route

You do not need a dedicated masquerade page. The middleware handles authentication when staff navigate to /masquerade/{userId}/.../{masqueradeToken}. The middle segments are optional.

Use appRoutes.masquerade.customSuccessResponse to redirect staff to the dashboard after authentication, as shown in the advanced configuration above. Keep any account-specific routing in your existing dashboard rather than a separate masquerade page.

Session state

Check auth at server boundaries

Middleware verifies masquerade tokens on matched routes, but does not replace checks at protected server boundaries. Use getAuth.user and enforce resource permissions before accessing protected data or performing mutations in pages, API routes, Route Handlers, and Server Actions. Session-based UI indicators do not authorize an operation. See Route protection.

Checking session state is useful when you need to display masquerade-specific UI elements or track staff activity. Use getSession or useSession to conditionally render masquerade indicators and apply different behavior for masqueraded sessions.

Session state fields

FieldValueDescription
authMethod"masquerade"The verified grant is MASQUERADE
authSource"web"The token came from the web accessToken cookie
isAuthenticatedtrueThe request has a verified user token
Session replacement

A successful masquerade request clears the current managed session. Blueprint Auth then stores the verified token in accessToken. A failed masquerade request also clears the managed session. This prevents use of the previous user identity after a failure.

See Session management for an overview of the session lifecycle.

Common patterns

When to use this

Display a visual indicator when staff are masquerading to prevent confusion and ensure they're aware they're viewing a customer's account.

Example

A header component that displays a prominent masquerade banner when staff are impersonating a user, helping prevent accidental actions on customer accounts.

Show implementation
components/Header.tsx
"use client";

import { useSession } from "@/lib/auth/client";
import { Logo } from "@/components/Logo";
import { LogoutButton } from "@/components/LogoutButton";
import { MasqueradeBadge } from "@/components/MasqueradeBadge";
import { NavigationMenu } from "@/components/NavigationMenu";

export function Header() {
const { data: session, isError, isFetched } = useSession();

return (
<header>
{!isFetched ? (
<p role="status">Loading session...</p>
) : isError ? (
<p role="alert">Unable to load the session.</p>
) : (
<>
{session.authMethod === "masquerade" && <MasqueradeBadge />}
{session.isAuthenticated && <LogoutButton />}
</>
)}
<NavigationMenu />
<Logo />
</header>
);
}

Security Considerations

Security Notes
  1. Token sensitivity: masquerade tokens grant full account access. Handle them as passwords.
  2. HTTPS only: never transmit masquerade tokens over unencrypted connections.
  3. Token invalidation: authentication errors clear the tokens.
  4. No token refresh: masquerade tokens cannot be refreshed. Staff must authenticate again.

FAQ

How does masquerade authentication work?
  1. Staff clicks masquerade button in Kraken support site, which navigates to masquerade URL with embedded token, for example /masquerade/{userId}/.../{masqueradeToken}
  2. Next.js middleware intercepts the request
  3. getMasqueradeParams function extracts userId and masqueradeToken from URL
  4. Middleware calls masqueradeAuthentication GraphQL mutation with the token and user ID
  5. Kraken validates the token and user ID, then returns an access token.
  6. Middleware verifies tokenUse: "access" and gty: "MASQUERADE".
  7. Middleware clears the current managed session.
  8. Middleware stores the token in accessToken.
  9. Staff gains access to the user's account.
What happens if a staff member is already authenticated?

The middleware removes all managed session cookies. It then creates a new masquerade session. This prevents use of the staff member's identity or an old masquerade identity.

How do staff exit masquerade mode?

Staff exit masquerade mode by using the standard logout functionality. Call the logout function or use the useLogout hook. Logout clears the managed session cookies, including accessToken.

What happens when a masquerade token is invalid?

When an invalid masquerade token is provided:

  1. Authentication fails in middleware.
  2. Blueprint Auth clears all managed session cookies and oAuthIdToken.
  3. Blueprint Auth keeps pkceVerifier for an OAuth flow that is in progress.
  4. The user is redirected to the login page or the configured error page.
  5. Staff must get a new masquerade token before they try again.

Next Steps

Now that you have masquerade authentication configured, explore these related guides:

API Reference

Quick reference to relevant functions: