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" },
login: { pathname: "/login" },
masquerade: {
// Extract userId and masqueradeToken from URL path
getMasqueradeParams({ url }) {
const [_masquerade, userId, masqueradeToken] = url.pathname
.split("/")
.filter(Boolean);
return { userId, masqueradeToken };
},
// Pathname where masquerade URLs are handled
pathname: "/masquerade",
},
},
});

Advanced Configuration (with custom redirects)

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

export const authConfig = createAuthConfig({
appRoutes: {
dashboard: { pathname: "/dashboard" },
login: { pathname: "/login" },
masquerade: {
getMasqueradeParams({ url }) {
const [_masquerade, userId, masqueradeToken] = url.pathname.split("/");
if (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 | undefinedOverride redirect after successful authentication
customErrorResponse(options: { url: NextURL; errorCode: ErrorCode }, helpers: { redirect, rewrite }) => NextResponse | undefinedOverride 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: ["/dashboard/:path*", "/login", "/masquerade/:path*"],
};
Matcher must include masquerade path

The middleware matcher array must include your appRoutes.masquerade.pathname value, otherwise the masquerade auth flow won't trigger.

Masquerade route

Create a page that handles the masquerade authentication flow. The middleware automatically authenticates the user and sets the masqueradeToken cookie when staff navigate to the masquerade URL. After successful authentication, the page typically redirects users to the dashboard.

pages/masquerade/[userId]/[masqueradeToken].tsx
import type { GetServerSidePropsContext } from "next";
import { getUserScopedGraphQLClient } from "@/lib/auth/server";
import { graphql } from "@/lib/graphql";

// This page component never renders - users are redirected in getServerSideProps
export default function MasqueradePage() {
return null;
}

const ViewerQuery = graphql(`
query MasqueradeViewer {
viewer {
accounts {
number
}
}
}
`);

export async function getServerSideProps(
context: GetServerSidePropsContext<{
userId: string;
masqueradeToken: string;
}>,
) {
// The masqueradeToken cookie is already set by middleware
// Fetch the user's first account and redirect to dashboard
const graphQLClient = getUserScopedGraphQLClient({ context });
const { viewer } = await graphQLClient.request(ViewerQuery);

const accountNumber = viewer?.accounts?.at(0)?.number;

if (!accountNumber) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}

return {
redirect: {
destination: `/dashboard/accounts/${accountNumber}`,
permanent: false,
},
};
}
Automatic Authentication

The middleware handles authentication automatically when staff navigate to /masquerade/{userId}/{masqueradeToken}. Your page component only needs to handle the post-authentication redirect.

Session state

Middleware handles security

The middleware ensures staff have valid masquerade tokens before reaching your page components. You don't need to check session state for security purposes.

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"Indicates staff member is authenticated via masquerade
isAuthenticatedtrueUser has valid authentication (any supported auth cookie)
Highest Priority

Masquerade authentication has the highest priority among all authentication methods. When a masquerade URL is accessed, any existing authentication (including full login sessions, scoped tokens, or mobile web view tokens) is cleared and replaced with the masquerade session. This ensures clean session state and prevents conflicts between the staff member's own account and the masqueraded user account.

Priority order:

  1. masquerade - Highest priority (current method)
  2. mobile-web-view - Mobile app integration
  3. oauth or email - Full authenticated sessions
  4. scoped - Anonymous/pre-signed key access

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: { isAuthenticated, authMethod },
} = useSession();

return (
<header>
{authMethod === "masquerade" && <MasqueradeBadge />}
<NavigationMenu />
<Logo />
{isAuthenticated && <LogoutButton />}
</header>
);
}

Security Considerations

Security Notes
  1. Token sensitivity: Masquerade tokens grant full account access - handle with the same security as passwords
  2. HTTPS only: Never transmit masquerade tokens over unencrypted connections
  3. Token invalidation: Tokens are automatically cleared on authentication errors
  4. No token refresh: Masquerade tokens cannot be refreshed - staff must re-authenticate

FAQ

How does masquerade authentication work?
  1. Staff clicks masquerade button in Kraken support site, which navigates to masquerade URL with embedded token (e.g., /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, returns a session token
  6. Middleware sets masqueradeToken and authProvider=masquerade cookies
  7. Staff gains authenticated access to the user's account
  8. Session persists until logout or masquerade token expiration
What happens if a staff member is already authenticated?

When a masquerade URL is accessed, the middleware removes all existing auth cookies and establishes a fresh masquerade session. This ensures clean session state and prevents conflicts between staff's own account and the masqueraded user account.

How do staff exit masquerade mode?

Staff exit masquerade mode by using the standard logout functionality. Call the logout mutation or use the useLogout hook, which clears all authentication cookies including the masquerade token.

What happens when a masquerade token is invalid?

When an invalid masquerade token is provided:

  1. Authentication fails at the middleware level
  2. The masqueradeToken and authProvider cookies are cleared (even if a valid token from another session exists)
  3. User is redirected to the login page (or custom error page if configured)
  4. Staff must obtain a new masquerade token to retry

Next Steps

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

API Reference

Quick reference to relevant functions: