Still using IdentityServer4?

Get a free 30-minute upgrade assessment

OAuth 2.0 Device Flow for Headless and IoT Devices in .NET

Maarten Balliauw Head of Customer Success

When you need a user to sign in on a device that has no browser, or even no keyboard, you use the OAuth 2.0 Device Flow in Duende IdentityServer. The specification calls it the Device Authorization Grant (RFC 8628).

Common use cases include edge gateways with simple displays, handheld scanners, kiosks, CLI tools over SSH, or smart TVs. Rather than requiring direct credential entry on restricted inputs, the device displays a short verification code. The user completes authentication and approves the request on a secondary device, while the target device polls Duende IdentityServer in the background to retrieve tokens.

YouTube TV sign-in screen showing a device activation code
Image from YouTube TV Help - https://support.google.com/youtubetv/answer/16519270

In this post, we'll configure a device flow client in Duende IdentityServer and write the C# polling loop using Duende.IdentityModel. We'll also cover refresh tokens on unreliable connections and removing a device's access when it leaves service.

If you are building a game or console client, also check out Authenticating Players in Godot 4 with OAuth 2.0 and OpenID Connect.

How Does the OAuth 2.0 Device Authorization Grant (RFC 8628) Work?

The device flow uses two codes: the user_code the user enters in their browser on the secondary device, and the device_code that stays with the IoT client and is sent when polling for tokens. Authentication happens on the IdentityServer login page, so your existing MFA or passkey setup still applies.

  1. The device POSTs to the device authorization endpoint, /connect/deviceauthorization.
  2. IdentityServer answers with a device_code, a user_code, a verification_uri, an expires_in, and an interval.
  3. The device displays the user_code and the verification URI, and keeps the device_code to itself.
  4. The user opens the URI on a phone, signs in, and enters the user_code, which ties their approval to this specific request.
  5. Meanwhile, the device polls /connect/token with grant_type=urn:ietf:params:oauth:grant-type:device_code and its device_code until it gets tokens or a terminal error.

The diagram below shows the exchange with a sample user code (481 273 905) and the default five-second polling interval:

sequenceDiagram
    participant Phone as User's Phone
    participant Device as Headless Device
    participant IdS as Duende IdentityServer

    Device->>IdS: POST /connect/deviceauthorization (client_id, scope)
    IdS-->>Device: device_code, user_code: 481 273 905, verification_uri, expires_in: 600, interval: 5
    Note over Device: Displays 481 273 905 and verification_uri (or a QR code)
    Device->>IdS: POST /connect/token (device_code)
    IdS-->>Device: 400 authorization_pending
    Phone->>IdS: Open verification_uri, sign in, enter 481 273 905, approve scopes
    Device->>IdS: POST /connect/token (device_code)
    IdS-->>Device: 200 OK (access_token, refresh_token)

How to Configure an OAuth Device Flow Client in Duende IdentityServer

To configure an OAuth 2.0 Device Flow client in Duende IdentityServer, set AllowedGrantTypes = GrantTypes.DeviceFlow on the Client registration. If the client platform can launch a browser and listen on http://127.0.0.1 (such as desktop apps, mobile devices, or local developer CLIs), use an interactive flow instead. Device flow is specifically intended for environments that cannot handle browser redirects.

Client authentication requirements depend on hardware capabilities. Public devices running uniform firmware without per-device key storage (e.g., smart TVs or handheld scanners) cannot maintain a secret. Register these clients with RequireClientSecret = false, and restrict scope and token lifetimes accordingly:

Csharp

new Client
{
    ClientId = "warehouse-handheld",
    ClientName = "Warehouse Handheld",
    RequireClientSecret = false,
    AllowedGrantTypes = GrantTypes.DeviceFlow,
    AllowedScopes = { "warehouse.tasks" },
    AccessTokenLifetime = 600
};

In this example, if a handheld device goes missing, an active access token has only the warehouse.tasks scope and expires within ten minutes.

For hardware equipped with TPMs or secure elements (e.g., edge gateways), retain RequireClientSecret = true. Both /connect/deviceauthorization and /connect/token support client authentication, allowing IdentityServer to validate both the client hardware identity and the approving user.

