You are shipping a command-line app, or an agent that runs in a terminal. You can use a CLI in Node.js (nodejs) with Authdog. The process prints a short code, the person approves it in a browser they already have, and the CLI receives an access token. The terminal does not listen on localhost.
That grant is device authorization (RFC 8628). It is the right path when a person is at the keyboard: a developer tool, a coding agent that can show a prompt, or any other Node.js CLI that should act as that user.
A job with nobody there to approve a code is a different credential. Use client credentials for that process. Do not paste a person's access token into an agent prompt.
Register a confidential client
In the console, open Authentication → Clients (?tab=clients) and click Create client.
- Token endpoint auth is HTTP Basic (
client_secret_basic). - Grant types are space-separated. Keep the defaults and add the device grant:
authorization_code refresh_token urn:ietf:params:oauth:grant-type:device_code- Scopes need
openid. Addprofileandemailwhen the CLI should read them. A requested scope missing from the client returnsinvalid_scope. - The form still requires a redirect URI. The device grant does not send the browser there. Use your app's HTTPS callback.
- Copy the client secret once. Put
AUTHDOG_CLIENT_IDandAUTHDOG_CLIENT_SECRETin the operator environment, not in the repo.
The secret names the application. It does not sign a person in. A user in that environment still has to approve the code. A binary you ship can be unpacked, so rotate the secret when you need to stop new device grants from that build.
The issuer for the environment is https://id.authdog.com/oidc/{environmentId}. If you mapped a vanity domain, read device_authorization_endpoint, token_endpoint, and userinfo_endpoint from /.well-known/openid-configuration and call those URLs. The samples below use the default issuer paths.
Sign in from Node.js
Node.js 20+ can call the two endpoints with fetch. No SDK and no loopback server.
const issuer = process.env.AUTHDOG_ISSUER // https://id.authdog.com/oidc/<environmentId>
const clientId = process.env.AUTHDOG_CLIENT_ID
const clientSecret = process.env.AUTHDOG_CLIENT_SECRET
if (!issuer || !clientId || !clientSecret) {
throw new Error("Set AUTHDOG_ISSUER, AUTHDOG_CLIENT_ID, and AUTHDOG_CLIENT_SECRET")
}
const basic = Buffer.from(`${clientId}:${clientSecret}`).toString("base64")
async function formPost(path: string, body: URLSearchParams) {
const response = await fetch(`${issuer}${path}`, {
method: "POST",
headers: {
Authorization: `Basic ${basic}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body,
})
const payload = (await response.json()) as {
device_code?: string
user_code?: string
verification_uri_complete?: string
interval?: number
expires_in?: number
access_token?: string
error?: string
}
return { ok: response.ok, payload }
}
const started = await formPost(
"/device",
new URLSearchParams({ scope: "openid profile email" }),
)
if (!started.ok || !started.payload.device_code) {
throw new Error(started.payload.error ?? "device authorization failed")
}
const deviceCode = started.payload.device_code
console.log(`Open ${started.payload.verification_uri_complete}`)
console.log(`Code: ${started.payload.user_code}`)
// device_code is the poll secret. Do not print it.
let waitMs = (started.payload.interval ?? 5) * 1000
const deadline = Date.now() + (started.payload.expires_in ?? 600) * 1000
let accessToken = ""
while (Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, waitMs))
const polled = await formPost(
"/token",
new URLSearchParams({
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
device_code: deviceCode,
}),
)
if (polled.ok && polled.payload.access_token) {
accessToken = polled.payload.access_token
break
}
if (polled.payload.error === "authorization_pending") continue
if (polled.payload.error === "slow_down") {
waitMs += 5000
continue
}
throw new Error(polled.payload.error ?? "device grant failed")
}
if (!accessToken) throw new Error("expired_token")HTTP 400 is normal while you wait. Keep polling on authorization_pending. On slow_down, wait five extra seconds, then continue. Stop on access_denied, expired_token, or invalid_grant.
The user code is eight characters, shown as ABCD-EFGH. The device code lives for 10 minutes. The poll interval starts at 5 seconds.
A successful poll returns access_token, token_type (Bearer), expires_in, scope, and an id_token because the scope includes openid. This sample does not request offline_access, so there is no refresh token. When the access token expires, run the device flow again.
Operators can drive the same two calls with the Authdog CLI:
ISSUER="https://id.authdog.com/oidc/$ENVIRONMENT_ID" \
CLIENT_ID="..." CLIENT_SECRET="..." \
authdog device authorize --pollYour product CLI should call the HTTP endpoints itself, as in the Node.js sample. It does not need the Authdog CLI, and it does not need a loopback listener.
Read the profile
Send the access token to the environment userinfo endpoint. Userinfo checks the signature, expiry, and revocation, and returns the current profile. The same bearer is what your API should accept. See Backend requests.
const me = await fetch(`${issuer}/userinfo`, {
headers: { Authorization: `Bearer ${accessToken}` },
})
if (!me.ok) throw new Error(`userinfo ${me.status}`)
const profile = await me.json()
console.log(profile.sub ?? profile.id)Store the access token in the OS credential store, or in a file the user owns with mode 0600. Do not write it to shell history, a prompt, or the repo.
import { chmod, writeFile } from "node:fs/promises"
const file = new URL("./.authdog-token", import.meta.url)
await writeFile(file, `${accessToken}\n`, { mode: 0o600 })
await chmod(file, 0o600)@authdog/node-sdk can call getUserInfo(accessToken) after this step. That package is a management and userinfo client. It does not run the device grant. See Node.js SDK.
When nobody is at the keyboard
An unattended agent, a CI job, or a coding agent that cannot show an approval prompt should not start a device grant. Register an agent and exchange client credentials. Ask for the scope that agent is allowed to use. Repeat the exchange before expires_in. There is no refresh token.
formPost is the helper from the device sample. Point it at a separate confidential client that allows client_credentials. The device client above is for a person.
const machine = await formPost(
"/token",
new URLSearchParams({
grant_type: "client_credentials",
scope: "mcp:invoke",
}),
)
if (!machine.ok || !machine.payload.access_token) {
throw new Error(machine.payload.error ?? "client credentials failed")
}The full registration steps, including the resource parameter that gives the token an audience, are in the Agents quickstart.
A resolved user, or a machine token, is not a permission grant. Enforce authorization on the server after the session check.
Check it
- Run the Node.js sample. Approve the code in a browser that is not the terminal. Userinfo returns that user's id.
- Deny a second code. The poll stops with
access_denied. - Let a code sit for 10 minutes. The poll stops with
expired_token. - Call your API with
Authorization: Bearerand the access token. The same check that accepts a browser session accepts this token.
Next
| Read | To learn how to |
|---|---|
| Sign up and sign in | Enable methods and see the device endpoints |
| Agents quickstart | Mint a token when no person can approve a code |
| Node.js SDK | Call userinfo and the management API from Node.js |
| Backend requests | Validate the bearer on your API |
| Machine authentication | Pick a credential for a job that is not a user |
| Sessions and tokens | See how the access token is issued and revoked |