Multi-account Authentication

Multi-account authentication integration for external platforms.

Running this example

To run this example locally:

  1. If you haven't already, create a new app in the Developer Portal(opens in a new tab or window). For more information, refer to our Quickstart guide.

  2. In your app's configuration on the Developer Portal(opens in a new tab or window), ensure the "Development URL" is set to http://localhost:8080.

  3. Clone the starter kit:

    git clone https://github.com/canva-sdks/canva-apps-sdk-starter-kit.git
    cd canva-apps-sdk-starter-kit
    SHELL
  4. Install dependencies:

    npm install
    SHELL
  5. Run the example:

    npm run start multi_account_authentication
    SHELL
  6. Click the Preview URL link shown in the terminal to open the example in the Canva editor.

Example app source code

import React from "react";
import {
Avatar,
Button,
Columns,
Column,
Rows,
Title,
Text,
Box,
FlyoutMenu,
FlyoutMenuItem,
FlyoutMenuDivider,
CheckIcon,
PlusIcon,
CogIcon,
LinkButton,
ArrowLeftIcon,
Alert,
} from "@canva/app-ui-kit";
import type { OauthAccount } from "@canva/user";
export enum View {
Switcher = "Switcher",
Manage = "Manage",
}
type AccountSwitcherMenuItemProps =
| {
account: OauthAccount;
isActive: boolean;
variant: View.Switcher;
onSwitch: () => void;
onSignInAgain: () => void;
}
| {
account: OauthAccount;
isActive: boolean;
variant: View.Manage;
onDisconnect: () => void;
};
const AccountSwitcherMenuItem = (props: AccountSwitcherMenuItemProps) => {
const { account, isActive } = props;
const variant = props.variant ?? View.Switcher;
const avatar = (
<Avatar name={account.displayName} photo={account.avatarUrl} />
);
const nameAndEmail = (
<Rows spacing="0">
<Columns spacing="1u" alignY="center">
<Column>
<Text size="medium" tone="primary">
{account.displayName}{" "}
{isActive && variant === View.Manage ? "(Current)" : ""}
</Text>
</Column>
</Columns>
<Text size="small" tone="tertiary">
{account.principal}
</Text>
</Rows>
);
if (variant === View.Manage) {
const { onDisconnect } = props as Extract<
AccountSwitcherMenuItemProps,
{ variant: View.Manage }
>;
const getEndContent = () => {
return (
<Text size="small" tone="critical">
<LinkButton onClick={() => onDisconnect()}>
<span
style={{
color: "var(--ui-kit-color-feedback-critical-bg)",
textDecoration: "underline",
}}
>
Disconnect
</span>
</LinkButton>
</Text>
);
};
return (
<Box paddingY="1u" paddingX="2u">
<Columns spacing="1u" align="spaceBetween" alignY="center">
<Column>
<Columns spacing="1u" alignY="center">
<Column width="content">{avatar}</Column>
<Column>{nameAndEmail}</Column>
</Columns>
</Column>
<Column width="content">{getEndContent()}</Column>
</Columns>
</Box>
);
}
// Switcher view
const { onSwitch } = props as Extract<
AccountSwitcherMenuItemProps,
{ variant: View.Switcher }
>;
const getEndContent = () => {
if (isActive) {
return <CheckIcon />;
}
return null;
};
const handleClick = () => {
if (isActive) {
return;
}
onSwitch();
};
return (
<FlyoutMenuItem
start={avatar}
end={getEndContent()}
onClick={handleClick}
disabled={isActive}
>
{nameAndEmail}
</FlyoutMenuItem>
);
};
const AccountSwitcherView = ({
accounts,
selectedAccountId,
onAccountSwitch,
onSignInAgain,
appName,
}: {
accounts: OauthAccount[];
selectedAccountId: string | null;
onAccountSwitch: (accountId: string) => void;
onSignInAgain: (accountId: string) => void;
appName: string;
}) => {
return (
<>
<FlyoutMenuDivider>{`Switch ${appName} accounts`}</FlyoutMenuDivider>
{accounts.map((account) => (
<AccountSwitcherMenuItem
key={account.id}
account={account}
isActive={account.id === selectedAccountId}
variant={View.Switcher}
onSwitch={() => onAccountSwitch(account.id)}
onSignInAgain={() => onSignInAgain(account.id)}
/>
))}
</>
);
};
const AccountSwitcherFooter = ({
accounts,
onAddAccount,
onManageAccounts,
}: {
accounts: OauthAccount[];
onAddAccount: () => void;
onManageAccounts: () => void;
}) => {
return (
<>
<FlyoutMenuDivider />
{accounts.length >= 4 ? (
<Box paddingX="1u" paddingBottom="0.5u">
<Alert tone="info" title="You've reached the limit.">
<br />
Remove an account to add a new one.
</Alert>
</Box>
) : (
<FlyoutMenuItem start={<PlusIcon />} onClick={onAddAccount}>
Add another account
</FlyoutMenuItem>
)}
<FlyoutMenuItem start={<CogIcon />} onClick={() => onManageAccounts()}>
Manage accounts
</FlyoutMenuItem>
</>
);
};
const ManageAccountsView = ({
accounts,
selectedAccountId,
onDisconnect,
onBack,
appName,
}: {
accounts: OauthAccount[];
selectedAccountId: string | null;
onDisconnect: (accountId: string) => void;
onBack: () => void;
appName: string;
}) => {
return (
<>
<Box paddingX="1u">
<Columns spacing="1u" alignY="center">
<Column width="containedContent">
<Button
variant="tertiary"
size="small"
icon={ArrowLeftIcon}
onClick={() => onBack()}
ariaLabel="Go back"
/>
</Column>
<Column>
<Title size="xsmall">Manage {appName} accounts</Title>
</Column>
</Columns>
</Box>
<FlyoutMenuDivider />
<Rows spacing="0">
{accounts.map((account) => (
<AccountSwitcherMenuItem
key={account.id}
account={account}
isActive={account.id === selectedAccountId}
variant={View.Manage}
onDisconnect={() => onDisconnect(account.id)}
/>
))}
</Rows>
</>
);
};
export interface AccountSelectorProps {
currentView: View;
setCurrentView: (view: View) => void;
accounts: OauthAccount[];
selectedAccountId: string | null;
triggerLabel: string;
appName: string;
onAccountSwitch: (accountId: string) => void;
onAddAccount: () => void;
onSignInAgain: (accountId: string) => void;
onManageAccounts: () => void;
onBack: () => void;
onDisconnect: (accountId: string) => void;
}
export const AccountSelector = ({
currentView,
setCurrentView,
accounts,
selectedAccountId,
triggerLabel,
appName,
onAccountSwitch,
onAddAccount,
onSignInAgain,
onManageAccounts,
onBack,
onDisconnect,
}: AccountSelectorProps) => {
const handleManageAccounts = () => {
setCurrentView(View.Manage);
onManageAccounts();
};
const handleBack = () => {
if (currentView === View.Manage) {
setCurrentView(View.Switcher);
onBack();
}
};
const handleAccountSwitch = (accountId: string) => {
onAccountSwitch(accountId);
};
const renderContent = () => {
if (currentView === View.Switcher) {
return (
<>
<AccountSwitcherView
accounts={accounts}
selectedAccountId={selectedAccountId}
onAccountSwitch={handleAccountSwitch}
onSignInAgain={onSignInAgain}
appName={appName}
/>
<AccountSwitcherFooter
accounts={accounts}
onAddAccount={onAddAccount}
onManageAccounts={handleManageAccounts}
/>
</>
);
}
if (currentView === View.Manage) {
return (
<ManageAccountsView
accounts={accounts}
selectedAccountId={selectedAccountId}
onDisconnect={onDisconnect}
onBack={handleBack}
appName={appName}
/>
);
}
return null;
};
const handleClose = () => {
// Reset to switcher view when flyout closes
setCurrentView(View.Switcher);
};
return (
<Box>
<FlyoutMenu
label={triggerLabel}
flyoutPlacement="bottom-start"
onClose={handleClose}
>
{renderContent()}
</FlyoutMenu>
</Box>
);
};
TYPESCRIPT
// For usage information, see the README.md file.
import {
Avatar,
Button,
Columns,
Column,
LoadingIndicator,
Rows,
Title,
Text,
Box,
} from "@canva/app-ui-kit";
import { useMemo, useState, useEffect, useCallback } from "react";
import { auth } from "@canva/user";
import type { OauthAccount } from "@canva/user";
import * as styles from "styles/components.css";
import { AccountSelector, View } from "./account_selector";
// Provider name as defined in the Developer Portal
const PROVIDER = "my_provider_name" as const;
const scope = new Set(["profile", "email", "openid"]);
const BASE_URL = `${BACKEND_HOST}/userinfo`;
export function App() {
const [accounts, setAccounts] = useState<OauthAccount[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [profile, setProfile] = useState<Record<string, unknown> | null>(null);
const [profileError, setProfileError] = useState<string | null>(null);
const [currentView, setCurrentView] = useState<View>(View.Switcher);
const [selectedAccountId, setSelectedAccountId] = useState<string | null>(
null,
);
const oauth = useMemo(
// Initialize the Canva OAuth client for user authentication
() => auth.initOauth({ type: "multi_account", provider: PROVIDER }),
[],
);
const retrieveAccounts = useCallback(async () => {
setLoading(true);
try {
const res = await oauth.getAccounts();
setAccounts(res.accounts);
// Set the first account as selected if none is selected
if (!selectedAccountId && res.accounts.length > 0) {
setSelectedAccountId(res.accounts[0]?.id ?? null);
}
} catch (error) {
setError(error instanceof Error ? error.message : "Unknown error");
} finally {
setLoading(false);
}
}, [selectedAccountId, oauth]);
useEffect(() => {
// Check if the user is already authenticated when the component mounts
retrieveAccounts();
}, [oauth, retrieveAccounts]);
const authorize = useCallback(async () => {
setError(null);
setLoading(true);
try {
await oauth.requestAuthorization({
scope,
queryParams: { access_type: "offline", prompt: "login" },
});
// Call retrieveAccounts after authorization
await retrieveAccounts();
// Reset the view to Switcher after successful authorization
setCurrentView(View.Switcher);
} catch (error) {
setError(error instanceof Error ? error.message : "Unknown error");
} finally {
setLoading(false);
}
}, [oauth, retrieveAccounts]);
const handleAccountSwitch = useCallback((accountId: string) => {
setSelectedAccountId(accountId);
// Clear profile data when switching accounts
setProfile(null);
setProfileError(null);
}, []);
const handleManageAccounts = useCallback(() => {
setCurrentView(View.Manage);
}, []);
const handleBack = useCallback(() => {
setCurrentView(View.Switcher);
}, []);
const handleDisconnect = useCallback(
async (accountId: string) => {
const account = accounts.find((acc) => acc.id === accountId);
if (account) {
setLoading(true);
try {
await account.deauthorize();
// If we're disconnecting the selected account, select the first remaining account
if (selectedAccountId === accountId) {
const remainingAccounts = accounts.filter(
(acc) => acc.id !== accountId,
);
setSelectedAccountId(remainingAccounts[0]?.id ?? null);
}
// Clear profile data when disconnecting any account
setProfile(null);
setProfileError(null);
await retrieveAccounts();
} finally {
setLoading(false);
}
}
},
[accounts, selectedAccountId, retrieveAccounts],
);
const handleSignInAgain = useCallback(
async (accountId: string) => {
await authorize();
},
[authorize],
);
const handleAddAccount = useCallback(async () => {
await authorize();
}, [authorize]);
const fetchProfile = useCallback(async (account: OauthAccount) => {
setLoading(true);
setProfileError(null);
setProfile(null);
try {
// Get access token for the account using the correct OAuth client
const tokenResponse = await account.getAccessToken({ scope });
if (!tokenResponse) {
throw new Error("Failed to get access token");
}
// Make request to Auth0 userinfo endpoint
const response = await fetch(`${BASE_URL}/userinfo`, {
method: "GET",
headers: {
Authorization: `Bearer ${tokenResponse.token}`,
Accept: "application/json",
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const profileData = await response.json();
// Add provider information to the profile data for display
setProfile(profileData);
} catch (error) {
setProfileError(error instanceof Error ? error.message : "Unknown error");
} finally {
setLoading(false);
}
}, []);
const result = (
<div className={styles.scrollContainer}>
<Box
justifyContent="center"
width="full"
height="full"
alignItems="center"
display="flex"
>
{error ? (
<Rows spacing="2u">
<Title>Authorization error</Title>
<Text>{error}</Text>
<Button variant="primary" onClick={() => authorize()}>
Try again
</Button>
</Rows>
) : loading ? (
<LoadingIndicator />
) : accounts.length === 0 ? (
<Rows spacing="2u">
<Title>Sign in required</Title>
<Text>
This example demonstrates how apps can allow users to authorize
with the app via a third-party platform.
</Text>
<Text>
To set up please see the README.md in the
/examples/fundamentals/multi_account_authentication folder
</Text>
<Text>
To use "Example App", you must sign in with your "Example"
account.
</Text>
<Button variant="primary" onClick={() => authorize()}>
Sign in to Example
</Button>
</Rows>
) : (
<Rows spacing="2u">
<Title>Auth0 Account Switcher</Title>
<Text>
Switch between your connected Auth0 accounts or manage your
account connections.
</Text>
<AccountSelector
currentView={currentView}
setCurrentView={setCurrentView}
accounts={accounts}
selectedAccountId={selectedAccountId}
triggerLabel="Switch Account"
appName="Auth0"
onAccountSwitch={handleAccountSwitch}
onAddAccount={handleAddAccount}
onSignInAgain={handleSignInAgain}
onManageAccounts={handleManageAccounts}
onBack={handleBack}
onDisconnect={handleDisconnect}
/>
{/* Show selected account info */}
{selectedAccountId && (
<Box
padding="2u"
border="standard"
borderRadius="standard"
background="neutral"
>
<Rows spacing="2u">
<Title size="small">Selected Account</Title>
{(() => {
const selectedAccount = accounts.find(
(acc) => acc.id === selectedAccountId,
);
return selectedAccount ? (
<Columns spacing="2u" alignY="center">
<Column width="content">
<Avatar
name={selectedAccount.displayName}
photo={selectedAccount.avatarUrl}
/>
</Column>
<Column>
<Rows spacing="1u">
<Text size="medium">
{selectedAccount.displayName}
</Text>
<Text size="small">
{selectedAccount.principal}
</Text>
</Rows>
</Column>
<Column width="content">
<Button
variant="primary"
onClick={() => fetchProfile(selectedAccount)}
disabled={loading}
>
{loading ? "Fetching..." : "Fetch Profile"}
</Button>
</Column>
</Columns>
) : null;
})()}
</Rows>
</Box>
)}
{/* Profile Display Section */}
{(profile || profileError || loading) && (
<Box
padding="3u"
border="standard"
borderRadius="standard"
background="neutral"
>
<Rows spacing="2u">
<Title size="small">Profile Information</Title>
{loading && (
<Box display="flex" justifyContent="center">
<LoadingIndicator />
</Box>
)}
{profileError && (
<Box padding="2u" borderRadius="standard" border="standard">
<Text>Error: {profileError}</Text>
</Box>
)}
{profile && (
<Box
padding="2u"
background="neutral"
borderRadius="standard"
>
<Text size="small">
<pre
style={{ whiteSpace: "pre-wrap", fontSize: "12px" }}
>
{JSON.stringify(profile, null, 2)}
</pre>
</Text>
</Box>
)}
</Rows>
</Box>
)}
</Rows>
)}
</Box>
</div>
);
return result;
}
TYPESCRIPT
// For usage information, see the README.md file.
import { AppUiProvider } from "@canva/app-ui-kit";
import { createRoot } from "react-dom/client";
import { App } from "./app";
import "@canva/app-ui-kit/styles.css";
import type { DesignEditorIntent } from "@canva/intents/design";
import { prepareDesignEditor } from "@canva/intents/design";
async function render() {
const root = createRoot(document.getElementById("root") as Element);
root.render(
<AppUiProvider>
<App />
</AppUiProvider>,
);
}
const designEditor: DesignEditorIntent = { render };
prepareDesignEditor(designEditor);
// Hot Module Replacement for development (automatically reloads the app when changes are made)
if (module.hot) {
module.hot.accept("./app", render);
}
TYPESCRIPT
# Multi-account authentication
Demonstrates how to implement multi-account OAuth authentication, allowing users to connect and switch between multiple accounts from the same OAuth provider. Shows account management, account switching UI, token management, and authenticated API requests using the selected account.
For API reference docs and instructions on running this example, see: https://www.canva.dev/docs/apps/authenticating-users/oauth-multi-account/.
Related examples: See fundamentals/authentication for single-account OAuth authentication, fundamentals/fetch for general API communication, or design_interaction/design_token for design-specific authentication patterns.
NOTE: This example differs from what is expected for public apps to pass a Canva review:
- Token storage and security is simplified for demonstration. Production apps must implement secure token storage and follow OAuth security best practices
- Error handling for authentication failures is simplified for demonstration. Production apps must implement comprehensive error handling with clear user feedback and graceful failure modes
- Token refresh mechanisms are not implemented. Production apps should implement proper token lifecycle management
- Internationalization is not implemented. Production apps must support multiple languages using the `@canva/app-i18n-kit` package to pass Canva review requirements
- The code structure is simplified: Production apps using [intents](https://www.canva.dev/docs/apps/intents/) are recommended to call the prepareDesignEditor function from src/intents/design_editor/index.tsx
MARKDOWN
# Setup
## Getting started
Before using this example, you'll need to [add multi-account OAuth configuration to your app](https://www.canva.dev/docs/apps/authenticating-users/oauth-multi-account/#add-multi-account-oauth-to-your-app) in the developer portal.
Once this is done, simply run the example from the root of `canva-apps-sdk-starter-kit` with:
```sh
npm start multi_account_authentication
```
MARKDOWN

API reference

Need help?