Device authorization grant

This documentation was generated with the assistance of AI. Please report any inaccuracies.

A program that cannot open a browser or type a password (a CLI, a TV, an IoT device) asks the authorization server for a device code and a short user code, shows the user code and a verification address, and polls the token endpoint. The user opens the address on another device, signs in (with a second factor when the policy asks for one), enters or confirms the code and approves on the consent page. The next poll returns the tokens. In this repository the device is service-client started with the device-flow profile (DeviceFlowCli) and the client is the public device-client.

At a glance
  • Actors: the user with a browser, the device (service-client, DeviceFlowCli), auth-server.

  • Clients involved: device-client, public (none), grant types urn:ietf:params:oauth:grant-type:device_code and refresh_token, scopes profile documents.read, consent required. It is seeded by DevDataInitializer under the dev profile only; elsewhere, register such a client through POST /api/admin/clients.

  • Preconditions: Spring profile device-flow on service-client with device-flow.issuer (required); optional device-flow.client-id (default device-client), device-flow.scope (default profile documents.read) and device-flow.print-access-token. No openid scope: Spring Authorization Server refuses it in device requests. Rate limit settings authserver.device.rate-limit.* (enabled, window PT15M, per-client 30, per-user 10).

  • Endpoints: POST /oauth2/device_authorization (framework), GET /oauth2/device_verification (custom page) and POST /oauth2/device_verification (framework), /oauth2/consent, POST /oauth2/token.

Steps

  1. DeviceFlowCli calls DeviceAuthorizationClient.requestDeviceAuthorization: POST /oauth2/device_authorization with client_id and scope, no secret.

  2. DeviceProtocolChainCustomizer (a ProtocolChainCustomizer, order 2) has enabled the device endpoints and added DeviceClientAuthenticationConverter / DeviceClientAuthenticationProvider: for a request to the device authorization endpoint or a device_code poll that carries a client_id and no credential, the client is authenticated by id alone, provided it is registered with the none method.

  3. The server answers device_code, user_code (for example ABCD-EFGH), verification_uri (/oauth2/device_verification), verification_uri_complete (with the user code), expires_in and interval. The CLI prints the user code and both addresses.

  4. The user opens the address. Not signed in, the browser goes to /login and comes back afterwards.

  5. Without a code, DeviceVerificationController renders templates/device-verification.html (a form posting user_code to POST /oauth2/device_verification). The complete address carries the code and goes straight to the framework’s verification endpoint.

  6. DeviceVerificationRequestGuard runs first among the verification converters:

    1. it counts the attempt in DeviceVerificationRateLimiter per client address and per user; over the limit, DeviceVerificationErrorHandler answers 429 with Retry-After;

    2. it finds the client of the device authorization stored for the user code (OAuth2AuthorizationService.findByToken, the code normalised to XXXX-XXXX), falling back to the consent post’s client_id, and applies the MFA policy with that client’s mfaRequired; when it is not satisfied, the user is sent to /login/second-factor and the request resumes after the second factor.

  7. The framework looks the user code up. An unknown or expired code redirects to /oauth2/device_verification?error. Otherwise, because device-client requires consent, it redirects to /oauth2/consent.

  8. The user approves (or denies) the scopes; the consent page posts the decision to POST /oauth2/device_verification. On approval the success handler redirects to /oauth2/device_verification?success.

  9. Meanwhile DeviceFlowCli polls: it waits interval seconds, then DeviceAuthorizationClient.pollToken posts grant_type=urn:ietf:params:oauth:grant-type:device_code, device_code and client_id to /oauth2/token.

    1. authorization_pending: keep polling.

    2. slow_down: add DeviceFlowCli.SLOW_DOWN_INCREMENT_SECONDS (5) to the interval.

    3. access_denied (the user denied) or expired_token, or the local deadline from expires_in passes: stop with a DeviceFlowException.

    4. 200: print token_type, expires_in, scope and whether a refresh token came, and the access token when device-flow.print-access-token is set.

/**
 * Guards the device verification endpoint. It is installed first among the converters of the endpoint and never
 * converts anything: it either lets the request go on (returning {@code null}) or refuses it. Every request that
 * carries a user code (the code typed on the verification page, a link that carries it, and the consent decision) is
 * counted against the limit on the attempts, and the multi-factor policy of the account and of the client must be
 * satisfied, as the authorization endpoint requires before it issues a code: a user who owes a second factor is sent
 * to the second-factor page and resumes afterwards. The framework's own MFA customizer covers only
 * {@code /oauth2/authorize}.
 *
 * <p>The client is the one the device authorization stored for the user code was issued to, because the code typed on
 * the page (or carried by the link) is the only thing the request names: so a client that requires multi-factor
 * authentication is enforced even when it skips the consent page. Only when no authorization holds the code (an
 * unknown or expired one, which the endpoint refuses anyway) is the {@code client_id} of the consent decision used.
 */
@RequiredArgsConstructor
public class DeviceVerificationRequestGuard implements AuthenticationConverter {

