Guide · IAM Identity Center · OIDC Device Authorization
IAM Identity Center OIDC Device Authorization for MCP Servers — Programmatic Short-Lived Credentials
The IAM Identity Center OIDC device authorization flow lets headless tools — CLI utilities, MCP server local launchers, and developer automation scripts — get short-lived AWS credentials without storing long-lived access keys. The user authenticates once in a browser, the tool polls for approval, then exchanges the resulting access token for temporary STS credentials in any AWS account they're assigned to. This guide covers the full flow end-to-end using @aws-sdk/client-sso-oidc and @aws-sdk/client-sso.
TL;DR
Register a public OIDC client once with RegisterClientCommand (cache the clientId and clientSecret — they're valid ~90 days). Start a device flow with StartDeviceAuthorizationCommand, show the user a code and URL, then poll CreateTokenCommand every interval seconds until you get an accessToken. Exchange the token for STS credentials with GetRoleCredentialsCommand from @aws-sdk/client-sso.
When to use the device authorization flow
The SSO OIDC device authorization flow is designed for two scenarios:
- CLI tools and developer utilities that run on a developer's machine but cannot open a browser directly (e.g., a terminal running over SSH, a VS Code task, or an MCP server that needs credentials at startup). The user is prompted to visit a URL and enter a code in their browser — the tool polls asynchronously until they do.
- Local MCP server launchers where the developer starts the server in a terminal and wants it to assume a production role for 8 hours without storing a static access key anywhere on disk.
For unattended server processes (ECS tasks, Lambda functions, EC2 instances), use IAM roles and instance/task profiles instead — no human is present to authorize the browser step. The device flow requires human interaction in the authorization loop.
SDK installation
npm install @aws-sdk/client-sso-oidc @aws-sdk/client-sso
Both clients are regional and must target the IAM Identity Center home region (the region where you enabled IdC):
import { SSOOIDCClient } from "@aws-sdk/client-sso-oidc";
import { SSOClient } from "@aws-sdk/client-sso";
const REGION = "us-east-1"; // IdC home region
const START_URL = "https://d-1234567890.awsapps.com/start";
const oidc = new SSOOIDCClient({ region: REGION });
const sso = new SSOClient({ region: REGION });
Step 1 — Register the OIDC client
RegisterClientCommand creates a public OAuth 2.0 client registration. The returned clientId and clientSecret are valid for ~90 days. Cache them so you don't register a new client on every run — excessive registrations are throttled and generate noise in audit logs.
import {
RegisterClientCommand,
StartDeviceAuthorizationCommand,
CreateTokenCommand,
} from "@aws-sdk/client-sso-oidc";
import fs from "fs";
import path from "path";
const CLIENT_CACHE_PATH = path.join(process.env.HOME!, ".aws", "sso", "cache", "oidc-client.json");
async function getOrRegisterClient() {
// Load cached client registration if still valid (> 7 days before expiry)
if (fs.existsSync(CLIENT_CACHE_PATH)) {
const cached = JSON.parse(fs.readFileSync(CLIENT_CACHE_PATH, "utf8"));
const expiresAt = cached.clientSecretExpiresAt * 1000; // convert to ms
if (expiresAt - Date.now() > 7 * 24 * 60 * 60 * 1000) {
return { clientId: cached.clientId, clientSecret: cached.clientSecret };
}
}
const reg = await oidc.send(new RegisterClientCommand({
clientName: "my-mcp-tool",
clientType: "public",
scopes: ["sso:account:access"],
}));
const record = {
clientId: reg.clientId,
clientSecret: reg.clientSecret,
clientSecretExpiresAt: reg.clientSecretExpiresAt, // Unix timestamp in seconds
};
fs.mkdirSync(path.dirname(CLIENT_CACHE_PATH), { recursive: true });
fs.writeFileSync(CLIENT_CACHE_PATH, JSON.stringify(record, null, 2), { mode: 0o600 });
return { clientId: reg.clientId!, clientSecret: reg.clientSecret! };
}
The scopes array must contain "sso:account:access". This is the only scope supported for the device authorization grant in IAM Identity Center — it grants the token permission to list accounts and get role credentials.
Step 2 — Start the device authorization
async function startDeviceFlow(clientId: string, clientSecret: string) {
const auth = await oidc.send(new StartDeviceAuthorizationCommand({
clientId,
clientSecret,
startUrl: START_URL,
}));
console.log("─────────────────────────────────────────────");
console.log("Sign in to AWS IAM Identity Center:");
console.log(` URL: ${auth.verificationUri}`);
console.log(` Code: ${auth.userCode}`);
console.log("─────────────────────────────────────────────");
// verificationUriComplete = URL with the code pre-filled, safe to open directly
// e.g., https://d-1234567890.awsapps.com/start/device?user_code=BCDF-WXYZ
return {
deviceCode: auth.deviceCode!,
expiresIn: auth.expiresIn!, // seconds until deviceCode expires (typically 600)
interval: Math.max(auth.interval ?? 5, 5), // polling interval in seconds (minimum 5)
};
}
The userCode is a human-readable code (format XXXX-YYYY) that the user enters at the portal. The verificationUriComplete includes the code as a query parameter — if your tool can open a browser, use this URL to skip manual code entry. If running over SSH or in a terminal where browser opening is unavailable, print both the URL and the code for the user to enter manually.
Step 3 — Poll for the access token
async function pollForToken(
clientId: string,
clientSecret: string,
deviceCode: string,
intervalSeconds: number,
expiresIn: number,
): Promise<{ accessToken: string; refreshToken?: string }> {
const deadline = Date.now() + expiresIn * 1000;
let currentInterval = intervalSeconds;
while (Date.now() < deadline) {
await new Promise(r => setTimeout(r, currentInterval * 1000));
try {
const token = await oidc.send(new CreateTokenCommand({
clientId,
clientSecret,
grantType: "urn:ietf:params:oauth:grant-type:device_code",
deviceCode,
}));
console.log("Authenticated successfully");
return {
accessToken: token.accessToken!,
refreshToken: token.refreshToken ?? undefined, // present only if refresh tokens are enabled
};
} catch (err: any) {
const code = err?.name ?? err?.__type ?? "";
if (code === "AuthorizationPendingException") {
// User has not yet approved — keep polling
continue;
}
if (code === "SlowDownException") {
// Server asks us to back off — increase interval by 5s
currentInterval += 5;
continue;
}
if (code === "ExpiredTokenException") {
throw new Error("Device code expired. Please run again to get a new code.");
}
if (code === "AccessDeniedException") {
throw new Error("Access denied — the user rejected the authorization request.");
}
throw err; // unexpected error
}
}
throw new Error("Timed out waiting for user authorization.");
}
The four exception names to handle:
| Exception | Meaning | Action |
|---|---|---|
AuthorizationPendingException |
User hasn't approved yet | Wait interval seconds, retry |
SlowDownException |
Polling too fast | Increase interval by 5 seconds, retry |
ExpiredTokenException |
Device code expired (10 min) | Restart from StartDeviceAuthorization |
AccessDeniedException |
User denied | Abort — do not retry |
Step 4 — Exchange the access token for STS credentials
The accessToken from CreateTokenCommand is an IdC bearer token, not STS credentials. Use GetRoleCredentialsCommand from @aws-sdk/client-sso to get the actual AWS access key, secret, and session token:
import { SSOClient, GetRoleCredentialsCommand, ListAccountsCommand } from "@aws-sdk/client-sso";
async function getCredentials(accessToken: string, accountId: string, roleName: string) {
const creds = await sso.send(new GetRoleCredentialsCommand({
accessToken,
accountId,
roleName, // the permission set name (e.g., "MCPServerDeveloper")
}));
const rc = creds.roleCredentials!;
return {
accessKeyId: rc.accessKeyId!,
secretAccessKey: rc.secretAccessKey!,
sessionToken: rc.sessionToken!,
expiration: rc.expiration ? new Date(rc.expiration) : undefined,
};
}
// Use in an MCP server startup sequence
const { clientId, clientSecret } = await getOrRegisterClient();
const { deviceCode, expiresIn, interval } = await startDeviceFlow(clientId, clientSecret);
const { accessToken } = await pollForToken(clientId, clientSecret, deviceCode, interval, expiresIn);
const awsCreds = await getCredentials(accessToken, "123456789012", "MCPServerDeveloper");
// Now use these credentials with any AWS SDK client
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
const dynamo = new DynamoDBClient({
region: "us-east-1",
credentials: awsCreds,
});
Token caching and refresh
The access token returned by CreateTokenCommand is valid for 8 hours by default (configurable in the IdC console under Settings → Authentication → Session settings). Cache it to avoid running the device flow on every tool invocation:
const TOKEN_CACHE_PATH = path.join(process.env.HOME!, ".aws", "sso", "cache", "token.json");
function saveToken(token: { accessToken: string; refreshToken?: string; expiresIn: number }) {
const record = {
accessToken: token.accessToken,
refreshToken: token.refreshToken,
expiresAt: Date.now() + token.expiresIn * 1000,
};
fs.writeFileSync(TOKEN_CACHE_PATH, JSON.stringify(record), { mode: 0o600 });
}
function loadCachedToken(): string | null {
if (!fs.existsSync(TOKEN_CACHE_PATH)) return null;
const cached = JSON.parse(fs.readFileSync(TOKEN_CACHE_PATH, "utf8"));
// Check expiry with 5-minute buffer
if (cached.expiresAt - Date.now() > 5 * 60 * 1000) return cached.accessToken;
return null;
}
When the IdC instance has refresh tokens enabled (console: Settings → Authentication → Refresh token rotation), CreateTokenCommand also returns a refreshToken valid for 90 days. Use it to get a new access token without user interaction:
import { CreateTokenCommand } from "@aws-sdk/client-sso-oidc";
async function refreshAccessToken(
clientId: string,
clientSecret: string,
refreshToken: string,
): Promise<{ accessToken: string; refreshToken?: string }> {
const token = await oidc.send(new CreateTokenCommand({
clientId,
clientSecret,
grantType: "refresh_token",
refreshToken,
}));
return {
accessToken: token.accessToken!,
refreshToken: token.refreshToken ?? undefined, // rotated token (save this, old one invalidated)
};
}
When refresh token rotation is enabled, using a refresh token invalidates it and returns a new one. Always save the new refresh token; discarding it means the user must re-authorize. If CreateTokenCommand with grantType: "refresh_token" throws UnauthorizedClientException or InvalidGrantException, the refresh token has expired — fall back to the device authorization flow.
Security considerations for token storage
IdC tokens are bearer tokens — anyone who can read them can use them to call AWS APIs. Apply the same protections you would to STS session tokens:
- Store cache files at
~/.aws/sso/cache/with mode0o600(readable only by the current user). The examples above use this. - Never write tokens to environment variables that persist across processes (e.g., do not export
AWS_SESSION_TOKENfrom a shell script run by a CI service). - For CI/CD pipelines (GitHub Actions, Jenkins, CodeBuild), use IAM roles for the CI runner itself rather than the device authorization flow — the device flow requires human interaction that CI cannot provide.
- For shared developer environments (devcontainers, remote EC2 dev boxes), store the token cache in the user's home directory, not in a shared volume.
- If you need to store client registration secrets (
clientId/clientSecret) for a tool distributed to many developers, store them in AWS Secrets Manager or a secrets provider, not hardcoded in the tool binary.
Combining the full flow in a reusable helper
export async function getIdCCredentials(
accountId: string,
roleName: string,
): Promise<{ accessKeyId: string; secretAccessKey: string; sessionToken: string; expiration?: Date }> {
// 1. Try cached access token first
const cached = loadCachedToken();
if (cached) {
return getCredentials(cached, accountId, roleName);
}
// 2. Try refresh token if available
const tokenRecord = fs.existsSync(TOKEN_CACHE_PATH)
? JSON.parse(fs.readFileSync(TOKEN_CACHE_PATH, "utf8"))
: null;
if (tokenRecord?.refreshToken) {
try {
const { clientId, clientSecret } = await getOrRegisterClient();
const refreshed = await refreshAccessToken(clientId, clientSecret, tokenRecord.refreshToken);
saveToken({ ...refreshed, expiresIn: 28800 }); // assume 8h if not provided
return getCredentials(refreshed.accessToken, accountId, roleName);
} catch {
// Refresh failed — fall through to device flow
}
}
// 3. Device authorization flow
const { clientId, clientSecret } = await getOrRegisterClient();
const { deviceCode, expiresIn, interval } = await startDeviceFlow(clientId, clientSecret);
const tokens = await pollForToken(clientId, clientSecret, deviceCode, interval, expiresIn);
saveToken({ ...tokens, expiresIn: 28800 });
return getCredentials(tokens.accessToken, accountId, roleName);
}
This helper gives MCP server tooling a clean interface: call getIdCCredentials("123456789012", "MCPServerDeveloper") at startup, use the credentials for the session, and trust that the helper handles token refresh and device re-authorization transparently. See the account assignments guide for how to list available accounts and roles from an access token, and the OAuth 2.0 fundamentals guide for background on the device authorization grant type (RFC 8628).