Skip to content

Check user code expiry and invalidity #1997

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2020-2023 the original author or authors.
* Copyright 2020-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -109,6 +109,15 @@ public Authentication authenticate(Authentication authentication) throws Authent
this.logger.trace("Retrieved authorization with user code");
}

OAuth2Authorization.Token<OAuth2UserCode> userCode = authorization.getToken(OAuth2UserCode.class);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please combine the 2 checks as follows:

if (!userCode.isActive()) {
	if (!userCode.isInvalidated()) {
		// Invalidate the user code
		authorization = OAuth2Authorization.from(authorization).invalidate(userCode.getToken()).build();
		this.authorizationService.save(authorization);
	}
	throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
}

And adjust the tests as necessary.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review, see last commit with the changes. A log might be relevant (see @colin-riddell's comment above). Let me know what you think.

if (!userCode.isActive()) {
if (!userCode.isInvalidated()) {
authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, userCode.getToken());
this.authorizationService.save(authorization);
}
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it worth providing more context on the error..

Suggested change
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, "User code is expired.", null);
throw new OAuth2AuthenticationException(error);

}

Authentication principal = (Authentication) deviceVerificationAuthentication.getPrincipal();
if (!isPrincipalAuthenticated(principal)) {
if (this.logger.isTraceEnabled()) {
Expand Down Expand Up @@ -161,7 +170,6 @@ public Authentication authenticate(Authentication authentication) throws Authent
requestedScopes, currentAuthorizedScopes);
}

OAuth2Authorization.Token<OAuth2UserCode> userCode = authorization.getToken(OAuth2UserCode.class);
// @formatter:off
authorization = OAuth2Authorization.from(authorization)
.principalName(principal.getName())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2020-2023 the original author or authors.
* Copyright 2020-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -20,6 +20,7 @@
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -145,10 +146,79 @@ public void authenticateWhenAuthorizationNotFoundThenThrowOAuth2AuthenticationEx
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
}

@Test
public void authenticateWhenUserCodeIsInvalidedThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
// @formatter:off
OAuth2Authorization authorization = TestOAuth2Authorizations
.authorization(registeredClient)
.token(createDeviceCode())
.token(createUserCode(), withInvalidated())
.attribute(OAuth2ParameterNames.SCOPE, registeredClient.getScopes())
.build();
// @formatter:on
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
Authentication authentication = createAuthentication();
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @formatter:on

verify(this.authorizationService).findByToken(USER_CODE,
OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
}

@Test
public void authenticateWhenUserCodeIsExpiredButNotInvalidatedThenInvalidateUserCodeAndThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
// @formatter:off
OAuth2Authorization authorization = TestOAuth2Authorizations
.authorization(registeredClient)
// Device code would also be expired but not relevant for this test
.token(createDeviceCode())
.token(createExpiredUserCode())
.attribute(OAuth2ParameterNames.SCOPE, registeredClient.getScopes())
.build();
// @formatter:on
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
Authentication authentication = createAuthentication();
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @formatter:on

ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
verify(this.authorizationService).findByToken(USER_CODE,
OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE);
verify(this.authorizationService).save(authorizationCaptor.capture());
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);

OAuth2Authorization updatedAuthorization = authorizationCaptor.getValue();
assertThat(updatedAuthorization.getToken(OAuth2UserCode.class))
.extracting(isInvalidated())
.isEqualTo(true);
}

@Test
public void authenticateWhenPrincipalNotAuthenticatedThenReturnUnauthenticated() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
// @formatter:off
OAuth2Authorization authorization = TestOAuth2Authorizations
.authorization(registeredClient)
.token(createDeviceCode())
.token(createUserCode())
.attribute(OAuth2ParameterNames.SCOPE, registeredClient.getScopes())
.build();
// @formatter:on
TestingAuthenticationToken principal = new TestingAuthenticationToken("user", null);
Authentication authentication = new OAuth2DeviceVerificationAuthenticationToken(principal, USER_CODE,
Collections.emptyMap());
Expand Down Expand Up @@ -331,6 +401,15 @@ private static OAuth2UserCode createUserCode() {
return new OAuth2UserCode(USER_CODE, issuedAt, issuedAt.plus(30, ChronoUnit.MINUTES));
}

private static OAuth2UserCode createExpiredUserCode() {
Instant issuedAt = Instant.now().minus(45, ChronoUnit.MINUTES);
return new OAuth2UserCode(USER_CODE, issuedAt, issuedAt.plus(30, ChronoUnit.MINUTES));
}

private static Consumer<Map<String, Object>> withInvalidated() {
return (metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true);
}

private static Function<OAuth2Authorization.Token<? extends OAuth2Token>, Boolean> isInvalidated() {
return (token) -> token.getMetadata(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME);
}
Expand Down