With RequireClientSecret = true, client authentication can use asymmetric key pairs (JWT bearer tokens) rather than shared secrets. The client signs a JWT with its private key, which IdentityServer validates against the registered public key.

To register the public key, call builder.Services.AddIdentityServer().AddJwtBearerClientAuthentication() and configure the gateway's public JWK in ClientSecrets with IdentityServerConstants.SecretTypes.JsonWebKey (private_key_jwt).

Store refresh tokens and private keys in hardware-backed storage (such as a TPM, secure element, or OS keystore) rather than plain files on disk, and never embed shared secrets in a firmware image.

Can a Device Get a Refresh Token With Device Flow?

A device can get a refresh token with device flow by setting AllowOfflineAccess = true on the Client in IdentityServer and requesting the offline_access scope from the device. Both must be in place before IdentityServer will return a refresh token alongside the access token.

Here is an example registration, which also needs refresh tokens because the gateway may go months between human visits:

Csharp

// Device flow client registration
new Client
{
    ClientId = "edge-gw-042",
    ClientName = "Edge Gateway #042 (Packaging Line)",
    AllowedGrantTypes = GrantTypes.DeviceFlow,

    // IoT gateway holds its private key in a TPM / secure element. IdentityServer
    // stores only the public JWK and validates a private_key_jwt assertion at
    // /connect/deviceauthorization and /connect/token (requires AddJwtBearerClientAuthentication()).
    ClientSecrets =
    {
        new Secret(edgeGatewayPublicJwkJson)
        {
            Type = IdentityServerConstants.SecretTypes.JsonWebKey
        }
    },

    AllowedScopes = { "telemetry.push", "config.pull", "firmware.check", "offline_access" },
    AllowOfflineAccess = true, // required for refresh tokens

    // Long-lived refresh tokens: device may not re-authorize for months.
    // To cut off a device, disable the client (Enabled = false) and remove its
    // refresh tokens from the operational store (the revocation endpoint
    // revokes one token per call, presented by the client), plus revoking the
    // device's enrollment record at renewal. Don't rely on short refresh-token
    // TTLs alone.
    AbsoluteRefreshTokenLifetime = 7776000, // 90 days
    SlidingRefreshTokenLifetime = 2592000,   // 30 days
    RefreshTokenExpiration = TokenExpiration.Sliding, // makes sliding lifetime take effect
    RefreshTokenUsage = TokenUsage.ReUse,

    DeviceCodeLifetime = 600,

    Properties =
    {
        { "device_serial", "EGW-2026-042" },
        { "firmware_version", "3.1.4" },
        { "install_location", "Packaging, Bay 7" }
    }
}

This configuration grants a 30-day sliding window up to a 90-day absolute maximum. Adjust lifetime parameters based on security policy and re-authentication requirements. See Security Is a Spectrum: How to Choose Session Lifetimes in Duende IdentityServer for session guidance.

Notice RefreshTokenExpiration = TokenExpiration.Sliding in the snippet: without that setting, SlidingRefreshTokenLifetime is ignored, and the token uses absolute expiration. The Properties dictionary also lets you store device metadata, such as a serial number, firmware version, or bay location, so that you can trace a client registration back to a physical unit.

For RefreshTokenUsage, TokenUsage.ReUse is usually the safer choice for devices on unreliable networks. With OneTimeOnly, IdentityServer consumes the old refresh token as soon as it issues a new one; if the network drops before the device receives that response, the old token is already spent, and the device is locked out until someone re-authorizes it in person. Use OneTimeOnly when replay detection matters more than surviving dropped responses on a stable link. Because the default for RefreshTokenUsage differs between the core model and the Entity Framework store, set it explicitly.

Keep in mind that refreshing a token always requires a round trip to IdentityServer. While a device is offline, it can only operate for the remaining lifetime of the access token it already holds, so size your access token lifetime and offline fallback behavior accordingly.

How to Poll the /connect/token Endpoint in C#

When polling the /connect/token endpoint during OAuth 2.0 Device Flow, your C# client must respect the server's polling interval and stop on terminal errors or expiration. RFC 8628 defines five rules for the polling loop:

  • Wait interval seconds between polls. If the response has none, the default is 5 seconds.
  • On authorization_pending, keep waiting. The user has not finished yet.
  • On slow_down, add 5 seconds to the interval, and keep that longer interval for every later poll.
  • On access_denied or expired_token, stop. The only way forward is to start a new flow.
  • Stop when expires_in has passed, even if the server has not said so yet.

