Skip to main content

Sign in from a CLI or a TV

Sign in on a device that has no browser: the device shows a code, and the person approves it on a phone.

RecipeReadyView source
Works with
JavaScript / TypeScriptPythonGoPlain HTTP
Standards
RFC 8628

What it shows​

  1. A command-line tool asks for a device code. It prints an address and a short user code.
  2. The person opens the address on a phone or a laptop, signs in, and selects Authorize.
  3. Meanwhile the tool asks the token endpoint for tokens every few seconds. It keeps waiting on authorization_pending, and asks less often after slow_down.
  4. The tool saves the tokens in a file that only the user can read, and reads the profile of the person.
  5. The tool exchanges the refresh token for a new access token, as it does when the old one expires.

The SDKs have no call for the device grant, so the first two requests are plain HTTP in each language. The profile and the refresh use the SDK.

Before you start​

  • An API key with the scopes admin:clients:read and admin:clients:write. Create it in the portal under Applications & developer tools, API keys. Only the setup script uses it: the tool itself holds no key and no secret.
  • A public application with the grant types Device flow and Offline access (the refresh token). The setup script creates it. In the portal, both are under Grant types on the Configuration tab of the application.
  • For the curl version: curl and jq.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYAn API key with the scopes admin:clients:read and admin:clients:write. Only the setup script uses it.
LUMOAUTH_CLIENT_IDThe client ID of the public application. The setup script prints it.
TOKEN_FILEOptional. Where the program saves the tokens. The default is device-tokens.json in the current folder.

The setup script creates what the recipe needs, through the Admin API. You can run it again at any time.

node sign-in/device-flow/setup.mjs
setup.mjs
// Creates the application that the command-line tool signs in with: a public
// application that may use the device grant and refresh tokens. Run it again
// at any time.
//
// node sign-in/device-flow/setup.mjs
//
// The API key needs the scopes admin:clients:read and admin:clients:write.
import { call, list, printEnv } from '../../_lib/admin.mjs';

const name = 'Acme CLI';
const grantTypes = ['urn:ietf:params:oauth:grant-type:device_code', 'refresh_token'];

let client = (await list('/admin/clients')).find((c) => c.name === name);
if (client) {
await call('PATCH', `/admin/clients/${client.id}`, { grantTypes });
} else {
// A tool on the person's computer cannot keep a secret, so the
// application is public. It needs no redirect URI.
client = (await call('POST', '/admin/clients', { name, isConfidential: false, grantTypes })).data;
}

console.log(`Application "${name}" is ready. Its grant types: ${grantTypes.join(', ')}.`);
printEnv({ LUMOAUTH_CLIENT_ID: client.clientId });

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. Each program waits until you approve the code in a browser. For the check, a browser opened the address, signed in and selected Authorize; in one run of the Node.js and Go programs it selected Deny.

sign-in/device-flow/js/device.mjs
// Sign in from a command-line tool with the device flow. The tool shows a
// code, the person approves it in a browser on any device, and the tool
// receives the tokens.
//
// node sign-in/device-flow/js/device.mjs
import { writeFileSync } from 'node:fs';
import { AuthModule } from '@lumoauth/client';

const api = `${process.env.LUMOAUTH_URL}/orgs/${process.env.LUMOAUTH_ORG_ID}/api/v1`;
const clientId = process.env.LUMOAUTH_CLIENT_ID;
const tokenFile = process.env.TOKEN_FILE ?? 'device-tokens.json';

// The SDK has no call for the device grant, so the first two requests are
// plain HTTP. Both endpoints take a form.
const post = async (path, fields) => {
const response = await fetch(api + path, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(fields),
});
return { ok: response.ok, body: await response.json() };
};

// 1. Ask for a device code and show the person where to approve it.
const device = await post('/oauth/device_authorization', { client_id: clientId, scope: 'openid profile email' });
if (!device.ok) throw new Error(`device_authorization: ${device.body.error}`);
const { device_code, user_code, verification_uri, verification_uri_complete, expires_in } = device.body;
console.log(`Open ${verification_uri} and enter the code ${user_code}`);
console.log(`Or open ${verification_uri_complete}`);

// 2. Ask the token endpoint until the person has decided. LumoAuth answers
// authorization_pending until then, and slow_down when the tool asks too often.
let interval = device.body.interval ?? 5;
console.log(`Waiting for approval. The code expires in ${expires_in} seconds.`);
let tokens;
while (!tokens) {
await new Promise((resolve) => setTimeout(resolve, interval * 1000));
const answer = await post('/oauth/token', {
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
device_code,
client_id: clientId,
});
if (answer.ok) {
tokens = answer.body;
} else if (answer.body.error === 'slow_down') {
interval += 5;
console.log(`slow_down: asking every ${interval} seconds now`);
} else if (answer.body.error !== 'authorization_pending') {
// access_denied: the person chose Deny. expired_token: nobody decided in time.
console.log(`Sign-in ended: ${answer.body.error}`);
process.exit(1);
}
}

// 3. Keep the tokens in a file that only this user can read.
writeFileSync(tokenFile, JSON.stringify(tokens), { mode: 0o600 });
console.log(`Approved. The access token expires in ${tokens.expires_in} seconds. Tokens saved in ${tokenFile}`);

// 4. The SDK reads the profile, and gets a new access token with the
// refresh token when the old one expires.
const auth = new AuthModule({ baseUrl: process.env.LUMOAUTH_URL, orgId: process.env.LUMOAUTH_ORG_ID, clientId });
const user = await auth.getUserInfo(tokens.access_token);
console.log(`Signed in as ${user.email}`);

const refreshed = await auth.refreshToken(tokens.refresh_token);
writeFileSync(tokenFile, JSON.stringify(refreshed), { mode: 0o600 });
console.log(`Refreshed. New access token for ${refreshed.expires_in} seconds, new refresh token: ${refreshed.refresh_token !== tokens.refresh_token ? 'yes' : 'no'}`);
node sign-in/device-flow/js/device.mjs

Check the result​

Run the program, open the address that it prints in a browser, sign in, and select Authorize on the page Authorize Device. The program goes on within a few seconds.

Output
Open https://app.lumoauth.dev/orgs/acme-corp/api/v1/oauth/device and enter the code WDJB-MJHT
Or open https://app.lumoauth.dev/orgs/acme-corp/api/v1/oauth/device?user_code=WDJB-MJHT
Waiting for approval. The code expires in 600 seconds.
Approved. The access token expires in 3600 seconds. Tokens saved in device-tokens.json
Signed in as maya.chen@example.com
Refreshed. New access token for 3600 seconds, new refresh token: yes
  • Select Deny instead: the program stops with Sign-in ended: access_denied.
  • Wait more than 10 minutes without a decision: the program stops with Sign-in ended: expired_token.
  • The address with user_code fills in the code for the person. Show it as a QR code on a TV.
  • The token file has the mode 600: only its owner can read it.

Limits​

  • The code expires after 600 seconds, and the tool must wait at least interval seconds between two requests. Both values are fixed by LumoAuth.
  • After each slow_down, LumoAuth expects 5 more seconds between requests. A tool that keeps the old interval gets slow_down again.
  • The token endpoint accepts only the full grant type urn:ietf:params:oauth:grant-type:device_code. The short form device_code is refused with unsupported_grant_type.
  • Each refresh returns a new refresh token. Save it every time: see Refresh token rotation.