    /** Type of the token the user code is stored as. */
    static final OAuth2TokenType USER_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.USER_CODE);

    /** Number of letters and digits of a user code. */
    private static final int USER_CODE_LENGTH = 8;

    /** Position of the dash the framework stores a user code with. */
    private static final int USER_CODE_GROUP = USER_CODE_LENGTH / 2;

    /** Everything a user may type around the letters and digits of a code (dashes, spaces). */
    private static final Pattern NOT_ALPHANUMERIC = Pattern.compile("[^A-Z\\d]+");

    /** Limits the attempts. */
    private final DeviceVerificationRateLimiter rateLimiter;

    /** Applies the multi-factor policy. */
    private final MfaAuthorizationManager authorizationManager;

    /** Finds the device authorization of a user code. */
    private final OAuth2AuthorizationService authorizationService;

    /** Finds the client of a device authorization. */
    private final RegisteredClientRepository registeredClientRepository;

    /**
     * Checks the request.
     *
     * @param request the request.
     * @return always {@code null}: this converter only vetoes requests.
     * @throws DeviceVerificationRateLimitedException if the client address or the user made too many attempts.
     * @throws SecondFactorRequiredException          if the user still owes a second factor.
     */
    @Override
    public Authentication convert(final HttpServletRequest request) {
        final var user = SecurityContextHolder.getContext().getAuthentication();
        if (!MfaAuthorizationManager.isUser(user)) {
            return null;
        }
        rateLimiter.check(request.getRemoteAddr(), user.getName());
        final var clientRequires = authorizationManager.clientRequiresMfa(clientIdOf(request));
        if (!authorizationManager.evaluate(user, clientRequires).isGranted()) {
            throw new SecondFactorRequiredException();
        }
        return null;
    }

    /**
     * Finds the client a request is about: the client of the device authorization stored for its user code, or the
     * {@code client_id} parameter when no authorization holds that code.
     *
     * @param request the request.
     * @return the client id, or {@code null} when neither tells it.
     */
    private String clientIdOf(final HttpServletRequest request) {
        return normalize(request.getParameter(OAuth2ParameterNames.USER_CODE))
                .map(userCode -> authorizationService.findByToken(userCode, USER_CODE_TOKEN_TYPE))
                .map(authorization -> registeredClientRepository.findById(authorization.getRegisteredClientId()))
                .map(RegisteredClient::getClientId)
                .orElseGet(() -> request.getParameter(OAuth2ParameterNames.CLIENT_ID));
    }

    /**
     * Normalises a user code as the framework stores it: upper case letters and digits in two groups of four,
     * separated by a dash.
     *
     * @param userCode the code as typed, may be {@code null}.
     * @return the stored form, or empty when the value cannot be a user code.
     */
    private static Optional<String> normalize(final String userCode) {
        if (!StringUtils.hasText(userCode)) {
            return Optional.empty();
        }
        final var compact = NOT_ALPHANUMERIC.matcher(userCode.toUpperCase(Locale.ROOT)).replaceAll("");
        if (compact.length() != USER_CODE_LENGTH) {
            return Optional.empty();
        }
        return Optional.of(compact.substring(0, USER_CODE_GROUP) + "-" + compact.substring(USER_CODE_GROUP));
    }
}
sequenceDiagram autonumber participant D as DeviceFlowCli participant A as auth-server participant B as User browser D->>A: POST /oauth2/device_authorization client_id=device-client scope A-->>D: device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval D->>D: print user code and addresses B->>A: GET verification_uri_complete A-->>B: 302 /login B->>A: sign in, second factor if required A->>A: DeviceVerificationRequestGuard: rate limit and MFA policy A-->>B: 302 /oauth2/consent B->>A: approve scopes, POST /oauth2/device_verification A-->>B: 302 /oauth2/device_verification?success loop every interval seconds D->>A: POST /oauth2/token grant_type=device_code device_code client_id alt user has not decided A-->>D: 400 authorization_pending else server asks to slow down A-->>D: 400 slow_down, interval plus 5 s else approved A-->>D: 200 access_token, refresh_token end end
flowchart TD P["POST /oauth2/device_verification (user_code)"] --> S{"Signed in?"} S -- No --> L[Redirect to /login] S -- Yes --> R{"Within rate limit?"} R -- No --> E429["429 with Retry-After"] R -- Yes --> M{"MFA policy satisfied for the code's client?"} M -- No --> SF[Redirect to /login/second-factor] M -- Yes --> C{"User code known and valid?"} C -- No --> ERR["Redirect to ?error"] C -- Yes --> CO[Consent page] CO -- Approve --> OK["Redirect to ?success, next poll gets tokens"] CO -- Deny --> DN["Next poll gets access_denied"]

Tokens and claims

  • Token response: access_token (JWT), refresh_token, token_type=Bearer, expires_in, scope. No ID token (no openid).

  • sub: the user who approved (demo with the dev data). scope: the approved scopes, for example profile documents.read.

  • aud: the client’s configured audiences; the seeded device-client has resource-server and the API audience (authserver.api.audience, default auth-server). roles and tenant: the user’s.

  • The seeded client’s tokens live 10 minutes (access) and 8 hours (refresh).

How it is tested

  • auth-server/boot: DeviceVerificationPageIT (the page signed in and out, error and success states, a full approval in which the device obtains tokens, an unknown code, the complete address going straight to consent, and the second factor required by the account or by a client without consent); DeviceVerificationRateLimitIT (429).

  • e2e-tests: DeviceFlowEndToEndIT runs the packaged service-client with device-flow, approves in headless Chromium through Playwright and checks the token; a denial ends the tool without tokens.

  • service-client/boot: unit tests DeviceFlowCliTest and DeviceAuthorizationClientTest (pending, slow down, denial, expiry).