Your loop also needs to handle transient network failures by backing off and giving up after a few retries rather than polling forever. Here is a complete helper using Duende.IdentityModel's RequestDeviceAuthorizationAsync and RequestDeviceTokenAsync extensions:

Csharp

public static class DeviceLogin
{
    private const int MaxNetworkFailures = 5;

    public static async Task<TokenResponse?> SignInAsync(
        HttpClient http,
        string authority, // e.g., "https://idp.example.com"
        string clientId,
        string scope,
        Action<string, string> showCode, // (userCode, verificationUri)
        CancellationToken ct,
        Func<string>? createClientAssertion = null) // used to sign private_key_jwt with the device key
    {
        var auth = await http.RequestDeviceAuthorizationAsync(new DeviceAuthorizationRequest
        {
            Address = $"{authority}/connect/deviceauthorization",
            ClientId = clientId,
            Scope = scope,
            // Both request types inherit ClientAssertion. Public clients skip it.
            ClientCredentialStyle = ClientCredentialStyle.PostBody,
            ClientAssertion = createClientAssertion is null ? new ClientAssertion() : new ClientAssertion
            {
                Type = OidcConstants.ClientAssertionTypes.JwtBearer,
                Value = createClientAssertion()
            }
        }, ct);

        if (auth.IsError || auth.DeviceCode is null || auth.UserCode is null
            || auth.VerificationUri is null || auth.ExpiresIn is not > 0)
        {
            return null; // fail closed: no usable device authorization
        }

        showCode(auth.UserCode, auth.VerificationUri);

        var interval = TimeSpan.FromSeconds(auth.Interval > 0 ? auth.Interval : 5);
        var deadline = DateTimeOffset.UtcNow.AddSeconds(auth.ExpiresIn.Value);
        var networkFailures = 0;

        while (DateTimeOffset.UtcNow < deadline)
        {
            await Task.Delay(interval, ct);

            var token = await http.RequestDeviceTokenAsync(new DeviceTokenRequest
            {
                Address = $"{authority}/connect/token",
                ClientId = clientId,
                DeviceCode = auth.DeviceCode,
                // A client assertion is single-use, so sign a new one for every poll.
                ClientCredentialStyle = ClientCredentialStyle.PostBody,
                ClientAssertion = createClientAssertion is null ? new ClientAssertion() : new ClientAssertion
                {
                    Type = OidcConstants.ClientAssertionTypes.JwtBearer,
                    Value = createClientAssertion()
                }
            }, ct);

            if (!token.IsError)
            {
                return token;
            }

            if (token.ErrorType == ResponseErrorType.Http)
            {
                // Network or transport problem: back off, and give up after a few tries.
                if (++networkFailures >= MaxNetworkFailures)
                {
                    return null;
                }
                await Task.Delay(TimeSpan.FromSeconds(Math.Min(60, Math.Pow(2, networkFailures))), ct);
                continue;
            }

            networkFailures = 0;

            switch (token.Error)
            {
                case "authorization_pending":
                    continue;
                case "slow_down":
                    interval += TimeSpan.FromSeconds(5); // applies to all later polls
                    continue;
                default:
                    // access_denied, expired_token or anything unexpected: stop, no token.
                    return null;
            }
        }

        // expires_in elapsed
        return null;
    }
}

Passing a CancellationToken into every delay and HTTP call lets a cancel button or device shutdown stop the loop immediately.

How Should a Device Display the Sign-In Code?

Consider the following usability implementation details for the device flow display interface:

  • By default, Duende IdentityServer generates a 9-digit numeric user_code. You can plug in your own IUserCodeGenerator if you prefer an alphanumeric character set that avoids ambiguous characters like 0 and O.
  • IdentityServer's device authorization response returns both verification_uri (for users typing the URL and code by hand) and verification_uri_complete, which pre-fills the user code in the query string. Rendering verification_uri_complete as a QR code on the device screen lets the user scan it with their phone camera and go straight to sign-in and approval without typing the code.
  • On the device screen, display a visible countdown based on expires_in, and update the screen immediately when the poll succeeds or expires.
  • On the IdentityServer consent screen, display the client name and requested scopes clearly so the user can confirm they are approving the device in front of them rather than a code someone sent them in a phishing message. Duende IdentityServer v8 never remembers consent for device flow, so every device authorization is an explicit approval.

