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.
What it shows
- A command-line tool asks for a device code. It prints an address and a short user code.
- The person opens the address on a phone or a laptop, signs in, and selects Authorize.
- Meanwhile the tool asks the token endpoint for tokens every few seconds. It keeps waiting on
authorization_pending, and asks less often afterslow_down. - The tool saves the tokens in a file that only the user can read, and reads the profile of the person.
- 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:readandadmin: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:
curlandjq.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | An API key with the scopes admin:clients:read and admin:clients:write. Only the setup script uses it. |
LUMOAUTH_CLIENT_ID | The client ID of the public application. The setup script prints it. |
TOKEN_FILE | Optional. 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.
- Node.js
- Python
- Go
- curl
// 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
"""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.
python sign-in/device-flow/python/device.py
"""
import json
import os
import sys
import time
import requests
from lumoauth import LumoAuth
api = f"{os.environ['LUMOAUTH_URL']}/orgs/{os.environ['LUMOAUTH_ORG_ID']}/api/v1"
client_id = os.environ["LUMOAUTH_CLIENT_ID"]
token_file = os.environ.get("TOKEN_FILE", "device-tokens.json")
# 1. Ask for a device code and show the person where to approve it. The SDK
# has no call for the device grant, so the first two requests are plain HTTP.
answer = requests.post(f"{api}/oauth/device_authorization", data={"client_id": client_id, "scope": "openid profile email"})
device = answer.json()
if not answer.ok:
sys.exit(f"device_authorization: {device['error']}")
print(f"Open {device['verification_uri']} and enter the code {device['user_code']}")
print(f"Or open {device['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.
interval = device.get("interval", 5)
print(f"Waiting for approval. The code expires in {device['expires_in']} seconds.")
tokens = None
while tokens is None:
time.sleep(interval)
answer = requests.post(f"{api}/oauth/token", data={
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
"device_code": device["device_code"],
"client_id": client_id,
})
body = answer.json()
if answer.ok:
tokens = body
elif body["error"] == "slow_down":
interval += 5
print(f"slow_down: asking every {interval} seconds now")
elif body["error"] != "authorization_pending":
# access_denied: the person chose Deny. expired_token: nobody decided in time.
print(f"Sign-in ended: {body['error']}")
sys.exit(1)
def save(values):
"""Keeps the tokens in a file that only this user can read."""
with open(os.open(token_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as file:
json.dump(values, file)
# 3. Keep the tokens.
save(tokens)
print(f"Approved. The access token expires in {tokens['expires_in']} seconds. Tokens saved in {token_file}")
# 4. The SDK reads the profile, and gets a new access token with the
# refresh token when the old one expires. It needs no API key for this.
lumo = LumoAuth()
user = lumo.auth.userinfo(tokens["access_token"])
print(f"Signed in as {user['email']}")
refreshed = lumo.auth.refresh_token(tokens["refresh_token"], client_id=client_id)
save(refreshed)
changed = "yes" if refreshed["refresh_token"] != tokens["refresh_token"] else "no"
print(f"Refreshed. New access token for {refreshed['expires_in']} seconds, new refresh token: {changed}")
python sign-in/device-flow/python/device.py
// 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.
//
// go run ./sign-in/device-flow/go
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
var api = os.Getenv("LUMOAUTH_URL") + "/orgs/" + os.Getenv("LUMOAUTH_ORG_ID") + "/api/v1"
// post sends a form and decodes the JSON answer. The SDK has no call for the
// device grant, so the first two requests are plain HTTP.
func post(path string, form url.Values, out any) (bool, error) {
resp, err := http.PostForm(api+path, form)
if err != nil {
return false, err
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK, json.NewDecoder(resp.Body).Decode(out)
}
// save keeps the tokens in a file that only this user can read.
func save(file string, tokens *lumoauth.TokenResponse) {
data, _ := json.Marshal(tokens)
if err := os.WriteFile(file, data, 0o600); err != nil {
log.Fatal(err)
}
}
func main() {
clientID := os.Getenv("LUMOAUTH_CLIENT_ID")
tokenFile := os.Getenv("TOKEN_FILE")
if tokenFile == "" {
tokenFile = "device-tokens.json"
}
// 1. Ask for a device code and show the person where to approve it.
var device struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
Error string `json:"error"`
}
ok, err := post("/oauth/device_authorization", url.Values{"client_id": {clientID}, "scope": {"openid profile email"}}, &device)
if err != nil || !ok {
log.Fatalf("device_authorization: %v %s", err, device.Error)
}
fmt.Printf("Open %s and enter the code %s\n", device.VerificationURI, device.UserCode)
fmt.Printf("Or open %s\n", device.VerificationURIComplete)
// 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.
interval := device.Interval
if interval == 0 {
interval = 5
}
fmt.Printf("Waiting for approval. The code expires in %d seconds.\n", device.ExpiresIn)
var tokens struct {
lumoauth.TokenResponse
Error string `json:"error"`
}
for {
time.Sleep(time.Duration(interval) * time.Second)
ok, err := post("/oauth/token", url.Values{
"grant_type": {"urn:ietf:params:oauth:grant-type:device_code"},
"device_code": {device.DeviceCode},
"client_id": {clientID},
}, &tokens)
if err != nil {
log.Fatal(err)
}
if ok {
break
}
if tokens.Error == "slow_down" {
interval += 5
fmt.Printf("slow_down: asking every %d seconds now\n", interval)
} else if tokens.Error != "authorization_pending" {
// access_denied: the person chose Deny. expired_token: nobody decided in time.
fmt.Printf("Sign-in ended: %s\n", tokens.Error)
os.Exit(1)
}
}
// 3. Keep the tokens.
save(tokenFile, &tokens.TokenResponse)
fmt.Printf("Approved. The access token expires in %d seconds. Tokens saved in %s\n", tokens.ExpiresIn, tokenFile)
// 4. The SDK reads the profile with the new access token, and gets a new
// access token with the refresh token when the old one expires.
client, err := lumoauth.New(lumoauth.WithAccessToken(tokens.AccessToken))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
user, err := client.Auth.UserInfo(ctx, "")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Signed in as %s\n", user.Email)
refreshed, err := client.Auth.RefreshToken(ctx, lumoauth.RefreshTokenParams{RefreshToken: tokens.RefreshToken, ClientID: clientID})
if err != nil {
log.Fatal(err)
}
save(tokenFile, refreshed)
changed := "no"
if refreshed.RefreshToken != tokens.RefreshToken {
changed = "yes"
}
fmt.Printf("Refreshed. New access token for %d seconds, new refresh token: %s\n", refreshed.ExpiresIn, changed)
}
go run ./sign-in/device-flow/go
#!/bin/sh
# Sign in from a command-line tool with the device flow, with curl and jq.
# The tool shows a code, the person approves it in a browser on any device,
# and the tool receives the tokens.
#
# sh sign-in/device-flow/http/device.sh
set -eu
API="$LUMOAUTH_URL/orgs/$LUMOAUTH_ORG_ID/api/v1"
TOKEN_FILE="${TOKEN_FILE:-device-tokens.json}"
# Keeps the tokens in a file that only this user can read.
save() { (umask 077 && printf '%s' "$1" > "$TOKEN_FILE"); }
# 1. Ask for a device code and show the person where to approve it.
DEVICE="$(curl --silent --show-error "$API/oauth/device_authorization" \
--data-urlencode "client_id=$LUMOAUTH_CLIENT_ID" \
--data-urlencode "scope=openid profile email")"
DEVICE_CODE="$(printf '%s' "$DEVICE" | jq -r '.device_code // empty')"
if [ -z "$DEVICE_CODE" ]; then
echo "device_authorization: $(printf '%s' "$DEVICE" | jq -r .error)"
exit 1
fi
echo "Open $(printf '%s' "$DEVICE" | jq -r .verification_uri) and enter the code $(printf '%s' "$DEVICE" | jq -r .user_code)"
echo "Or open $(printf '%s' "$DEVICE" | jq -r .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.
INTERVAL="$(printf '%s' "$DEVICE" | jq -r '.interval // 5')"
echo "Waiting for approval. The code expires in $(printf '%s' "$DEVICE" | jq -r .expires_in) seconds."
while :; do
sleep "$INTERVAL"
TOKENS="$(curl --silent --show-error "$API/oauth/token" \
--data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:device_code" \
--data-urlencode "device_code=$DEVICE_CODE" \
--data-urlencode "client_id=$LUMOAUTH_CLIENT_ID")"
ERROR="$(printf '%s' "$TOKENS" | jq -r '.error // empty')"
case "$ERROR" in
"") break ;;
authorization_pending) ;;
slow_down)
INTERVAL=$((INTERVAL + 5))
echo "slow_down: asking every $INTERVAL seconds now" ;;
*)
# access_denied: the person chose Deny. expired_token: nobody decided in time.
echo "Sign-in ended: $ERROR"
exit 1 ;;
esac
done
# 3. Keep the tokens.
save "$TOKENS"
echo "Approved. The access token expires in $(printf '%s' "$TOKENS" | jq -r .expires_in) seconds. Tokens saved in $TOKEN_FILE"
# 4. Read the profile with the access token, and get a new access token with
# the refresh token when the old one expires.
EMAIL="$(curl --silent --show-error "$API/oauth/userinfo" \
--header "Authorization: Bearer $(printf '%s' "$TOKENS" | jq -r .access_token)" | jq -r .email)"
echo "Signed in as $EMAIL"
REFRESH_TOKEN="$(printf '%s' "$TOKENS" | jq -r .refresh_token)"
REFRESHED="$(curl --silent --show-error --fail-with-body "$API/oauth/token" \
--data-urlencode "grant_type=refresh_token" \
--data-urlencode "refresh_token=$REFRESH_TOKEN" \
--data-urlencode "client_id=$LUMOAUTH_CLIENT_ID")"
save "$REFRESHED"
CHANGED=no
[ "$(printf '%s' "$REFRESHED" | jq -r .refresh_token)" != "$REFRESH_TOKEN" ] && CHANGED=yes
echo "Refreshed. New access token for $(printf '%s' "$REFRESHED" | jq -r .expires_in) seconds, new refresh token: $CHANGED"
sh sign-in/device-flow/http/device.sh
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.
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_codefills 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
intervalseconds 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 getsslow_downagain. - The token endpoint accepts only the full grant type
urn:ietf:params:oauth:grant-type:device_code. The short formdevice_codeis refused withunsupported_grant_type. - Each refresh returns a new refresh token. Save it every time: see Refresh token rotation.