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.
-
Actors: the user with a browser, the device (
service-client,DeviceFlowCli),auth-server. -
Clients involved:
device-client, public (none), grant typesurn:ietf:params:oauth:grant-type:device_codeandrefresh_token, scopesprofile documents.read, consent required. It is seeded byDevDataInitializerunder thedevprofile only; elsewhere, register such a client throughPOST /api/admin/clients. -
Preconditions: Spring profile
device-flowonservice-clientwithdevice-flow.issuer(required); optionaldevice-flow.client-id(defaultdevice-client),device-flow.scope(defaultprofile documents.read) anddevice-flow.print-access-token. Noopenidscope: Spring Authorization Server refuses it in device requests. Rate limit settingsauthserver.device.rate-limit.*(enabled,windowPT15M,per-client30,per-user10). -
Endpoints:
POST /oauth2/device_authorization(framework),GET /oauth2/device_verification(custom page) andPOST /oauth2/device_verification(framework),/oauth2/consent,POST /oauth2/token.
Steps
-
DeviceFlowClicallsDeviceAuthorizationClient.requestDeviceAuthorization:POST /oauth2/device_authorizationwithclient_idandscope, no secret. -
DeviceProtocolChainCustomizer(aProtocolChainCustomizer, order 2) has enabled the device endpoints and addedDeviceClientAuthenticationConverter/DeviceClientAuthenticationProvider: for a request to the device authorization endpoint or adevice_codepoll that carries aclient_idand no credential, the client is authenticated by id alone, provided it is registered with thenonemethod. -
The server answers
device_code,user_code(for exampleABCD-EFGH),verification_uri(/oauth2/device_verification),verification_uri_complete(with the user code),expires_inandinterval. The CLI prints the user code and both addresses. -
The user opens the address. Not signed in, the browser goes to
/loginand comes back afterwards. -
Without a code,
DeviceVerificationControllerrenderstemplates/device-verification.html(a form postinguser_codetoPOST /oauth2/device_verification). The complete address carries the code and goes straight to the framework’s verification endpoint. -
DeviceVerificationRequestGuardruns first among the verification converters:-
it counts the attempt in
DeviceVerificationRateLimiterper client address and per user; over the limit,DeviceVerificationErrorHandleranswers429withRetry-After; -
it finds the client of the device authorization stored for the user code (
OAuth2AuthorizationService.findByToken, the code normalised toXXXX-XXXX), falling back to the consent post’sclient_id, and applies the MFA policy with that client’smfaRequired; when it is not satisfied, the user is sent to/login/second-factorand the request resumes after the second factor.
-
-
The framework looks the user code up. An unknown or expired code redirects to
/oauth2/device_verification?error. Otherwise, becausedevice-clientrequires consent, it redirects to/oauth2/consent. -
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. -
Meanwhile
DeviceFlowClipolls: it waitsintervalseconds, thenDeviceAuthorizationClient.pollTokenpostsgrant_type=urn:ietf:params:oauth:grant-type:device_code,device_codeandclient_idto/oauth2/token.-
authorization_pending: keep polling. -
slow_down: addDeviceFlowCli.SLOW_DOWN_INCREMENT_SECONDS(5) to the interval. -
access_denied(the user denied) orexpired_token, or the local deadline fromexpires_inpasses: stop with aDeviceFlowException. -
200: printtoken_type,expires_in,scopeand whether a refresh token came, and the access token whendevice-flow.print-access-tokenis 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));
}
}
Tokens and claims
-
Token response:
access_token(JWT),refresh_token,token_type=Bearer,expires_in,scope. No ID token (noopenid). -
sub: the user who approved (demowith the dev data).scope: the approved scopes, for exampleprofile documents.read. -
aud: the client’s configured audiences; the seededdevice-clienthasresource-serverand the API audience (authserver.api.audience, defaultauth-server).rolesandtenant: 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:DeviceFlowEndToEndITruns the packagedservice-clientwithdevice-flow, approves in headless Chromium through Playwright and checks the token; a denial ends the tool without tokens. -
service-client/boot: unit testsDeviceFlowCliTestandDeviceAuthorizationClientTest(pending, slow down, denial, expiry).