When Should You Use Device Flow vs. Client Credentials (private_key_jwt) vs. mTLS?

Use device flow when you need user-delegated authorization on a device without browser input. Use client credentials when the device acts autonomously as a service or workload, utilizing asymmetric keys (private_key_jwt) or mTLS certificates.

Device flow Client credentials (private_key_jwt) mTLS

Who is authenticated

A user, approving a device

The device or workload itself

The device, by its X.509 certificate

Needs a human

Yes, at enrollment and re-authorization

No

No

Needs PKI

No

A key pair per workload

Yes, to issue and revoke certificates

Token represents

The user's delegated authorization

The client

The client, optionally bound to its certificate (cnf)

Typical device

Handhelds, kiosks, CLIs, consoles

Back-end workers and services

Managed fleets with a PKI

Keep in mind that device flow alone only proves a user approved the request, while a client certificate or TPM-backed key proves which physical device is calling. As we saw with the edge gateway earlier, you can combine both when you need user approval tied to specific hardware. For unattended sensors or background services where no human is present, skip device flow and use client credentials with a private-key JWT or mTLS.

For private_key_jwt with client credentials, the ClientSecrets registration with IdentityServerConstants.SecretTypes.JsonWebKey is the same as the edge-gw-042 gateway we configured earlier, just with AllowedGrantTypes = GrantTypes.ClientCredentials. Only the public key lives in IdentityServer; the workload keeps the private key.

For devices that come with a certificate, mTLS lets the certificate authenticate the client:

Csharp

new Client
{
    ClientId = "opcua-server-01",
    ClientName = "OPC UA Server (Line 3)",
    AllowedGrantTypes = GrantTypes.ClientCredentials,

    ClientSecrets =
    {
        new Secret
        {
            Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint,
            Value = "A1B2C3D4E5F6..."
        }
    },

    AllowedScopes = { "mes.write", "historian.write", "scada.events" },
    AccessTokenLifetime = 3600,
    AccessTokenType = AccessTokenType.Jwt,

    Claims =
    {
        new ClientClaim("device_type", "opcua_server"),
        new ClientClaim("location", "building-a"),
        new ClientClaim("line", "3")
    }
}

To enable mTLS client authentication in Duende IdentityServer, call AddMutualTlsSecretValidators() during service registration:

Csharp

builder.Services.AddIdentityServer()
    .AddMutualTlsSecretValidators();

Along with registering the secret validators, enable the mTLS endpoints in your IdentityServer options and configure your web server or reverse proxy to validate the client certificate chain and revocation status against your PKI before forwarding the certificate to IdentityServer. The Duende mTLS documentation covers the host and proxy setup in detail.

Managing Access Tokens in .NET Worker Services

A background service using client credentials still needs to obtain access tokens and replace them when they expire. Duende.AccessTokenManagement handles that through a configured HttpClient, so your worker code can concentrate on calling the API.

Csharp

var secret = builder.Configuration["Worker:ClientSecret"]
    ?? throw new InvalidOperationException("Worker:ClientSecret is not configured.");

builder.Services.AddClientCredentialsTokenManagement()
    .AddClient(ClientCredentialsClientName.Parse("telemetry.client"), client =>
    {
        client.TokenEndpoint = new Uri("https://idp.example.com/connect/token");
        client.ClientId = ClientId.Parse("edge-worker-01");
        client.ClientSecret = ClientSecret.Parse(secret);
        client.Scope = Scope.Parse("telemetry.push");
    });

builder.Services.AddClientCredentialsHttpClient(
    "telemetry",
    ClientCredentialsClientName.Parse("telemetry.client"),
    client => client.BaseAddress = new Uri("https://api.example.com/telemetry/"));

// Illustrative: TelemetryWorker is application code, not a Duende API.
public class TelemetryWorker(IHttpClientFactory factory) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var client = factory.CreateClient("telemetry");
        while (!stoppingToken.IsCancellationRequested)
        {
            var response = await client.PostAsync("push", content: null, stoppingToken);
            if (!response.IsSuccessStatusCode)
            {
                // Fail closed: surface the failure instead of retrying with a different identity.
                throw new HttpRequestException($"Push failed with status {(int)response.StatusCode}.");
            }

            await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
        }
    }
}

A shared client secret is the simple option. If you would rather not keep a secret on the host at all, the library can authenticate with private_key_jwt client assertions, so the worker holds a key pair instead. The client assertions page in the docs covers the setup.

If your workloads run in Azure and already have a managed identity, see Bridge Azure Workload Identity to Client Identity with Dynamic Client Registration for how to register them without managing secrets in configuration.

How to Revoke Tokens and Offboard a Device in Duende IdentityServer

When a device is lost, sold, or decommissioned, you revoke its access in Duende IdentityServer by disabling the client, deleting its persisted grants with IPersistedGrantStore.RemoveAllAsync, and revoking its certificate. IdentityServer does not have a single client-level revoke API:

  1. Set Enabled = false on the client.
  2. Remove its persisted grants with IPersistedGrantStore.RemoveAllAsync(PersistedGrantFilter). That removes refresh tokens, reference tokens, and consents.
  3. Revoke the device certificate or the enrollment record in your own PKI or registry.
  4. Keep in mind that JWT access tokens that were already issued stay valid until they expire, which is why access token lifetimes should be short.

The revocation endpoint, /connect/revocation, does not replace this. It revokes one presented token per call, so it suits a client handing back a single token, not an operator closing down a device.

Csharp

// Remove all refresh tokens, reference tokens, and consents for the retired device.
// PersistedGrantFilter also exposes ClientIds when retiring a batch of devices at once.
await persistedGrantStore.RemoveAllAsync(new PersistedGrantFilter
{
    ClientId = "edge-gw-042"
});

FAQ

How Can a Headless Device Authenticate Without a Browser?

A headless device authenticates without a browser by using the OAuth 2.0 Device Flow, also known as the Device Authorization Grant (RFC 8628). The device requests a code from IdentityServer, shows it, and the user signs in and confirms the code on another device, such as a phone. The headless device polls the token endpoint and receives tokens once the user has finished.

How Should an IoT Client Handle Polling, Expiration and slow_down?

An IoT client handles polling correctly by waiting between polls for the interval returned by the device authorization endpoint (5 seconds by default). On slow_down, add 5 seconds to the interval for all later polls. Stop on access_denied or expired_token, and when expires_in has passed, then start a new flow if the user still wants one.

When Should I Use Device Flow Instead of Client Credentials?

Use device flow instead of client credentials when a person must authorize the device and the tokens should carry that person's delegated authorization. Use client credentials when the device or workload acts as itself, preferably with private_key_jwt or an mTLS certificate. Device flow is not meant for unattended sensors.

How Do I Revoke a Device's Access in IdentityServer?

IdentityServer has no client-level revoke API, so you revoke a device's access in several steps. Disable the client with Enabled = false, remove its persisted grants with IPersistedGrantStore.RemoveAllAsync(PersistedGrantFilter), and revoke the device certificate or enrollment record. JWT access tokens already issued remain valid until they expire.

Can a Device Get a Refresh Token With Device Flow?

A device can get a refresh token with device flow. The client needs AllowOfflineAccess = true, and the device must request the offline_access scope. For devices on unreliable networks, RefreshTokenUsage = TokenUsage.ReUse avoids a lockout when a rotation response gets lost.

Wrapping Up

Device flow lets users approve access from their own browser without entering credentials on the device. For gateways with per-device keys, private_key_jwt also authenticates the client making the request. Before deploying, decide how users will reauthorize devices and how you'll remove access when a device is retired.

If you want to go deeper, the Device Authorization Endpoint docs cover the protocol details, Refresh Tokens explains lifetimes and rotation, and the Persisted Grant Store reference describes what you remove when a device retires. For back-end workers, see Duende Access Token Management for Workers.

If you are designing a device fleet and want a second opinion, take a look at the Duende partners, or ask in the Duende community discussions.

About the author

Maarten Balliauw Head of Customer Success

Loves building web and cloud apps. He focuses on .NET web technologies, C#, Microsoft Azure, and application performance. Creator of SpeakerTravel and formerly founded MyGet.

Related Articles