Apply updated Code Style
Closes gh-13881
This commit is contained in:
@@ -75,7 +75,9 @@ import org.springframework.util.StringUtils;
|
||||
public final class AuthorizedClientServiceOAuth2AuthorizedClientManager implements OAuth2AuthorizedClientManager {
|
||||
|
||||
private static final OAuth2AuthorizedClientProvider DEFAULT_AUTHORIZED_CLIENT_PROVIDER = OAuth2AuthorizedClientProviderBuilder
|
||||
.builder().clientCredentials().build();
|
||||
.builder()
|
||||
.clientCredentials()
|
||||
.build();
|
||||
|
||||
private final ClientRegistrationRepository clientRegistrationRepository;
|
||||
|
||||
@@ -105,10 +107,10 @@ public final class AuthorizedClientServiceOAuth2AuthorizedClientManager implemen
|
||||
this.authorizedClientProvider = DEFAULT_AUTHORIZED_CLIENT_PROVIDER;
|
||||
this.contextAttributesMapper = new DefaultContextAttributesMapper();
|
||||
this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientService
|
||||
.saveAuthorizedClient(authorizedClient, principal);
|
||||
.saveAuthorizedClient(authorizedClient, principal);
|
||||
this.authorizationFailureHandler = new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(
|
||||
(clientRegistrationId, principal, attributes) -> authorizedClientService
|
||||
.removeAuthorizedClient(clientRegistrationId, principal.getName()));
|
||||
.removeAuthorizedClient(clientRegistrationId, principal.getName()));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@@ -124,7 +126,7 @@ public final class AuthorizedClientServiceOAuth2AuthorizedClientManager implemen
|
||||
}
|
||||
else {
|
||||
ClientRegistration clientRegistration = this.clientRegistrationRepository
|
||||
.findByRegistrationId(clientRegistrationId);
|
||||
.findByRegistrationId(clientRegistrationId);
|
||||
Assert.notNull(clientRegistration,
|
||||
"Could not find ClientRegistration with id '" + clientRegistrationId + "'");
|
||||
authorizedClient = this.authorizedClientService.loadAuthorizedClient(clientRegistrationId,
|
||||
|
||||
@@ -83,7 +83,9 @@ public final class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager
|
||||
implements ReactiveOAuth2AuthorizedClientManager {
|
||||
|
||||
private static final ReactiveOAuth2AuthorizedClientProvider DEFAULT_AUTHORIZED_CLIENT_PROVIDER = ReactiveOAuth2AuthorizedClientProviderBuilder
|
||||
.builder().clientCredentials().build();
|
||||
.builder()
|
||||
.clientCredentials()
|
||||
.build();
|
||||
|
||||
private final ReactiveClientRegistrationRepository clientRegistrationRepository;
|
||||
|
||||
@@ -111,41 +113,41 @@ public final class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager
|
||||
this.clientRegistrationRepository = clientRegistrationRepository;
|
||||
this.authorizedClientService = authorizedClientService;
|
||||
this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientService
|
||||
.saveAuthorizedClient(authorizedClient, principal);
|
||||
.saveAuthorizedClient(authorizedClient, principal);
|
||||
this.authorizationFailureHandler = new RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler(
|
||||
(clientRegistrationId, principal, attributes) -> this.authorizedClientService
|
||||
.removeAuthorizedClient(clientRegistrationId, principal.getName()));
|
||||
.removeAuthorizedClient(clientRegistrationId, principal.getName()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizeRequest authorizeRequest) {
|
||||
Assert.notNull(authorizeRequest, "authorizeRequest cannot be null");
|
||||
return createAuthorizationContext(authorizeRequest)
|
||||
.flatMap((authorizationContext) -> authorize(authorizationContext, authorizeRequest.getPrincipal()));
|
||||
.flatMap((authorizationContext) -> authorize(authorizationContext, authorizeRequest.getPrincipal()));
|
||||
}
|
||||
|
||||
private Mono<OAuth2AuthorizationContext> createAuthorizationContext(OAuth2AuthorizeRequest authorizeRequest) {
|
||||
String clientRegistrationId = authorizeRequest.getClientRegistrationId();
|
||||
Authentication principal = authorizeRequest.getPrincipal();
|
||||
return Mono.justOrEmpty(authorizeRequest.getAuthorizedClient())
|
||||
.map(OAuth2AuthorizationContext::withAuthorizedClient)
|
||||
.switchIfEmpty(Mono.defer(() -> this.clientRegistrationRepository
|
||||
.findByRegistrationId(clientRegistrationId)
|
||||
.flatMap((clientRegistration) -> this.authorizedClientService
|
||||
.loadAuthorizedClient(clientRegistrationId, principal.getName())
|
||||
.map(OAuth2AuthorizationContext::withAuthorizedClient)
|
||||
.switchIfEmpty(Mono.fromSupplier(
|
||||
() -> OAuth2AuthorizationContext.withClientRegistration(clientRegistration))))
|
||||
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(
|
||||
"Could not find ClientRegistration with id '" + clientRegistrationId + "'")))))
|
||||
.flatMap((contextBuilder) -> this.contextAttributesMapper.apply(authorizeRequest)
|
||||
.defaultIfEmpty(Collections.emptyMap()).map((contextAttributes) -> {
|
||||
OAuth2AuthorizationContext.Builder builder = contextBuilder.principal(principal);
|
||||
if (!contextAttributes.isEmpty()) {
|
||||
builder = builder.attributes((attributes) -> attributes.putAll(contextAttributes));
|
||||
}
|
||||
return builder.build();
|
||||
}));
|
||||
.map(OAuth2AuthorizationContext::withAuthorizedClient)
|
||||
.switchIfEmpty(Mono.defer(() -> this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)
|
||||
.flatMap((clientRegistration) -> this.authorizedClientService
|
||||
.loadAuthorizedClient(clientRegistrationId, principal.getName())
|
||||
.map(OAuth2AuthorizationContext::withAuthorizedClient)
|
||||
.switchIfEmpty(Mono
|
||||
.fromSupplier(() -> OAuth2AuthorizationContext.withClientRegistration(clientRegistration))))
|
||||
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(
|
||||
"Could not find ClientRegistration with id '" + clientRegistrationId + "'")))))
|
||||
.flatMap((contextBuilder) -> this.contextAttributesMapper.apply(authorizeRequest)
|
||||
.defaultIfEmpty(Collections.emptyMap())
|
||||
.map((contextAttributes) -> {
|
||||
OAuth2AuthorizationContext.Builder builder = contextBuilder.principal(principal);
|
||||
if (!contextAttributes.isEmpty()) {
|
||||
builder = builder.attributes((attributes) -> attributes.putAll(contextAttributes));
|
||||
}
|
||||
return builder.build();
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -162,17 +164,17 @@ public final class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager
|
||||
private Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext authorizationContext,
|
||||
Authentication principal) {
|
||||
return this.authorizedClientProvider.authorize(authorizationContext)
|
||||
// Delegate to the authorizationSuccessHandler of the successful
|
||||
// authorization
|
||||
.flatMap((authorizedClient) -> this.authorizationSuccessHandler
|
||||
.onAuthorizationSuccess(authorizedClient, principal, Collections.emptyMap())
|
||||
.thenReturn(authorizedClient))
|
||||
// Delegate to the authorizationFailureHandler of the failed authorization
|
||||
.onErrorResume(OAuth2AuthorizationException.class,
|
||||
(authorizationException) -> this.authorizationFailureHandler
|
||||
.onAuthorizationFailure(authorizationException, principal, Collections.emptyMap())
|
||||
.then(Mono.error(authorizationException)))
|
||||
.switchIfEmpty(Mono.defer(() -> Mono.justOrEmpty(authorizationContext.getAuthorizedClient())));
|
||||
// Delegate to the authorizationSuccessHandler of the successful
|
||||
// authorization
|
||||
.flatMap((authorizedClient) -> this.authorizationSuccessHandler
|
||||
.onAuthorizationSuccess(authorizedClient, principal, Collections.emptyMap())
|
||||
.thenReturn(authorizedClient))
|
||||
// Delegate to the authorizationFailureHandler of the failed authorization
|
||||
.onErrorResume(OAuth2AuthorizationException.class,
|
||||
(authorizationException) -> this.authorizationFailureHandler
|
||||
.onAuthorizationFailure(authorizationException, principal, Collections.emptyMap())
|
||||
.then(Mono.error(authorizationException)))
|
||||
.switchIfEmpty(Mono.defer(() -> Mono.justOrEmpty(authorizationContext.getAuthorizedClient())));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -81,12 +81,11 @@ public final class ClientCredentialsReactiveOAuth2AuthorizedClientProvider
|
||||
// Therefore, renewing an expired access token (re-authorization)
|
||||
// is the same as acquiring a new access token (authorization).
|
||||
return Mono.just(new OAuth2ClientCredentialsGrantRequest(clientRegistration))
|
||||
.flatMap(this.accessTokenResponseClient::getTokenResponse)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(ex) -> new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(),
|
||||
ex))
|
||||
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
|
||||
tokenResponse.getAccessToken()));
|
||||
.flatMap(this.accessTokenResponseClient::getTokenResponse)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(ex) -> new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex))
|
||||
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
|
||||
tokenResponse.getAccessToken()));
|
||||
}
|
||||
|
||||
private boolean hasTokenExpired(OAuth2Token token) {
|
||||
|
||||
@@ -73,7 +73,8 @@ public final class DelegatingReactiveOAuth2AuthorizedClientProvider implements R
|
||||
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext context) {
|
||||
Assert.notNull(context, "context cannot be null");
|
||||
return Flux.fromIterable(this.authorizedClientProviders)
|
||||
.concatMap((authorizedClientProvider) -> authorizedClientProvider.authorize(context)).next();
|
||||
.concatMap((authorizedClientProvider) -> authorizedClientProvider.authorize(context))
|
||||
.next();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -62,8 +62,8 @@ public final class InMemoryReactiveOAuth2AuthorizedClientService implements Reac
|
||||
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
|
||||
Assert.hasText(principalName, "principalName cannot be empty");
|
||||
return (Mono<T>) this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)
|
||||
.map((clientRegistration) -> new OAuth2AuthorizedClientId(clientRegistrationId, principalName))
|
||||
.flatMap((identifier) -> Mono.justOrEmpty(this.authorizedClients.get(identifier)));
|
||||
.map((clientRegistration) -> new OAuth2AuthorizedClientId(clientRegistrationId, principalName))
|
||||
.flatMap((identifier) -> Mono.justOrEmpty(this.authorizedClients.get(identifier)));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -166,8 +166,8 @@ public class JdbcOAuth2AuthorizedClientService implements OAuth2AuthorizedClient
|
||||
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
|
||||
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
|
||||
Assert.notNull(principal, "principal cannot be null");
|
||||
boolean existsAuthorizedClient = null != this.loadAuthorizedClient(
|
||||
authorizedClient.getClientRegistration().getRegistrationId(), principal.getName());
|
||||
boolean existsAuthorizedClient = null != this
|
||||
.loadAuthorizedClient(authorizedClient.getClientRegistration().getRegistrationId(), principal.getName());
|
||||
if (existsAuthorizedClient) {
|
||||
updateAuthorizedClient(authorizedClient, principal);
|
||||
}
|
||||
@@ -183,7 +183,7 @@ public class JdbcOAuth2AuthorizedClientService implements OAuth2AuthorizedClient
|
||||
|
||||
private void updateAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
|
||||
List<SqlParameterValue> parameters = this.authorizedClientParametersMapper
|
||||
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal));
|
||||
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal));
|
||||
SqlParameterValue clientRegistrationIdParameter = parameters.remove(0);
|
||||
SqlParameterValue principalNameParameter = parameters.remove(0);
|
||||
parameters.add(clientRegistrationIdParameter);
|
||||
@@ -197,7 +197,7 @@ public class JdbcOAuth2AuthorizedClientService implements OAuth2AuthorizedClient
|
||||
|
||||
private void insertAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
|
||||
List<SqlParameterValue> parameters = this.authorizedClientParametersMapper
|
||||
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal));
|
||||
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal));
|
||||
try (LobCreator lobCreator = this.lobHandler.getLobCreator()) {
|
||||
PreparedStatementSetter pss = new LobCreatorArgumentPreparedStatementSetter(lobCreator,
|
||||
parameters.toArray());
|
||||
@@ -265,7 +265,7 @@ public class JdbcOAuth2AuthorizedClientService implements OAuth2AuthorizedClient
|
||||
public OAuth2AuthorizedClient mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
String clientRegistrationId = rs.getString("client_registration_id");
|
||||
ClientRegistration clientRegistration = this.clientRegistrationRepository
|
||||
.findByRegistrationId(clientRegistrationId);
|
||||
.findByRegistrationId(clientRegistrationId);
|
||||
if (clientRegistration == null) {
|
||||
throw new DataRetrievalFailureException(
|
||||
"The ClientRegistration with id '" + clientRegistrationId + "' exists in the data source, "
|
||||
@@ -320,8 +320,8 @@ public class JdbcOAuth2AuthorizedClientService implements OAuth2AuthorizedClient
|
||||
parameters.add(new SqlParameterValue(Types.VARCHAR, clientRegistration.getRegistrationId()));
|
||||
parameters.add(new SqlParameterValue(Types.VARCHAR, principal.getName()));
|
||||
parameters.add(new SqlParameterValue(Types.VARCHAR, accessToken.getTokenType().getValue()));
|
||||
parameters.add(
|
||||
new SqlParameterValue(Types.BLOB, accessToken.getTokenValue().getBytes(StandardCharsets.UTF_8)));
|
||||
parameters
|
||||
.add(new SqlParameterValue(Types.BLOB, accessToken.getTokenValue().getBytes(StandardCharsets.UTF_8)));
|
||||
parameters.add(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(accessToken.getIssuedAt())));
|
||||
parameters.add(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(accessToken.getExpiresAt())));
|
||||
String accessTokenScopes = null;
|
||||
|
||||
@@ -46,7 +46,7 @@ public final class OAuth2AuthorizationContext {
|
||||
* client}.
|
||||
*/
|
||||
public static final String REQUEST_SCOPE_ATTRIBUTE_NAME = OAuth2AuthorizationContext.class.getName()
|
||||
.concat(".REQUEST_SCOPE");
|
||||
.concat(".REQUEST_SCOPE");
|
||||
|
||||
/**
|
||||
* The name of the {@link #getAttribute(String) attribute} in the context associated
|
||||
|
||||
@@ -220,7 +220,7 @@ public final class OAuth2AuthorizeRequest {
|
||||
OAuth2AuthorizeRequest authorizeRequest = new OAuth2AuthorizeRequest();
|
||||
if (this.authorizedClient != null) {
|
||||
authorizeRequest.clientRegistrationId = this.authorizedClient.getClientRegistration()
|
||||
.getRegistrationId();
|
||||
.getRegistrationId();
|
||||
authorizeRequest.authorizedClient = this.authorizedClient;
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -104,8 +104,8 @@ public final class OAuth2AuthorizedClientProviderBuilder {
|
||||
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
|
||||
*/
|
||||
public OAuth2AuthorizedClientProviderBuilder refreshToken(Consumer<RefreshTokenGrantBuilder> builderConsumer) {
|
||||
RefreshTokenGrantBuilder builder = (RefreshTokenGrantBuilder) this.builders.computeIfAbsent(
|
||||
RefreshTokenOAuth2AuthorizedClientProvider.class, (k) -> new RefreshTokenGrantBuilder());
|
||||
RefreshTokenGrantBuilder builder = (RefreshTokenGrantBuilder) this.builders
|
||||
.computeIfAbsent(RefreshTokenOAuth2AuthorizedClientProvider.class, (k) -> new RefreshTokenGrantBuilder());
|
||||
builderConsumer.accept(builder);
|
||||
return OAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
@@ -163,7 +163,7 @@ public final class OAuth2AuthorizedClientProviderBuilder {
|
||||
@Deprecated
|
||||
public OAuth2AuthorizedClientProviderBuilder password(Consumer<PasswordGrantBuilder> builderConsumer) {
|
||||
PasswordGrantBuilder builder = (PasswordGrantBuilder) this.builders
|
||||
.computeIfAbsent(PasswordOAuth2AuthorizedClientProvider.class, (k) -> new PasswordGrantBuilder());
|
||||
.computeIfAbsent(PasswordOAuth2AuthorizedClientProvider.class, (k) -> new PasswordGrantBuilder());
|
||||
builderConsumer.accept(builder);
|
||||
return OAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -107,12 +107,12 @@ public final class PasswordReactiveOAuth2AuthorizedClientProvider implements Rea
|
||||
}
|
||||
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, username,
|
||||
password);
|
||||
return Mono.just(passwordGrantRequest).flatMap(this.accessTokenResponseClient::getTokenResponse)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(),
|
||||
e))
|
||||
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
|
||||
tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()));
|
||||
return Mono.just(passwordGrantRequest)
|
||||
.flatMap(this.accessTokenResponseClient::getTokenResponse)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(), e))
|
||||
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
|
||||
tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()));
|
||||
}
|
||||
|
||||
private boolean hasTokenExpired(OAuth2Token token) {
|
||||
|
||||
@@ -140,17 +140,19 @@ public class R2dbcReactiveOAuth2AuthorizedClientService implements ReactiveOAuth
|
||||
Assert.hasText(principalName, "principalName cannot be empty");
|
||||
|
||||
return (Mono<T>) this.databaseClient.sql(LOAD_AUTHORIZED_CLIENT_SQL)
|
||||
.bind("clientRegistrationId", clientRegistrationId).bind("principalName", principalName)
|
||||
.map(this.authorizedClientRowMapper).first().flatMap(this::getAuthorizedClient);
|
||||
.bind("clientRegistrationId", clientRegistrationId)
|
||||
.bind("principalName", principalName)
|
||||
.map(this.authorizedClientRowMapper)
|
||||
.first()
|
||||
.flatMap(this::getAuthorizedClient);
|
||||
}
|
||||
|
||||
private Mono<OAuth2AuthorizedClient> getAuthorizedClient(OAuth2AuthorizedClientHolder authorizedClientHolder) {
|
||||
return this.clientRegistrationRepository.findByRegistrationId(authorizedClientHolder.getClientRegistrationId())
|
||||
.switchIfEmpty(
|
||||
Mono.error(dataRetrievalFailureException(authorizedClientHolder.getClientRegistrationId())))
|
||||
.map((clientRegistration) -> new OAuth2AuthorizedClient(clientRegistration,
|
||||
authorizedClientHolder.getPrincipalName(), authorizedClientHolder.getAccessToken(),
|
||||
authorizedClientHolder.getRefreshToken()));
|
||||
.switchIfEmpty(Mono.error(dataRetrievalFailureException(authorizedClientHolder.getClientRegistrationId())))
|
||||
.map((clientRegistration) -> new OAuth2AuthorizedClient(clientRegistration,
|
||||
authorizedClientHolder.getPrincipalName(), authorizedClientHolder.getAccessToken(),
|
||||
authorizedClientHolder.getRefreshToken()));
|
||||
}
|
||||
|
||||
private static Throwable dataRetrievalFailureException(String clientRegistrationId) {
|
||||
@@ -163,15 +165,17 @@ public class R2dbcReactiveOAuth2AuthorizedClientService implements ReactiveOAuth
|
||||
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
|
||||
Assert.notNull(principal, "principal cannot be null");
|
||||
return this
|
||||
.loadAuthorizedClient(authorizedClient.getClientRegistration().getRegistrationId(), principal.getName())
|
||||
.flatMap((dbAuthorizedClient) -> updateAuthorizedClient(authorizedClient, principal))
|
||||
.switchIfEmpty(Mono.defer(() -> insertAuthorizedClient(authorizedClient, principal))).then();
|
||||
.loadAuthorizedClient(authorizedClient.getClientRegistration().getRegistrationId(), principal.getName())
|
||||
.flatMap((dbAuthorizedClient) -> updateAuthorizedClient(authorizedClient, principal))
|
||||
.switchIfEmpty(Mono.defer(() -> insertAuthorizedClient(authorizedClient, principal)))
|
||||
.then();
|
||||
}
|
||||
|
||||
private Mono<Integer> updateAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
|
||||
GenericExecuteSpec executeSpec = this.databaseClient.sql(UPDATE_AUTHORIZED_CLIENT_SQL);
|
||||
for (Entry<String, Parameter> entry : this.authorizedClientParametersMapper
|
||||
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal)).entrySet()) {
|
||||
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal))
|
||||
.entrySet()) {
|
||||
executeSpec = executeSpec.bind(entry.getKey(), entry.getValue());
|
||||
}
|
||||
return executeSpec.fetch().rowsUpdated();
|
||||
@@ -180,7 +184,8 @@ public class R2dbcReactiveOAuth2AuthorizedClientService implements ReactiveOAuth
|
||||
private Mono<Integer> insertAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
|
||||
GenericExecuteSpec executeSpec = this.databaseClient.sql(SAVE_AUTHORIZED_CLIENT_SQL);
|
||||
for (Entry<String, Parameter> entry : this.authorizedClientParametersMapper
|
||||
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal)).entrySet()) {
|
||||
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal))
|
||||
.entrySet()) {
|
||||
executeSpec = executeSpec.bind(entry.getKey(), entry.getValue());
|
||||
}
|
||||
return executeSpec.fetch().rowsUpdated();
|
||||
@@ -190,8 +195,10 @@ public class R2dbcReactiveOAuth2AuthorizedClientService implements ReactiveOAuth
|
||||
public Mono<Void> removeAuthorizedClient(String clientRegistrationId, String principalName) {
|
||||
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
|
||||
Assert.hasText(principalName, "principalName cannot be empty");
|
||||
return this.databaseClient.sql(REMOVE_AUTHORIZED_CLIENT_SQL).bind("clientRegistrationId", clientRegistrationId)
|
||||
.bind("principalName", principalName).then();
|
||||
return this.databaseClient.sql(REMOVE_AUTHORIZED_CLIENT_SQL)
|
||||
.bind("clientRegistrationId", clientRegistrationId)
|
||||
.bind("principalName", principalName)
|
||||
.then();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -310,10 +317,10 @@ public class R2dbcReactiveOAuth2AuthorizedClientService implements ReactiveOAuth
|
||||
Parameter.fromOrEmpty(accessToken.getTokenType().getValue(), String.class));
|
||||
parameters.put("accessTokenValue", Parameter.fromOrEmpty(
|
||||
ByteBuffer.wrap(accessToken.getTokenValue().getBytes(StandardCharsets.UTF_8)), ByteBuffer.class));
|
||||
parameters.put("accessTokenIssuedAt", Parameter.fromOrEmpty(
|
||||
LocalDateTime.ofInstant(accessToken.getIssuedAt(), ZoneOffset.UTC), LocalDateTime.class));
|
||||
parameters.put("accessTokenExpiresAt", Parameter.fromOrEmpty(
|
||||
LocalDateTime.ofInstant(accessToken.getExpiresAt(), ZoneOffset.UTC), LocalDateTime.class));
|
||||
parameters.put("accessTokenIssuedAt", Parameter
|
||||
.fromOrEmpty(LocalDateTime.ofInstant(accessToken.getIssuedAt(), ZoneOffset.UTC), LocalDateTime.class));
|
||||
parameters.put("accessTokenExpiresAt", Parameter
|
||||
.fromOrEmpty(LocalDateTime.ofInstant(accessToken.getExpiresAt(), ZoneOffset.UTC), LocalDateTime.class));
|
||||
String accessTokenScopes = null;
|
||||
if (!CollectionUtils.isEmpty(accessToken.getScopes())) {
|
||||
accessTokenScopes = StringUtils.collectionToDelimitedString(accessToken.getScopes(), ",");
|
||||
@@ -350,7 +357,7 @@ public class R2dbcReactiveOAuth2AuthorizedClientService implements ReactiveOAuth
|
||||
String dbClientRegistrationId = row.get("client_registration_id", String.class);
|
||||
OAuth2AccessToken.TokenType tokenType = null;
|
||||
if (OAuth2AccessToken.TokenType.BEARER.getValue()
|
||||
.equalsIgnoreCase(row.get("access_token_type", String.class))) {
|
||||
.equalsIgnoreCase(row.get("access_token_type", String.class))) {
|
||||
tokenType = OAuth2AccessToken.TokenType.BEARER;
|
||||
}
|
||||
String tokenValue = new String(row.get("access_token_value", ByteBuffer.class).array(),
|
||||
|
||||
@@ -165,8 +165,8 @@ public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
@Deprecated
|
||||
public ReactiveOAuth2AuthorizedClientProviderBuilder password(Consumer<PasswordGrantBuilder> builderConsumer) {
|
||||
PasswordGrantBuilder builder = (PasswordGrantBuilder) this.builders.computeIfAbsent(
|
||||
PasswordReactiveOAuth2AuthorizedClientProvider.class, (k) -> new PasswordGrantBuilder());
|
||||
PasswordGrantBuilder builder = (PasswordGrantBuilder) this.builders
|
||||
.computeIfAbsent(PasswordReactiveOAuth2AuthorizedClientProvider.class, (k) -> new PasswordGrantBuilder());
|
||||
builderConsumer.accept(builder);
|
||||
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
@@ -177,8 +177,10 @@ public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
|
||||
* @return the {@link DelegatingReactiveOAuth2AuthorizedClientProvider}
|
||||
*/
|
||||
public ReactiveOAuth2AuthorizedClientProvider build() {
|
||||
List<ReactiveOAuth2AuthorizedClientProvider> authorizedClientProviders = this.builders.values().stream()
|
||||
.map(Builder::build).collect(Collectors.toList());
|
||||
List<ReactiveOAuth2AuthorizedClientProvider> authorizedClientProviders = this.builders.values()
|
||||
.stream()
|
||||
.map(Builder::build)
|
||||
.collect(Collectors.toList());
|
||||
return new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProviders);
|
||||
}
|
||||
|
||||
|
||||
@@ -92,12 +92,12 @@ public final class RefreshTokenReactiveOAuth2AuthorizedClientProvider
|
||||
ClientRegistration clientRegistration = context.getClientRegistration();
|
||||
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
|
||||
authorizedClient.getAccessToken(), authorizedClient.getRefreshToken(), scopes);
|
||||
return Mono.just(refreshTokenGrantRequest).flatMap(this.accessTokenResponseClient::getTokenResponse)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(),
|
||||
e))
|
||||
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
|
||||
tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()));
|
||||
return Mono.just(refreshTokenGrantRequest)
|
||||
.flatMap(this.accessTokenResponseClient::getTokenResponse)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(), e))
|
||||
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
|
||||
tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()));
|
||||
}
|
||||
|
||||
private boolean hasTokenExpired(OAuth2Token token) {
|
||||
|
||||
@@ -103,7 +103,7 @@ public class RemoveAuthorizedClientOAuth2AuthorizationFailureHandler implements
|
||||
Assert.notNull(authorizedClientRemover, "authorizedClientRemover cannot be null");
|
||||
Assert.notNull(removeAuthorizedClientErrorCodes, "removeAuthorizedClientErrorCodes cannot be null");
|
||||
this.removeAuthorizedClientErrorCodes = Collections
|
||||
.unmodifiableSet(new HashSet<>(removeAuthorizedClientErrorCodes));
|
||||
.unmodifiableSet(new HashSet<>(removeAuthorizedClientErrorCodes));
|
||||
this.delegate = authorizedClientRemover;
|
||||
}
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ public class RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler
|
||||
Assert.notNull(authorizedClientRemover, "authorizedClientRemover cannot be null");
|
||||
Assert.notNull(removeAuthorizedClientErrorCodes, "removeAuthorizedClientErrorCodes cannot be null");
|
||||
this.removeAuthorizedClientErrorCodes = Collections
|
||||
.unmodifiableSet(new HashSet<>(removeAuthorizedClientErrorCodes));
|
||||
.unmodifiableSet(new HashSet<>(removeAuthorizedClientErrorCodes));
|
||||
this.delegate = authorizedClientRemover;
|
||||
}
|
||||
|
||||
|
||||
@@ -72,12 +72,12 @@ public class OAuth2AuthorizationCodeAuthenticationProvider implements Authentica
|
||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
|
||||
OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange()
|
||||
.getAuthorizationResponse();
|
||||
.getAuthorizationResponse();
|
||||
if (authorizationResponse.statusError()) {
|
||||
throw new OAuth2AuthorizationException(authorizationResponse.getError());
|
||||
}
|
||||
OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange()
|
||||
.getAuthorizationRequest();
|
||||
.getAuthorizationRequest();
|
||||
if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
|
||||
OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
|
||||
throw new OAuth2AuthorizationException(oauth2Error);
|
||||
|
||||
@@ -85,12 +85,12 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManager implements Rea
|
||||
return Mono.defer(() -> {
|
||||
OAuth2AuthorizationCodeAuthenticationToken token = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
|
||||
OAuth2AuthorizationResponse authorizationResponse = token.getAuthorizationExchange()
|
||||
.getAuthorizationResponse();
|
||||
.getAuthorizationResponse();
|
||||
if (authorizationResponse.statusError()) {
|
||||
return Mono.error(new OAuth2AuthorizationException(authorizationResponse.getError()));
|
||||
}
|
||||
OAuth2AuthorizationRequest authorizationRequest = token.getAuthorizationExchange()
|
||||
.getAuthorizationRequest();
|
||||
.getAuthorizationRequest();
|
||||
if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
|
||||
OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
|
||||
return Mono.error(new OAuth2AuthorizationException(oauth2Error));
|
||||
|
||||
@@ -95,8 +95,10 @@ public class OAuth2LoginAuthenticationProvider implements AuthenticationProvider
|
||||
// Section 3.1.2.1 Authentication Request -
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest scope
|
||||
// REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
|
||||
if (loginAuthenticationToken.getAuthorizationExchange().getAuthorizationRequest().getScopes()
|
||||
.contains("openid")) {
|
||||
if (loginAuthenticationToken.getAuthorizationExchange()
|
||||
.getAuthorizationRequest()
|
||||
.getScopes()
|
||||
.contains("openid")) {
|
||||
// This is an OpenID Connect Authentication Request so return null
|
||||
// and let OidcAuthorizationCodeAuthenticationProvider handle it instead
|
||||
return null;
|
||||
@@ -104,9 +106,9 @@ public class OAuth2LoginAuthenticationProvider implements AuthenticationProvider
|
||||
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken;
|
||||
try {
|
||||
authorizationCodeAuthenticationToken = (OAuth2AuthorizationCodeAuthenticationToken) this.authorizationCodeAuthenticationProvider
|
||||
.authenticate(new OAuth2AuthorizationCodeAuthenticationToken(
|
||||
loginAuthenticationToken.getClientRegistration(),
|
||||
loginAuthenticationToken.getAuthorizationExchange()));
|
||||
.authenticate(
|
||||
new OAuth2AuthorizationCodeAuthenticationToken(loginAuthenticationToken.getClientRegistration(),
|
||||
loginAuthenticationToken.getAuthorizationExchange()));
|
||||
}
|
||||
catch (OAuth2AuthorizationException ex) {
|
||||
OAuth2Error oauth2Error = ex.getError();
|
||||
@@ -117,7 +119,7 @@ public class OAuth2LoginAuthenticationProvider implements AuthenticationProvider
|
||||
OAuth2User oauth2User = this.userService.loadUser(new OAuth2UserRequest(
|
||||
loginAuthenticationToken.getClientRegistration(), accessToken, additionalParameters));
|
||||
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
|
||||
.mapAuthorities(oauth2User.getAuthorities());
|
||||
.mapAuthorities(oauth2User.getAuthorities());
|
||||
OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(
|
||||
loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange(),
|
||||
oauth2User, mappedAuthorities, accessToken, authorizationCodeAuthenticationToken.getRefreshToken());
|
||||
|
||||
@@ -98,9 +98,10 @@ public class OAuth2LoginReactiveAuthenticationManager implements ReactiveAuthent
|
||||
return Mono.empty();
|
||||
}
|
||||
return this.authorizationCodeManager.authenticate(token)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString(), e))
|
||||
.cast(OAuth2AuthorizationCodeAuthenticationToken.class).flatMap(this::onSuccess);
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString(), e))
|
||||
.cast(OAuth2AuthorizationCodeAuthenticationToken.class)
|
||||
.flatMap(this::onSuccess);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -124,7 +125,7 @@ public class OAuth2LoginReactiveAuthenticationManager implements ReactiveAuthent
|
||||
additionalParameters);
|
||||
return this.userService.loadUser(userRequest).map((oauth2User) -> {
|
||||
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
|
||||
.mapAuthorities(oauth2User.getAuthorities());
|
||||
.mapAuthorities(oauth2User.getAuthorities());
|
||||
OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(
|
||||
authentication.getClientRegistration(), authentication.getAuthorizationExchange(), oauth2User,
|
||||
mappedAuthorities, accessToken, authentication.getRefreshToken());
|
||||
|
||||
@@ -55,8 +55,9 @@ abstract class AbstractOAuth2AuthorizationGrantRequestEntityConverter<T extends
|
||||
HttpHeaders headers = getHeadersConverter().convert(authorizationGrantRequest);
|
||||
MultiValueMap<String, String> parameters = getParametersConverter().convert(authorizationGrantRequest);
|
||||
URI uri = UriComponentsBuilder
|
||||
.fromUriString(authorizationGrantRequest.getClientRegistration().getProviderDetails().getTokenUri())
|
||||
.build().toUri();
|
||||
.fromUriString(authorizationGrantRequest.getClientRegistration().getProviderDetails().getTokenUri())
|
||||
.build()
|
||||
.toUri();
|
||||
return new RequestEntity<>(parameters, headers, HttpMethod.POST, uri);
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ public abstract class AbstractWebClientReactiveOAuth2AccessTokenResponseClient<T
|
||||
private Converter<T, MultiValueMap<String, String>> parametersConverter = this::populateTokenRequestParameters;
|
||||
|
||||
private BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> bodyExtractor = OAuth2BodyExtractors
|
||||
.oauth2AccessTokenResponse();
|
||||
.oauth2AccessTokenResponse();
|
||||
|
||||
AbstractWebClientReactiveOAuth2AccessTokenResponseClient() {
|
||||
}
|
||||
@@ -225,7 +225,7 @@ public abstract class AbstractWebClientReactiveOAuth2AccessTokenResponseClient<T
|
||||
*/
|
||||
private Mono<OAuth2AccessTokenResponse> readTokenResponse(T grantRequest, ClientResponse response) {
|
||||
return response.body(this.bodyExtractor)
|
||||
.map((tokenResponse) -> populateTokenResponse(grantRequest, tokenResponse));
|
||||
.map((tokenResponse) -> populateTokenResponse(grantRequest, tokenResponse));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -75,7 +75,7 @@ public final class DefaultRefreshTokenTokenResponseClient
|
||||
if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())
|
||||
|| tokenResponse.getRefreshToken() == null) {
|
||||
OAuth2AccessTokenResponse.Builder tokenResponseBuilder = OAuth2AccessTokenResponse
|
||||
.withResponse(tokenResponse);
|
||||
.withResponse(tokenResponse);
|
||||
if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) {
|
||||
// As per spec, in Section 5.1 Successful Access Token Response
|
||||
// https://tools.ietf.org/html/rfc6749#section-5.1
|
||||
|
||||
@@ -92,7 +92,7 @@ public class NimbusAuthorizationCodeTokenResponseClient
|
||||
ClientID clientId = new ClientID(clientRegistration.getClientId());
|
||||
Secret clientSecret = new Secret(clientRegistration.getClientSecret());
|
||||
boolean isPost = ClientAuthenticationMethod.CLIENT_SECRET_POST
|
||||
.equals(clientRegistration.getClientAuthenticationMethod())
|
||||
.equals(clientRegistration.getClientAuthenticationMethod())
|
||||
|| ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod());
|
||||
ClientAuthentication clientAuthentication = isPost ? new ClientSecretPost(clientId, clientSecret)
|
||||
: new ClientSecretBasic(clientId, clientSecret);
|
||||
@@ -107,7 +107,7 @@ public class NimbusAuthorizationCodeTokenResponseClient
|
||||
String accessToken = accessTokenResponse.getTokens().getAccessToken().getValue();
|
||||
OAuth2AccessToken.TokenType accessTokenType = null;
|
||||
if (OAuth2AccessToken.TokenType.BEARER.getValue()
|
||||
.equalsIgnoreCase(accessTokenResponse.getTokens().getAccessToken().getType().getValue())) {
|
||||
.equalsIgnoreCase(accessTokenResponse.getTokens().getAccessToken().getType().getValue())) {
|
||||
accessTokenType = OAuth2AccessToken.TokenType.BEARER;
|
||||
}
|
||||
long expiresIn = accessTokenResponse.getTokens().getAccessToken().getLifetime();
|
||||
|
||||
@@ -110,7 +110,7 @@ public final class NimbusJwtClientAuthenticationParametersConverter<T extends Ab
|
||||
ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
|
||||
if (!ClientAuthenticationMethod.PRIVATE_KEY_JWT.equals(clientRegistration.getClientAuthenticationMethod())
|
||||
&& !ClientAuthenticationMethod.CLIENT_SECRET_JWT
|
||||
.equals(clientRegistration.getClientAuthenticationMethod())) {
|
||||
.equals(clientRegistration.getClientAuthenticationMethod())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ public class OAuth2AuthorizationCodeGrantRequestEntityConverter
|
||||
parameters.add(OAuth2ParameterNames.CODE, authorizationExchange.getAuthorizationResponse().getCode());
|
||||
String redirectUri = authorizationExchange.getAuthorizationRequest().getRedirectUri();
|
||||
String codeVerifier = authorizationExchange.getAuthorizationRequest()
|
||||
.getAttribute(PkceParameterNames.CODE_VERIFIER);
|
||||
.getAttribute(PkceParameterNames.CODE_VERIFIER);
|
||||
if (redirectUri != null) {
|
||||
parameters.add(OAuth2ParameterNames.REDIRECT_URI, redirectUri);
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ public class OAuth2RefreshTokenGrantRequest extends AbstractOAuth2AuthorizationG
|
||||
this.accessToken = accessToken;
|
||||
this.refreshToken = refreshToken;
|
||||
this.scopes = Collections
|
||||
.unmodifiableSet((scopes != null) ? new LinkedHashSet<>(scopes) : Collections.emptySet());
|
||||
.unmodifiableSet((scopes != null) ? new LinkedHashSet<>(scopes) : Collections.emptySet());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -77,7 +77,7 @@ public class WebClientReactiveAuthorizationCodeTokenResponseClient
|
||||
body.with(OAuth2ParameterNames.REDIRECT_URI, redirectUri);
|
||||
}
|
||||
String codeVerifier = authorizationExchange.getAuthorizationRequest()
|
||||
.getAttribute(PkceParameterNames.CODE_VERIFIER);
|
||||
.getAttribute(PkceParameterNames.CODE_VERIFIER);
|
||||
if (codeVerifier != null) {
|
||||
body.with(PkceParameterNames.CODE_VERIFIER, codeVerifier);
|
||||
}
|
||||
|
||||
@@ -65,8 +65,8 @@ public final class WebClientReactivePasswordTokenResponseClient
|
||||
BodyInserters.FormInserter<String> populateTokenRequestBody(OAuth2PasswordGrantRequest grantRequest,
|
||||
BodyInserters.FormInserter<String> body) {
|
||||
return super.populateTokenRequestBody(grantRequest, body)
|
||||
.with(OAuth2ParameterNames.USERNAME, grantRequest.getUsername())
|
||||
.with(OAuth2ParameterNames.PASSWORD, grantRequest.getPassword());
|
||||
.with(OAuth2ParameterNames.USERNAME, grantRequest.getUsername())
|
||||
.with(OAuth2ParameterNames.PASSWORD, grantRequest.getPassword());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ public final class WebClientReactiveRefreshTokenTokenResponseClient
|
||||
return accessTokenResponse;
|
||||
}
|
||||
OAuth2AccessTokenResponse.Builder tokenResponseBuilder = OAuth2AccessTokenResponse
|
||||
.withResponse(accessTokenResponse);
|
||||
.withResponse(accessTokenResponse);
|
||||
if (CollectionUtils.isEmpty(accessTokenResponse.getAccessToken().getScopes())) {
|
||||
tokenResponseBuilder.scopes(defaultScopes(grantRequest));
|
||||
}
|
||||
|
||||
@@ -53,27 +53,27 @@ final class ClientRegistrationDeserializer extends JsonDeserializer<ClientRegist
|
||||
JsonNode providerDetailsNode = JsonNodeUtils.findObjectNode(clientRegistrationNode, "providerDetails");
|
||||
JsonNode userInfoEndpointNode = JsonNodeUtils.findObjectNode(providerDetailsNode, "userInfoEndpoint");
|
||||
return ClientRegistration
|
||||
.withRegistrationId(JsonNodeUtils.findStringValue(clientRegistrationNode, "registrationId"))
|
||||
.clientId(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientId"))
|
||||
.clientSecret(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientSecret"))
|
||||
.clientAuthenticationMethod(CLIENT_AUTHENTICATION_METHOD_CONVERTER
|
||||
.convert(JsonNodeUtils.findObjectNode(clientRegistrationNode, "clientAuthenticationMethod")))
|
||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE_CONVERTER
|
||||
.convert(JsonNodeUtils.findObjectNode(clientRegistrationNode, "authorizationGrantType")))
|
||||
.redirectUri(JsonNodeUtils.findStringValue(clientRegistrationNode, "redirectUri"))
|
||||
.scope(JsonNodeUtils.findValue(clientRegistrationNode, "scopes", JsonNodeUtils.STRING_SET, mapper))
|
||||
.clientName(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientName"))
|
||||
.authorizationUri(JsonNodeUtils.findStringValue(providerDetailsNode, "authorizationUri"))
|
||||
.tokenUri(JsonNodeUtils.findStringValue(providerDetailsNode, "tokenUri"))
|
||||
.userInfoUri(JsonNodeUtils.findStringValue(userInfoEndpointNode, "uri"))
|
||||
.userInfoAuthenticationMethod(AUTHENTICATION_METHOD_CONVERTER
|
||||
.convert(JsonNodeUtils.findObjectNode(userInfoEndpointNode, "authenticationMethod")))
|
||||
.userNameAttributeName(JsonNodeUtils.findStringValue(userInfoEndpointNode, "userNameAttributeName"))
|
||||
.jwkSetUri(JsonNodeUtils.findStringValue(providerDetailsNode, "jwkSetUri"))
|
||||
.issuerUri(JsonNodeUtils.findStringValue(providerDetailsNode, "issuerUri"))
|
||||
.providerConfigurationMetadata(JsonNodeUtils.findValue(providerDetailsNode, "configurationMetadata",
|
||||
JsonNodeUtils.STRING_OBJECT_MAP, mapper))
|
||||
.build();
|
||||
.withRegistrationId(JsonNodeUtils.findStringValue(clientRegistrationNode, "registrationId"))
|
||||
.clientId(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientId"))
|
||||
.clientSecret(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientSecret"))
|
||||
.clientAuthenticationMethod(CLIENT_AUTHENTICATION_METHOD_CONVERTER
|
||||
.convert(JsonNodeUtils.findObjectNode(clientRegistrationNode, "clientAuthenticationMethod")))
|
||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE_CONVERTER
|
||||
.convert(JsonNodeUtils.findObjectNode(clientRegistrationNode, "authorizationGrantType")))
|
||||
.redirectUri(JsonNodeUtils.findStringValue(clientRegistrationNode, "redirectUri"))
|
||||
.scope(JsonNodeUtils.findValue(clientRegistrationNode, "scopes", JsonNodeUtils.STRING_SET, mapper))
|
||||
.clientName(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientName"))
|
||||
.authorizationUri(JsonNodeUtils.findStringValue(providerDetailsNode, "authorizationUri"))
|
||||
.tokenUri(JsonNodeUtils.findStringValue(providerDetailsNode, "tokenUri"))
|
||||
.userInfoUri(JsonNodeUtils.findStringValue(userInfoEndpointNode, "uri"))
|
||||
.userInfoAuthenticationMethod(AUTHENTICATION_METHOD_CONVERTER
|
||||
.convert(JsonNodeUtils.findObjectNode(userInfoEndpointNode, "authenticationMethod")))
|
||||
.userNameAttributeName(JsonNodeUtils.findStringValue(userInfoEndpointNode, "userNameAttributeName"))
|
||||
.jwkSetUri(JsonNodeUtils.findStringValue(providerDetailsNode, "jwkSetUri"))
|
||||
.issuerUri(JsonNodeUtils.findStringValue(providerDetailsNode, "issuerUri"))
|
||||
.providerConfigurationMetadata(JsonNodeUtils.findValue(providerDetailsNode, "configurationMetadata",
|
||||
JsonNodeUtils.STRING_OBJECT_MAP, mapper))
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ final class OAuth2AuthorizationRequestDeserializer extends JsonDeserializer<OAut
|
||||
private OAuth2AuthorizationRequest deserialize(JsonParser parser, ObjectMapper mapper, JsonNode root)
|
||||
throws JsonParseException {
|
||||
AuthorizationGrantType authorizationGrantType = AUTHORIZATION_GRANT_TYPE_CONVERTER
|
||||
.convert(JsonNodeUtils.findObjectNode(root, "authorizationGrantType"));
|
||||
.convert(JsonNodeUtils.findObjectNode(root, "authorizationGrantType"));
|
||||
Builder builder = getBuilder(parser, authorizationGrantType);
|
||||
builder.authorizationUri(JsonNodeUtils.findStringValue(root, "authorizationUri"));
|
||||
builder.clientId(JsonNodeUtils.findStringValue(root, "clientId"));
|
||||
|
||||
@@ -123,16 +123,18 @@ public class OidcAuthorizationCodeAuthenticationProvider implements Authenticati
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
|
||||
// scope
|
||||
// REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
|
||||
if (!authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getScopes()
|
||||
.contains(OidcScopes.OPENID)) {
|
||||
if (!authorizationCodeAuthentication.getAuthorizationExchange()
|
||||
.getAuthorizationRequest()
|
||||
.getScopes()
|
||||
.contains(OidcScopes.OPENID)) {
|
||||
// This is NOT an OpenID Connect Authentication Request so return null
|
||||
// and let OAuth2LoginAuthenticationProvider handle it instead
|
||||
return null;
|
||||
}
|
||||
OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange()
|
||||
.getAuthorizationRequest();
|
||||
.getAuthorizationRequest();
|
||||
OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange()
|
||||
.getAuthorizationResponse();
|
||||
.getAuthorizationResponse();
|
||||
if (authorizationResponse.statusError()) {
|
||||
throw new OAuth2AuthenticationException(authorizationResponse.getError(),
|
||||
authorizationResponse.getError().toString());
|
||||
@@ -156,7 +158,7 @@ public class OidcAuthorizationCodeAuthenticationProvider implements Authenticati
|
||||
OidcUser oidcUser = this.userService.loadUser(new OidcUserRequest(clientRegistration,
|
||||
accessTokenResponse.getAccessToken(), idToken, additionalParameters));
|
||||
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
|
||||
.mapAuthorities(oidcUser.getAuthorities());
|
||||
.mapAuthorities(oidcUser.getAuthorities());
|
||||
OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(
|
||||
authorizationCodeAuthentication.getClientRegistration(),
|
||||
authorizationCodeAuthentication.getAuthorizationExchange(), oidcUser, mappedAuthorities,
|
||||
|
||||
@@ -118,16 +118,19 @@ public class OidcAuthorizationCodeReactiveAuthenticationManager implements React
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
|
||||
// scope REQUIRED. OpenID Connect requests MUST contain the "openid" scope
|
||||
// value.
|
||||
if (!authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getScopes()
|
||||
.contains("openid")) {
|
||||
if (!authorizationCodeAuthentication.getAuthorizationExchange()
|
||||
.getAuthorizationRequest()
|
||||
.getScopes()
|
||||
.contains("openid")) {
|
||||
// This is an OpenID Connect Authentication Request so return empty
|
||||
// and let OAuth2LoginReactiveAuthenticationManager handle it instead
|
||||
return Mono.empty();
|
||||
}
|
||||
OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange()
|
||||
.getAuthorizationRequest();
|
||||
.getAuthorizationRequest();
|
||||
OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication
|
||||
.getAuthorizationExchange().getAuthorizationResponse();
|
||||
.getAuthorizationExchange()
|
||||
.getAuthorizationResponse();
|
||||
if (authorizationResponse.statusError()) {
|
||||
return Mono.error(new OAuth2AuthenticationException(authorizationResponse.getError(),
|
||||
authorizationResponse.getError().toString()));
|
||||
@@ -139,16 +142,16 @@ public class OidcAuthorizationCodeReactiveAuthenticationManager implements React
|
||||
OAuth2AuthorizationCodeGrantRequest authzRequest = new OAuth2AuthorizationCodeGrantRequest(
|
||||
authorizationCodeAuthentication.getClientRegistration(),
|
||||
authorizationCodeAuthentication.getAuthorizationExchange());
|
||||
return this.accessTokenResponseClient.getTokenResponse(authzRequest).flatMap(
|
||||
(accessTokenResponse) -> authenticationResult(authorizationCodeAuthentication, accessTokenResponse))
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString(), e))
|
||||
.onErrorMap(JwtException.class, (e) -> {
|
||||
OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, e.getMessage(),
|
||||
null);
|
||||
return new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(),
|
||||
e);
|
||||
});
|
||||
return this.accessTokenResponseClient.getTokenResponse(authzRequest)
|
||||
.flatMap((accessTokenResponse) -> authenticationResult(authorizationCodeAuthentication,
|
||||
accessTokenResponse))
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString(), e))
|
||||
.onErrorMap(JwtException.class, (e) -> {
|
||||
OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, e.getMessage(),
|
||||
null);
|
||||
return new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(), e);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -220,8 +223,9 @@ public class OidcAuthorizationCodeReactiveAuthenticationManager implements React
|
||||
|
||||
private static Mono<OidcIdToken> validateNonce(
|
||||
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication, OidcIdToken idToken) {
|
||||
String requestNonce = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest()
|
||||
.getAttribute(OidcParameterNames.NONCE);
|
||||
String requestNonce = authorizationCodeAuthentication.getAuthorizationExchange()
|
||||
.getAuthorizationRequest()
|
||||
.getAttribute(OidcParameterNames.NONCE);
|
||||
if (requestNonce != null) {
|
||||
String nonceHash = getNonceHash(requestNonce);
|
||||
String nonceHashClaim = idToken.getNonce();
|
||||
|
||||
@@ -118,8 +118,8 @@ public final class OidcIdTokenDecoderFactory implements JwtDecoderFactory<Client
|
||||
|
||||
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
|
||||
TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
|
||||
return (source) -> ClaimConversionService.getSharedInstance().convert(source, sourceDescriptor,
|
||||
targetDescriptor);
|
||||
return (source) -> ClaimConversionService.getSharedInstance()
|
||||
.convert(source, sourceDescriptor, targetDescriptor);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -129,7 +129,7 @@ public final class OidcIdTokenDecoderFactory implements JwtDecoderFactory<Client
|
||||
NimbusJwtDecoder jwtDecoder = buildDecoder(clientRegistration);
|
||||
jwtDecoder.setJwtValidator(this.jwtValidatorFactory.apply(clientRegistration));
|
||||
Converter<Map<String, Object>, Map<String, Object>> claimTypeConverter = this.claimTypeConverterFactory
|
||||
.apply(clientRegistration);
|
||||
.apply(clientRegistration);
|
||||
if (claimTypeConverter != null) {
|
||||
jwtDecoder.setClaimSetConverter(claimTypeConverter);
|
||||
}
|
||||
|
||||
@@ -118,8 +118,8 @@ public final class ReactiveOidcIdTokenDecoderFactory implements ReactiveJwtDecod
|
||||
|
||||
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
|
||||
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
|
||||
return (source) -> ClaimConversionService.getSharedInstance().convert(source, sourceDescriptor,
|
||||
targetDescriptor);
|
||||
return (source) -> ClaimConversionService.getSharedInstance()
|
||||
.convert(source, sourceDescriptor, targetDescriptor);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -129,7 +129,7 @@ public final class ReactiveOidcIdTokenDecoderFactory implements ReactiveJwtDecod
|
||||
NimbusReactiveJwtDecoder jwtDecoder = buildDecoder(clientRegistration);
|
||||
jwtDecoder.setJwtValidator(this.jwtValidatorFactory.apply(clientRegistration));
|
||||
Converter<Map<String, Object>, Map<String, Object>> claimTypeConverter = this.claimTypeConverterFactory
|
||||
.apply(clientRegistration);
|
||||
.apply(clientRegistration);
|
||||
if (claimTypeConverter != null) {
|
||||
jwtDecoder.setClaimSetConverter(claimTypeConverter);
|
||||
}
|
||||
@@ -163,8 +163,9 @@ public final class ReactiveOidcIdTokenDecoderFactory implements ReactiveJwtDecod
|
||||
null);
|
||||
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
|
||||
}
|
||||
return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).jwsAlgorithm((SignatureAlgorithm) jwsAlgorithm)
|
||||
.build();
|
||||
return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri)
|
||||
.jwsAlgorithm((SignatureAlgorithm) jwsAlgorithm)
|
||||
.build();
|
||||
}
|
||||
if (jwsAlgorithm != null && MacAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
|
||||
@@ -189,8 +190,9 @@ public final class ReactiveOidcIdTokenDecoderFactory implements ReactiveJwtDecod
|
||||
}
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8),
|
||||
JCA_ALGORITHM_MAPPINGS.get(jwsAlgorithm));
|
||||
return NimbusReactiveJwtDecoder.withSecretKey(secretKeySpec).macAlgorithm((MacAlgorithm) jwsAlgorithm)
|
||||
.build();
|
||||
return NimbusReactiveJwtDecoder.withSecretKey(secretKeySpec)
|
||||
.macAlgorithm((MacAlgorithm) jwsAlgorithm)
|
||||
.build();
|
||||
}
|
||||
OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE,
|
||||
"Failed to find a Signature Verifier for Client Registration: '"
|
||||
|
||||
@@ -90,8 +90,8 @@ public class OidcReactiveOAuth2UserService implements ReactiveOAuth2UserService<
|
||||
|
||||
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
|
||||
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
|
||||
return (source) -> ClaimConversionService.getSharedInstance().convert(source, sourceDescriptor,
|
||||
targetDescriptor);
|
||||
return (source) -> ClaimConversionService.getSharedInstance()
|
||||
.convert(source, sourceDescriptor, targetDescriptor);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -144,7 +144,7 @@ public class OidcReactiveOAuth2UserService implements ReactiveOAuth2UserService<
|
||||
|
||||
private Map<String, Object> convertClaims(Map<String, Object> claims, ClientRegistration clientRegistration) {
|
||||
Converter<Map<String, Object>, Map<String, Object>> claimTypeConverter = this.claimTypeConverterFactory
|
||||
.apply(clientRegistration);
|
||||
.apply(clientRegistration);
|
||||
return (claimTypeConverter != null) ? claimTypeConverter.convert(claims)
|
||||
: DEFAULT_CLAIM_TYPE_CONVERTER.convert(claims);
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@ public class OidcUserService implements OAuth2UserService<OidcUserRequest, OidcU
|
||||
|
||||
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
|
||||
TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
|
||||
return (source) -> ClaimConversionService.getSharedInstance().convert(source, sourceDescriptor,
|
||||
targetDescriptor);
|
||||
return (source) -> ClaimConversionService.getSharedInstance()
|
||||
.convert(source, sourceDescriptor, targetDescriptor);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -138,7 +138,7 @@ public class OidcUserService implements OAuth2UserService<OidcUserRequest, OidcU
|
||||
|
||||
private Map<String, Object> getClaims(OidcUserRequest userRequest, OAuth2User oauth2User) {
|
||||
Converter<Map<String, Object>, Map<String, Object>> converter = this.claimTypeConverterFactory
|
||||
.apply(userRequest.getClientRegistration());
|
||||
.apply(userRequest.getClientRegistration());
|
||||
if (converter != null) {
|
||||
return converter.convert(oauth2User.getAttributes());
|
||||
}
|
||||
@@ -170,7 +170,7 @@ public class OidcUserService implements OAuth2UserService<OidcUserRequest, OidcU
|
||||
// The Authorization Code Grant Flow, which is response_type=code, results in an
|
||||
// Access Token being issued.
|
||||
if (AuthorizationGrantType.AUTHORIZATION_CODE
|
||||
.equals(userRequest.getClientRegistration().getAuthorizationGrantType())) {
|
||||
.equals(userRequest.getClientRegistration().getAuthorizationGrantType())) {
|
||||
// Return true if there is at least one match between the authorized scope(s)
|
||||
// and accessible scope(s)
|
||||
//
|
||||
|
||||
@@ -63,7 +63,7 @@ public final class OidcClientInitiatedLogoutSuccessHandler extends SimpleUrlLogo
|
||||
if (authentication instanceof OAuth2AuthenticationToken && authentication.getPrincipal() instanceof OidcUser) {
|
||||
String registrationId = ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId();
|
||||
ClientRegistration clientRegistration = this.clientRegistrationRepository
|
||||
.findByRegistrationId(registrationId);
|
||||
.findByRegistrationId(registrationId);
|
||||
URI endSessionEndpoint = this.endSessionEndpoint(clientRegistration);
|
||||
if (endSessionEndpoint != null) {
|
||||
String idToken = idToken(authentication);
|
||||
|
||||
@@ -97,8 +97,9 @@ public class OidcClientInitiatedServerLogoutSuccessHandler implements ServerLogo
|
||||
|
||||
private URI endSessionEndpoint(ClientRegistration clientRegistration) {
|
||||
if (clientRegistration != null) {
|
||||
Object endSessionEndpoint = clientRegistration.getProviderDetails().getConfigurationMetadata()
|
||||
.get("end_session_endpoint");
|
||||
Object endSessionEndpoint = clientRegistration.getProviderDetails()
|
||||
.getConfigurationMetadata()
|
||||
.get("end_session_endpoint");
|
||||
if (endSessionEndpoint != null) {
|
||||
return URI.create(endSessionEndpoint.toString());
|
||||
}
|
||||
|
||||
@@ -732,8 +732,9 @@ public final class ClientRegistration implements Serializable {
|
||||
}
|
||||
|
||||
private static boolean validateScope(String scope) {
|
||||
return scope == null || scope.chars().allMatch((c) -> withinTheRangeOf(c, 0x21, 0x21)
|
||||
|| withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
|
||||
return scope == null || scope.chars()
|
||||
.allMatch((c) -> withinTheRangeOf(c, 0x21, 0x21) || withinTheRangeOf(c, 0x23, 0x5B)
|
||||
|| withinTheRangeOf(c, 0x5D, 0x7E));
|
||||
}
|
||||
|
||||
private static boolean withinTheRangeOf(int c, int min, int max) {
|
||||
|
||||
@@ -163,7 +163,7 @@ public final class ClientRegistrations {
|
||||
Map<String, Object> configuration = rest.exchange(request, typeReference).getBody();
|
||||
OIDCProviderMetadata metadata = parse(configuration, OIDCProviderMetadata::parse);
|
||||
ClientRegistration.Builder builder = withProviderConfiguration(metadata, issuer.toASCIIString())
|
||||
.jwkSetUri(metadata.getJWKSetURI().toASCIIString());
|
||||
.jwkSetUri(metadata.getJWKSetURI().toASCIIString());
|
||||
if (metadata.getUserInfoEndpointURI() != null) {
|
||||
builder.userInfoUri(metadata.getUserInfoEndpointURI().toASCIIString());
|
||||
}
|
||||
@@ -266,7 +266,7 @@ public final class ClientRegistrations {
|
||||
private static ClientAuthenticationMethod getClientAuthenticationMethod(
|
||||
List<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> metadataAuthMethods) {
|
||||
if (metadataAuthMethods == null || metadataAuthMethods
|
||||
.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) {
|
||||
.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) {
|
||||
// If null, the default includes client_secret_basic
|
||||
return ClientAuthenticationMethod.CLIENT_SECRET_BASIC;
|
||||
}
|
||||
|
||||
@@ -88,15 +88,17 @@ public class DefaultOAuth2UserService implements OAuth2UserService<OAuth2UserReq
|
||||
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
|
||||
Assert.notNull(userRequest, "userRequest cannot be null");
|
||||
if (!StringUtils
|
||||
.hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) {
|
||||
.hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) {
|
||||
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE,
|
||||
"Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: "
|
||||
+ userRequest.getClientRegistration().getRegistrationId(),
|
||||
null);
|
||||
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
|
||||
}
|
||||
String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint()
|
||||
.getUserNameAttributeName();
|
||||
String userNameAttributeName = userRequest.getClientRegistration()
|
||||
.getProviderDetails()
|
||||
.getUserInfoEndpoint()
|
||||
.getUserNameAttributeName();
|
||||
if (!StringUtils.hasText(userNameAttributeName)) {
|
||||
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE,
|
||||
"Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: "
|
||||
@@ -125,7 +127,7 @@ public class DefaultOAuth2UserService implements OAuth2UserService<OAuth2UserReq
|
||||
StringBuilder errorDetails = new StringBuilder();
|
||||
errorDetails.append("Error details: [");
|
||||
errorDetails.append("UserInfo Uri: ")
|
||||
.append(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri());
|
||||
.append(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri());
|
||||
errorDetails.append(", Error Code: ").append(oauth2Error.getErrorCode());
|
||||
if (oauth2Error.getDescription() != null) {
|
||||
errorDetails.append(", Error Description: ").append(oauth2Error.getDescription());
|
||||
|
||||
@@ -84,8 +84,10 @@ public class DefaultReactiveOAuth2UserService implements ReactiveOAuth2UserServi
|
||||
public Mono<OAuth2User> loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
|
||||
return Mono.defer(() -> {
|
||||
Assert.notNull(userRequest, "userRequest cannot be null");
|
||||
String userInfoUri = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint()
|
||||
.getUri();
|
||||
String userInfoUri = userRequest.getClientRegistration()
|
||||
.getProviderDetails()
|
||||
.getUserInfoEndpoint()
|
||||
.getUri();
|
||||
if (!StringUtils.hasText(userInfoUri)) {
|
||||
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE,
|
||||
"Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: "
|
||||
@@ -93,8 +95,10 @@ public class DefaultReactiveOAuth2UserService implements ReactiveOAuth2UserServi
|
||||
null);
|
||||
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
|
||||
}
|
||||
String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails()
|
||||
.getUserInfoEndpoint().getUserNameAttributeName();
|
||||
String userNameAttributeName = userRequest.getClientRegistration()
|
||||
.getProviderDetails()
|
||||
.getUserInfoEndpoint()
|
||||
.getUserNameAttributeName();
|
||||
if (!StringUtils.hasText(userNameAttributeName)) {
|
||||
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE,
|
||||
"Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: "
|
||||
@@ -102,8 +106,10 @@ public class DefaultReactiveOAuth2UserService implements ReactiveOAuth2UserServi
|
||||
null);
|
||||
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
|
||||
}
|
||||
AuthenticationMethod authenticationMethod = userRequest.getClientRegistration().getProviderDetails()
|
||||
.getUserInfoEndpoint().getAuthenticationMethod();
|
||||
AuthenticationMethod authenticationMethod = userRequest.getClientRegistration()
|
||||
.getProviderDetails()
|
||||
.getUserInfoEndpoint()
|
||||
.getAuthenticationMethod();
|
||||
WebClient.RequestHeadersSpec<?> requestHeadersSpec = getRequestHeaderSpec(userRequest, userInfoUri,
|
||||
authenticationMethod);
|
||||
// @formatter:off
|
||||
@@ -195,7 +201,7 @@ public class DefaultReactiveOAuth2UserService implements ReactiveOAuth2UserServi
|
||||
}
|
||||
// Other error?
|
||||
return httpResponse.bodyToMono(STRING_STRING_MAP)
|
||||
.map((body) -> new UserInfoErrorResponse(ErrorObject.parse(new JSONObject(body))));
|
||||
.map((body) -> new UserInfoErrorResponse(ErrorObject.parse(new JSONObject(body))));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ import org.springframework.web.util.UriComponentsBuilder;
|
||||
public class OAuth2UserRequestEntityConverter implements Converter<OAuth2UserRequest, RequestEntity<?>> {
|
||||
|
||||
private static final MediaType DEFAULT_CONTENT_TYPE = MediaType
|
||||
.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
|
||||
/**
|
||||
* Returns the {@link RequestEntity} used for the UserInfo Request.
|
||||
@@ -58,7 +58,9 @@ public class OAuth2UserRequestEntityConverter implements Converter<OAuth2UserReq
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
|
||||
URI uri = UriComponentsBuilder
|
||||
.fromUriString(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri()).build().toUri();
|
||||
.fromUriString(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri())
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
RequestEntity<?> request;
|
||||
if (HttpMethod.POST.equals(httpMethod)) {
|
||||
@@ -77,7 +79,7 @@ public class OAuth2UserRequestEntityConverter implements Converter<OAuth2UserReq
|
||||
|
||||
private HttpMethod getHttpMethod(ClientRegistration clientRegistration) {
|
||||
if (AuthenticationMethod.FORM
|
||||
.equals(clientRegistration.getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod())) {
|
||||
.equals(clientRegistration.getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod())) {
|
||||
return HttpMethod.POST;
|
||||
}
|
||||
return HttpMethod.GET;
|
||||
|
||||
@@ -76,7 +76,7 @@ public final class DefaultOAuth2AuthorizationRequestResolver implements OAuth2Au
|
||||
Base64.getUrlEncoder().withoutPadding(), 96);
|
||||
|
||||
private static final Consumer<OAuth2AuthorizationRequest.Builder> DEFAULT_PKCE_APPLIER = OAuth2AuthorizationRequestCustomizers
|
||||
.withPkce();
|
||||
.withPkce();
|
||||
|
||||
private final ClientRegistrationRepository clientRegistrationRepository;
|
||||
|
||||
@@ -198,8 +198,9 @@ public final class DefaultOAuth2AuthorizationRequestResolver implements OAuth2Au
|
||||
|
||||
private String resolveRegistrationId(HttpServletRequest request) {
|
||||
if (this.authorizationRequestMatcher.matches(request)) {
|
||||
return this.authorizationRequestMatcher.matcher(request).getVariables()
|
||||
.get(REGISTRATION_ID_URI_VARIABLE_NAME);
|
||||
return this.authorizationRequestMatcher.matcher(request)
|
||||
.getVariables()
|
||||
.get(REGISTRATION_ID_URI_VARIABLE_NAME);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -248,8 +249,9 @@ public final class DefaultOAuth2AuthorizationRequestResolver implements OAuth2Au
|
||||
uriVariables.put("basePath", (path != null) ? path : "");
|
||||
uriVariables.put("baseUrl", uriComponents.toUriString());
|
||||
uriVariables.put("action", (action != null) ? action : "");
|
||||
return UriComponentsBuilder.fromUriString(clientRegistration.getRedirectUri()).buildAndExpand(uriVariables)
|
||||
.toUriString();
|
||||
return UriComponentsBuilder.fromUriString(clientRegistration.getRedirectUri())
|
||||
.buildAndExpand(uriVariables)
|
||||
.toUriString();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -123,9 +123,9 @@ public final class DefaultOAuth2AuthorizedClientManager implements OAuth2Authori
|
||||
this.authorizedClientProvider = DEFAULT_AUTHORIZED_CLIENT_PROVIDER;
|
||||
this.contextAttributesMapper = new DefaultContextAttributesMapper();
|
||||
this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientRepository
|
||||
.saveAuthorizedClient(authorizedClient, principal,
|
||||
(HttpServletRequest) attributes.get(HttpServletRequest.class.getName()),
|
||||
(HttpServletResponse) attributes.get(HttpServletResponse.class.getName()));
|
||||
.saveAuthorizedClient(authorizedClient, principal,
|
||||
(HttpServletRequest) attributes.get(HttpServletRequest.class.getName()),
|
||||
(HttpServletResponse) attributes.get(HttpServletResponse.class.getName()));
|
||||
this.authorizationFailureHandler = new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(
|
||||
(clientRegistrationId, principal, attributes) -> authorizedClientRepository.removeAuthorizedClient(
|
||||
clientRegistrationId, principal,
|
||||
@@ -156,7 +156,7 @@ public final class DefaultOAuth2AuthorizedClientManager implements OAuth2Authori
|
||||
}
|
||||
else {
|
||||
ClientRegistration clientRegistration = this.clientRegistrationRepository
|
||||
.findByRegistrationId(clientRegistrationId);
|
||||
.findByRegistrationId(clientRegistrationId);
|
||||
Assert.notNull(clientRegistration,
|
||||
"Could not find ClientRegistration with id '" + clientRegistrationId + "'");
|
||||
contextBuilder = OAuth2AuthorizationContext.withClientRegistration(clientRegistration);
|
||||
|
||||
@@ -134,8 +134,8 @@ public final class DefaultReactiveOAuth2AuthorizedClientManager implements React
|
||||
this.clientRegistrationRepository = clientRegistrationRepository;
|
||||
this.authorizedClientRepository = authorizedClientRepository;
|
||||
this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientRepository
|
||||
.saveAuthorizedClient(authorizedClient, principal,
|
||||
(ServerWebExchange) attributes.get(ServerWebExchange.class.getName()));
|
||||
.saveAuthorizedClient(authorizedClient, principal,
|
||||
(ServerWebExchange) attributes.get(ServerWebExchange.class.getName()));
|
||||
this.authorizationFailureHandler = new RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler(
|
||||
(clientRegistrationId, principal, attributes) -> authorizedClientRepository.removeAuthorizedClient(
|
||||
clientRegistrationId, principal,
|
||||
|
||||
@@ -42,7 +42,7 @@ public final class HttpSessionOAuth2AuthorizationRequestRepository
|
||||
implements AuthorizationRequestRepository<OAuth2AuthorizationRequest> {
|
||||
|
||||
private static final String DEFAULT_AUTHORIZATION_REQUEST_ATTR_NAME = HttpSessionOAuth2AuthorizationRequestRepository.class
|
||||
.getName() + ".AUTHORIZATION_REQUEST";
|
||||
.getName() + ".AUTHORIZATION_REQUEST";
|
||||
|
||||
private final String sessionAttributeName = DEFAULT_AUTHORIZATION_REQUEST_ATTR_NAME;
|
||||
|
||||
@@ -93,8 +93,8 @@ public final class HttpSessionOAuth2AuthorizationRequestRepository
|
||||
request.getSession().removeAttribute(this.sessionAttributeName);
|
||||
}
|
||||
else if (authorizationRequests.size() == 1) {
|
||||
request.getSession().setAttribute(this.sessionAttributeName,
|
||||
authorizationRequests.values().iterator().next());
|
||||
request.getSession()
|
||||
.setAttribute(this.sessionAttributeName, authorizationRequests.values().iterator().next());
|
||||
}
|
||||
else {
|
||||
request.getSession().setAttribute(this.sessionAttributeName, authorizationRequests);
|
||||
|
||||
@@ -39,7 +39,7 @@ import org.springframework.util.Assert;
|
||||
public final class HttpSessionOAuth2AuthorizedClientRepository implements OAuth2AuthorizedClientRepository {
|
||||
|
||||
private static final String DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME = HttpSessionOAuth2AuthorizedClientRepository.class
|
||||
.getName() + ".AUTHORIZED_CLIENTS";
|
||||
.getName() + ".AUTHORIZED_CLIENTS";
|
||||
|
||||
private final String sessionAttributeName = DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME;
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ import org.springframework.web.util.UriComponentsBuilder;
|
||||
public class OAuth2AuthorizationCodeGrantFilter extends OncePerRequestFilter {
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
private final ClientRegistrationRepository clientRegistrationRepository;
|
||||
|
||||
@@ -189,7 +189,7 @@ public class OAuth2AuthorizationCodeGrantFilter extends OncePerRequestFilter {
|
||||
return false;
|
||||
}
|
||||
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository
|
||||
.loadAuthorizationRequest(request);
|
||||
.loadAuthorizationRequest(request);
|
||||
if (authorizationRequest == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -219,7 +219,7 @@ public class OAuth2AuthorizationCodeGrantFilter extends OncePerRequestFilter {
|
||||
private void processAuthorizationResponse(HttpServletRequest request, HttpServletResponse response)
|
||||
throws IOException {
|
||||
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository
|
||||
.removeAuthorizationRequest(request, response);
|
||||
.removeAuthorizationRequest(request, response);
|
||||
String registrationId = authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID);
|
||||
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
|
||||
MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
|
||||
@@ -232,12 +232,12 @@ public class OAuth2AuthorizationCodeGrantFilter extends OncePerRequestFilter {
|
||||
OAuth2AuthorizationCodeAuthenticationToken authenticationResult;
|
||||
try {
|
||||
authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationManager
|
||||
.authenticate(authenticationRequest);
|
||||
.authenticate(authenticationRequest);
|
||||
}
|
||||
catch (OAuth2AuthorizationException ex) {
|
||||
OAuth2Error error = ex.getError();
|
||||
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri())
|
||||
.queryParam(OAuth2ParameterNames.ERROR, error.getErrorCode());
|
||||
.queryParam(OAuth2ParameterNames.ERROR, error.getErrorCode());
|
||||
if (!StringUtils.isEmpty(error.getDescription())) {
|
||||
uriBuilder.queryParam(OAuth2ParameterNames.ERROR_DESCRIPTION, error.getDescription());
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilt
|
||||
// Check to see if we need to handle ClientAuthorizationRequiredException
|
||||
Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex);
|
||||
ClientAuthorizationRequiredException authzEx = (ClientAuthorizationRequiredException) this.throwableAnalyzer
|
||||
.getFirstThrowableOfType(ClientAuthorizationRequiredException.class, causeChain);
|
||||
.getFirstThrowableOfType(ClientAuthorizationRequiredException.class, causeChain);
|
||||
if (authzEx != null) {
|
||||
try {
|
||||
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request,
|
||||
|
||||
@@ -167,7 +167,7 @@ public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProce
|
||||
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
|
||||
}
|
||||
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository
|
||||
.removeAuthorizationRequest(request, response);
|
||||
.removeAuthorizationRequest(request, response);
|
||||
if (authorizationRequest == null) {
|
||||
OAuth2Error oauth2Error = new OAuth2Error(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE);
|
||||
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
|
||||
@@ -192,9 +192,10 @@ public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProce
|
||||
new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
|
||||
authenticationRequest.setDetails(authenticationDetails);
|
||||
OAuth2LoginAuthenticationToken authenticationResult = (OAuth2LoginAuthenticationToken) this
|
||||
.getAuthenticationManager().authenticate(authenticationRequest);
|
||||
.getAuthenticationManager()
|
||||
.authenticate(authenticationRequest);
|
||||
OAuth2AuthenticationToken oauth2Authentication = this.authenticationResultConverter
|
||||
.convert(authenticationResult);
|
||||
.convert(authenticationResult);
|
||||
Assert.notNull(oauth2Authentication, "authentication result cannot be null");
|
||||
oauth2Authentication.setDetails(authenticationDetails);
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
|
||||
|
||||
@@ -74,7 +74,7 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
|
||||
"anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
private OAuth2AuthorizedClientManager authorizedClientManager;
|
||||
|
||||
@@ -111,7 +111,7 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
|
||||
public boolean supportsParameter(MethodParameter parameter) {
|
||||
Class<?> parameterType = parameter.getParameterType();
|
||||
return (OAuth2AuthorizedClient.class.isAssignableFrom(parameterType) && (AnnotatedElementUtils
|
||||
.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class) != null));
|
||||
.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class) != null));
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@@ -143,7 +143,7 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
|
||||
|
||||
private String resolveClientRegistrationId(MethodParameter parameter) {
|
||||
RegisteredOAuth2AuthorizedClient authorizedClientAnnotation = AnnotatedElementUtils
|
||||
.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class);
|
||||
.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class);
|
||||
Authentication principal = this.securityContextHolderStrategy.getContext().getAuthentication();
|
||||
if (!StringUtils.isEmpty(authorizedClientAnnotation.registrationId())) {
|
||||
return authorizedClientAnnotation.registrationId();
|
||||
@@ -207,7 +207,7 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
|
||||
.build();
|
||||
// @formatter:on
|
||||
((DefaultOAuth2AuthorizedClientManager) this.authorizedClientManager)
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
* {@link ClientRegistration#getRegistrationId()}
|
||||
*/
|
||||
private static final String CLIENT_REGISTRATION_ID_ATTR_NAME = OAuth2AuthorizedClient.class.getName()
|
||||
.concat(".CLIENT_REGISTRATION_ID");
|
||||
.concat(".CLIENT_REGISTRATION_ID");
|
||||
|
||||
/**
|
||||
* The request attribute name used to locate the
|
||||
@@ -129,7 +129,8 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
"anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
|
||||
private final Mono<Authentication> currentAuthenticationMono = ReactiveSecurityContextHolder.getContext()
|
||||
.map(SecurityContext::getAuthentication).defaultIfEmpty(ANONYMOUS_USER_TOKEN);
|
||||
.map(SecurityContext::getAuthentication)
|
||||
.defaultIfEmpty(ANONYMOUS_USER_TOKEN);
|
||||
|
||||
// @formatter:off
|
||||
private final Mono<String> clientRegistrationIdMono = this.currentAuthenticationMono
|
||||
@@ -233,8 +234,12 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
(UnAuthenticatedServerOAuth2AuthorizedClientRepository) authorizedClientRepository,
|
||||
authorizationFailureHandler);
|
||||
unauthenticatedAuthorizedClientManager
|
||||
.setAuthorizedClientProvider(ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.authorizationCode().refreshToken().clientCredentials().password().build());
|
||||
.setAuthorizedClientProvider(ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.authorizationCode()
|
||||
.refreshToken()
|
||||
.clientCredentials()
|
||||
.password()
|
||||
.build());
|
||||
return unauthenticatedAuthorizedClientManager;
|
||||
}
|
||||
DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
|
||||
@@ -388,11 +393,11 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
// @formatter:on
|
||||
if (this.authorizedClientManager instanceof UnAuthenticatedReactiveOAuth2AuthorizedClientManager) {
|
||||
((UnAuthenticatedReactiveOAuth2AuthorizedClientManager) this.authorizedClientManager)
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
}
|
||||
else {
|
||||
((DefaultReactiveOAuth2AuthorizedClientManager) this.authorizedClientManager)
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,7 +442,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
|
||||
private Mono<ClientResponse> exchangeAndHandleResponse(ClientRequest request, ExchangeFunction next) {
|
||||
return next.exchange(request)
|
||||
.transform((responseMono) -> this.clientResponseHandler.handleResponse(request, responseMono));
|
||||
.transform((responseMono) -> this.clientResponseHandler.handleResponse(request, responseMono));
|
||||
}
|
||||
|
||||
private Mono<OAuth2AuthorizedClient> authorizedClient(ClientRequest request) {
|
||||
@@ -578,7 +583,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
this.clientRegistrationRepository = clientRegistrationRepository;
|
||||
this.authorizedClientRepository = authorizedClientRepository;
|
||||
this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientRepository
|
||||
.saveAuthorizedClient(authorizedClient, principal, null);
|
||||
.saveAuthorizedClient(authorizedClient, principal, null);
|
||||
this.authorizationFailureHandler = authorizationFailureHandler;
|
||||
}
|
||||
|
||||
@@ -604,13 +609,12 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
private Mono<OAuth2AuthorizedClient> reauthorize(OAuth2AuthorizedClient authorizedClient,
|
||||
OAuth2AuthorizeRequest authorizeRequest, Authentication principal) {
|
||||
return Mono
|
||||
.just(OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(principal)
|
||||
.build())
|
||||
.flatMap((authorizationContext) -> authorize(authorizationContext, principal))
|
||||
// Default to the existing authorizedClient if the client was not
|
||||
// re-authorized
|
||||
.defaultIfEmpty((authorizeRequest.getAuthorizedClient() != null)
|
||||
? authorizeRequest.getAuthorizedClient() : authorizedClient);
|
||||
.just(OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(principal).build())
|
||||
.flatMap((authorizationContext) -> authorize(authorizationContext, principal))
|
||||
// Default to the existing authorizedClient if the client was not
|
||||
// re-authorized
|
||||
.defaultIfEmpty((authorizeRequest.getAuthorizedClient() != null)
|
||||
? authorizeRequest.getAuthorizedClient() : authorizedClient);
|
||||
}
|
||||
|
||||
private Mono<OAuth2AuthorizedClient> findAndAuthorize(String clientRegistrationId, Authentication principal) {
|
||||
@@ -776,10 +780,10 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
|
||||
Mono<String> clientRegistrationId = effectiveClientRegistrationId(request);
|
||||
return Mono
|
||||
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
|
||||
serverWebExchange, clientRegistrationId)
|
||||
.flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(),
|
||||
new ClientAuthorizationException(oauth2Error, zipped.getT3(), exception)));
|
||||
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
|
||||
serverWebExchange, clientRegistrationId)
|
||||
.flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(),
|
||||
new ClientAuthorizationException(oauth2Error, zipped.getT3(), exception)));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -794,9 +798,9 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
private Mono<Void> handleAuthorizationException(ClientRequest request, OAuth2AuthorizationException exception) {
|
||||
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
|
||||
return Mono
|
||||
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
|
||||
serverWebExchange)
|
||||
.flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(), exception));
|
||||
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
|
||||
serverWebExchange)
|
||||
.flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(), exception));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -141,7 +141,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
private static final String OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME = OAuth2AuthorizedClient.class.getName();
|
||||
|
||||
private static final String CLIENT_REGISTRATION_ID_ATTR_NAME = OAuth2AuthorizedClient.class.getName()
|
||||
.concat(".CLIENT_REGISTRATION_ID");
|
||||
.concat(".CLIENT_REGISTRATION_ID");
|
||||
|
||||
private static final String AUTHENTICATION_ATTR_NAME = Authentication.class.getName();
|
||||
|
||||
@@ -153,7 +153,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
"anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
@Deprecated
|
||||
private Duration accessTokenExpiresSkew = Duration.ofMinutes(1);
|
||||
@@ -275,7 +275,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
.build();
|
||||
// @formatter:on
|
||||
((DefaultOAuth2AuthorizedClientManager) this.authorizedClientManager)
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
}
|
||||
|
||||
private void updateClientCredentialsProvider(
|
||||
@@ -473,7 +473,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
|
||||
private Mono<ClientResponse> exchangeAndHandleResponse(ClientRequest request, ExchangeFunction next) {
|
||||
return next.exchange(request)
|
||||
.transform((responseMono) -> this.clientResponseHandler.handleResponse(request, responseMono));
|
||||
.transform((responseMono) -> this.clientResponseHandler.handleResponse(request, responseMono));
|
||||
}
|
||||
|
||||
private Mono<ClientRequest> mergeRequestAttributesIfNecessary(ClientRequest request) {
|
||||
@@ -488,8 +488,8 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
private Mono<ClientRequest> mergeRequestAttributesFromContext(ClientRequest request) {
|
||||
ClientRequest.Builder builder = ClientRequest.from(request);
|
||||
return Mono.subscriberContext()
|
||||
.map((ctx) -> builder.attributes((attrs) -> populateRequestAttributes(attrs, ctx)))
|
||||
.map(ClientRequest.Builder::build);
|
||||
.map((ctx) -> builder.attributes((attrs) -> populateRequestAttributes(attrs, ctx)))
|
||||
.map(ClientRequest.Builder::build);
|
||||
}
|
||||
|
||||
private void populateRequestAttributes(Map<String, Object> attrs, Context ctx) {
|
||||
@@ -558,14 +558,14 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
HttpServletRequest servletRequest = getRequest(attrs);
|
||||
HttpServletResponse servletResponse = getResponse(attrs);
|
||||
OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId)
|
||||
.principal(authentication);
|
||||
.principal(authentication);
|
||||
builder.attributes((attributes) -> addToAttributes(attributes, servletRequest, servletResponse));
|
||||
OAuth2AuthorizeRequest authorizeRequest = builder.build();
|
||||
// NOTE: 'authorizedClientManager.authorize()' needs to be executed on a dedicated
|
||||
// thread via subscribeOn(Schedulers.boundedElastic()) since it performs a
|
||||
// blocking I/O operation using RestTemplate internally
|
||||
return Mono.fromSupplier(() -> this.authorizedClientManager.authorize(authorizeRequest))
|
||||
.subscribeOn(Schedulers.boundedElastic());
|
||||
.subscribeOn(Schedulers.boundedElastic());
|
||||
}
|
||||
|
||||
private Mono<OAuth2AuthorizedClient> reauthorizeClient(OAuth2AuthorizedClient authorizedClient,
|
||||
@@ -581,14 +581,14 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
HttpServletRequest servletRequest = getRequest(attrs);
|
||||
HttpServletResponse servletResponse = getResponse(attrs);
|
||||
OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withAuthorizedClient(authorizedClient)
|
||||
.principal(authentication);
|
||||
.principal(authentication);
|
||||
builder.attributes((attributes) -> addToAttributes(attributes, servletRequest, servletResponse));
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = builder.build();
|
||||
// NOTE: 'authorizedClientManager.authorize()' needs to be executed on a dedicated
|
||||
// thread via subscribeOn(Schedulers.boundedElastic()) since it performs a
|
||||
// blocking I/O operation using RestTemplate internally
|
||||
return Mono.fromSupplier(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
|
||||
.subscribeOn(Schedulers.boundedElastic());
|
||||
.subscribeOn(Schedulers.boundedElastic());
|
||||
}
|
||||
|
||||
private void addToAttributes(Map<String, Object> attributes, HttpServletRequest servletRequest,
|
||||
@@ -685,10 +685,10 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
@Override
|
||||
public Mono<ClientResponse> handleResponse(ClientRequest request, Mono<ClientResponse> responseMono) {
|
||||
return responseMono.flatMap((response) -> handleResponse(request, response).thenReturn(response))
|
||||
.onErrorResume(WebClientResponseException.class,
|
||||
(e) -> handleWebClientResponseException(request, e).then(Mono.error(e)))
|
||||
.onErrorResume(OAuth2AuthorizationException.class,
|
||||
(e) -> handleAuthorizationException(request, e).then(Mono.error(e)));
|
||||
.onErrorResume(WebClientResponseException.class,
|
||||
(e) -> handleWebClientResponseException(request, e).then(Mono.error(e)))
|
||||
.onErrorResume(OAuth2AuthorizationException.class,
|
||||
(e) -> handleAuthorizationException(request, e).then(Mono.error(e)));
|
||||
}
|
||||
|
||||
private Mono<Void> handleResponse(ClientRequest request, ClientResponse response) {
|
||||
|
||||
@@ -104,7 +104,7 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
|
||||
ServerWebExchange exchange) {
|
||||
return Mono.defer(() -> {
|
||||
RegisteredOAuth2AuthorizedClient authorizedClientAnnotation = AnnotatedElementUtils
|
||||
.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class);
|
||||
.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class);
|
||||
String clientRegistrationId = StringUtils.hasLength(authorizedClientAnnotation.registrationId())
|
||||
? authorizedClientAnnotation.registrationId() : null;
|
||||
return authorizeRequest(clientRegistrationId, exchange).flatMap(this.authorizedClientManager::authorize);
|
||||
@@ -114,15 +114,16 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
|
||||
private Mono<OAuth2AuthorizeRequest> authorizeRequest(String registrationId, ServerWebExchange exchange) {
|
||||
Mono<Authentication> defaultedAuthentication = currentAuthentication();
|
||||
Mono<String> defaultedRegistrationId = Mono.justOrEmpty(registrationId)
|
||||
.switchIfEmpty(clientRegistrationId(defaultedAuthentication))
|
||||
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(
|
||||
"The clientRegistrationId could not be resolved. Please provide one")));
|
||||
.switchIfEmpty(clientRegistrationId(defaultedAuthentication))
|
||||
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(
|
||||
"The clientRegistrationId could not be resolved. Please provide one")));
|
||||
Mono<ServerWebExchange> defaultedExchange = Mono.justOrEmpty(exchange)
|
||||
.switchIfEmpty(currentServerWebExchange());
|
||||
.switchIfEmpty(currentServerWebExchange());
|
||||
return Mono.zip(defaultedRegistrationId, defaultedAuthentication, defaultedExchange)
|
||||
.map((zipped) -> OAuth2AuthorizeRequest.withClientRegistrationId(zipped.getT1())
|
||||
.principal(zipped.getT2()).attribute(ServerWebExchange.class.getName(), zipped.getT3())
|
||||
.build());
|
||||
.map((zipped) -> OAuth2AuthorizeRequest.withClientRegistrationId(zipped.getT1())
|
||||
.principal(zipped.getT2())
|
||||
.attribute(ServerWebExchange.class.getName(), zipped.getT3())
|
||||
.build());
|
||||
}
|
||||
|
||||
private Mono<Authentication> currentAuthentication() {
|
||||
@@ -135,8 +136,8 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
|
||||
|
||||
private Mono<String> clientRegistrationId(Mono<Authentication> authentication) {
|
||||
return authentication.filter((t) -> t instanceof OAuth2AuthenticationToken)
|
||||
.cast(OAuth2AuthenticationToken.class)
|
||||
.map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId);
|
||||
.cast(OAuth2AuthenticationToken.class)
|
||||
.map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId);
|
||||
}
|
||||
|
||||
private Mono<ServerWebExchange> currentServerWebExchange() {
|
||||
|
||||
@@ -86,7 +86,7 @@ public class DefaultServerOAuth2AuthorizationRequestResolver implements ServerOA
|
||||
Base64.getUrlEncoder().withoutPadding(), 96);
|
||||
|
||||
private static final Consumer<OAuth2AuthorizationRequest.Builder> DEFAULT_PKCE_APPLIER = OAuth2AuthorizationRequestCustomizers
|
||||
.withPkce();
|
||||
.withPkce();
|
||||
|
||||
private final ServerWebExchangeMatcher authorizationRequestMatcher;
|
||||
|
||||
@@ -139,7 +139,7 @@ public class DefaultServerOAuth2AuthorizationRequestResolver implements ServerOA
|
||||
@Override
|
||||
public Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange, String clientRegistrationId) {
|
||||
return findByRegistrationId(exchange, clientRegistrationId)
|
||||
.map((clientRegistration) -> authorizationRequest(exchange, clientRegistration));
|
||||
.map((clientRegistration) -> authorizationRequest(exchange, clientRegistration));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -177,7 +177,7 @@ public class OAuth2AuthorizationCodeGrantWebFilter implements WebFilter {
|
||||
private void updateDefaultAuthenticationConverter() {
|
||||
if (this.defaultAuthenticationConverter) {
|
||||
((ServerOAuth2AuthorizationCodeAuthenticationTokenConverter) this.authenticationConverter)
|
||||
.setAuthorizationRequestRepository(this.authorizationRequestRepository);
|
||||
.setAuthorizationRequestRepository(this.authorizationRequestRepository);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,7 +197,7 @@ public class OAuth2AuthorizationCodeGrantWebFilter implements WebFilter {
|
||||
|
||||
private void updateDefaultAuthenticationSuccessHandler() {
|
||||
((RedirectServerAuthenticationSuccessHandler) this.authenticationSuccessHandler)
|
||||
.setRequestCache(this.requestCache);
|
||||
.setRequestCache(this.requestCache);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -221,13 +221,13 @@ public class OAuth2AuthorizationCodeGrantWebFilter implements WebFilter {
|
||||
private Mono<Void> authenticate(ServerWebExchange exchange, WebFilterChain chain, Authentication token) {
|
||||
WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain);
|
||||
return this.authenticationManager.authenticate(token)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(ex) -> new OAuth2AuthenticationException(ex.getError(), ex.getError().toString()))
|
||||
.switchIfEmpty(Mono.defer(
|
||||
() -> Mono.error(new IllegalStateException("No provider found for " + token.getClass()))))
|
||||
.flatMap((authentication) -> onAuthenticationSuccess(authentication, webFilterExchange))
|
||||
.onErrorResume(AuthenticationException.class,
|
||||
(e) -> this.authenticationFailureHandler.onAuthenticationFailure(webFilterExchange, e));
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
(ex) -> new OAuth2AuthenticationException(ex.getError(), ex.getError().toString()))
|
||||
.switchIfEmpty(Mono
|
||||
.defer(() -> Mono.error(new IllegalStateException("No provider found for " + token.getClass()))))
|
||||
.flatMap((authentication) -> onAuthenticationSuccess(authentication, webFilterExchange))
|
||||
.onErrorResume(AuthenticationException.class,
|
||||
(e) -> this.authenticationFailureHandler.onAuthenticationFailure(webFilterExchange, e));
|
||||
}
|
||||
|
||||
private Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) {
|
||||
|
||||
@@ -153,7 +153,7 @@ public class OAuth2AuthorizationRequestRedirectWebFilter implements WebFilter {
|
||||
Mono<Void> saveAuthorizationRequest = Mono.empty();
|
||||
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationRequest.getGrantType())) {
|
||||
saveAuthorizationRequest = this.authorizationRequestRepository
|
||||
.saveAuthorizationRequest(authorizationRequest, exchange);
|
||||
.saveAuthorizationRequest(authorizationRequest, exchange);
|
||||
}
|
||||
// @formatter:off
|
||||
URI redirectUri = UriComponentsBuilder.fromUriString(authorizationRequest.getAuthorizationRequestUri())
|
||||
@@ -161,7 +161,7 @@ public class OAuth2AuthorizationRequestRedirectWebFilter implements WebFilter {
|
||||
.toUri();
|
||||
// @formatter:on
|
||||
return saveAuthorizationRequest
|
||||
.then(this.authorizationRedirectStrategy.sendRedirect(exchange, redirectUri));
|
||||
.then(this.authorizationRedirectStrategy.sendRedirect(exchange, redirectUri));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ public final class WebSessionOAuth2ServerAuthorizationRequestRepository
|
||||
implements ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> {
|
||||
|
||||
private static final String DEFAULT_AUTHORIZATION_REQUEST_ATTR_NAME = WebSessionOAuth2ServerAuthorizationRequestRepository.class
|
||||
.getName() + ".AUTHORIZATION_REQUEST";
|
||||
.getName() + ".AUTHORIZATION_REQUEST";
|
||||
|
||||
private final String sessionAttributeName = DEFAULT_AUTHORIZATION_REQUEST_ATTR_NAME;
|
||||
|
||||
@@ -140,7 +140,7 @@ public final class WebSessionOAuth2ServerAuthorizationRequestRepository
|
||||
else if (sessionAttributeValue instanceof Map) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, OAuth2AuthorizationRequest> authorizationRequests = (Map<String, OAuth2AuthorizationRequest>) sessionAttrs
|
||||
.get(this.sessionAttributeName);
|
||||
.get(this.sessionAttributeName);
|
||||
return authorizationRequests;
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -40,7 +40,7 @@ import org.springframework.web.server.WebSession;
|
||||
public final class WebSessionServerOAuth2AuthorizedClientRepository implements ServerOAuth2AuthorizedClientRepository {
|
||||
|
||||
private static final String DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME = WebSessionServerOAuth2AuthorizedClientRepository.class
|
||||
.getName() + ".AUTHORIZED_CLIENTS";
|
||||
.getName() + ".AUTHORIZED_CLIENTS";
|
||||
|
||||
private final String sessionAttributeName = DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME;
|
||||
|
||||
|
||||
@@ -87,7 +87,7 @@ public class AuthorizationCodeOAuth2AuthorizedClientProviderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
|
||||
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext));
|
||||
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ public class AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
|
||||
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block());
|
||||
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -87,12 +87,12 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
|
||||
public void onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Authentication principal,
|
||||
Map<String, Object> attributes) {
|
||||
AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.this.authorizedClientService
|
||||
.saveAuthorizedClient(authorizedClient, principal);
|
||||
.saveAuthorizedClient(authorizedClient, principal);
|
||||
}
|
||||
});
|
||||
this.authorizationFailureHandler = spy(new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(
|
||||
(clientRegistrationId, principal, attributes) -> this.authorizedClientService
|
||||
.removeAuthorizedClient(clientRegistrationId, principal.getName())));
|
||||
.removeAuthorizedClient(clientRegistrationId, principal.getName())));
|
||||
this.authorizedClientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(
|
||||
this.clientRegistrationRepository, this.authorizedClientService);
|
||||
this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider);
|
||||
@@ -186,10 +186,11 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenNotAuthorizedAndUnsupportedProviderThenNotAuthorized() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(this.clientRegistration);
|
||||
.willReturn(this.clientRegistration);
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
|
||||
.build();
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
|
||||
@@ -206,9 +207,9 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(this.clientRegistration);
|
||||
.willReturn(this.clientRegistration);
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(this.authorizedClient);
|
||||
.willReturn(this.authorizedClient);
|
||||
// @formatter:off
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
|
||||
@@ -232,13 +233,14 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(this.clientRegistration);
|
||||
.willReturn(this.clientRegistration);
|
||||
given(this.authorizedClientService.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
|
||||
eq(this.principal.getName()))).willReturn(this.authorizedClient);
|
||||
eq(this.principal.getName())))
|
||||
.willReturn(this.authorizedClient);
|
||||
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
|
||||
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(reauthorizedClient);
|
||||
.willReturn(reauthorizedClient);
|
||||
// @formatter:off
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
|
||||
@@ -262,7 +264,8 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void reauthorizeWhenUnsupportedProviderThenNotReauthorized() {
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).build();
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
|
||||
@@ -281,9 +284,10 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
|
||||
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
|
||||
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(reauthorizedClient);
|
||||
.willReturn(reauthorizedClient);
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).build();
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
|
||||
@@ -303,12 +307,14 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
|
||||
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
|
||||
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(reauthorizedClient);
|
||||
.willReturn(reauthorizedClient);
|
||||
// Override the mock with the default
|
||||
this.authorizedClientManager.setContextAttributesMapper(
|
||||
new AuthorizedClientServiceOAuth2AuthorizedClientManager.DefaultContextAttributesMapper());
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).attribute(OAuth2ParameterNames.SCOPE, "read write").build();
|
||||
.principal(this.principal)
|
||||
.attribute(OAuth2ParameterNames.SCOPE, "read write")
|
||||
.build();
|
||||
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
|
||||
@@ -316,9 +322,9 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
|
||||
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
|
||||
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
|
||||
assertThat(authorizationContext.getAttributes())
|
||||
.containsKey(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
|
||||
.containsKey(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
|
||||
String[] requestScopeAttribute = authorizationContext
|
||||
.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
|
||||
.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
|
||||
assertThat(requestScopeAttribute).contains("read", "write");
|
||||
assertThat(authorizedClient).isSameAs(reauthorizedClient);
|
||||
verify(this.authorizationSuccessHandler).onAuthorizationSuccess(eq(reauthorizedClient), eq(this.principal),
|
||||
@@ -332,12 +338,13 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
|
||||
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null),
|
||||
this.clientRegistration.getRegistrationId());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willThrow(authorizationException);
|
||||
.willThrow(authorizationException);
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).build();
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
assertThatExceptionOfType(ClientAuthorizationException.class)
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
|
||||
.isEqualTo(authorizationException);
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
|
||||
.isEqualTo(authorizationException);
|
||||
verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
|
||||
any());
|
||||
verify(this.authorizedClientService).removeAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
|
||||
@@ -349,7 +356,7 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
|
||||
ClientAuthorizationException authorizationException = new ClientAuthorizationException(
|
||||
new OAuth2Error("non-matching-error-code", null, null), this.clientRegistration.getRegistrationId());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willThrow(authorizationException);
|
||||
.willThrow(authorizationException);
|
||||
// @formatter:off
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest
|
||||
.withAuthorizedClient(this.authorizedClient)
|
||||
|
||||
@@ -85,10 +85,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
this.authorizedClientService = mock(ReactiveOAuth2AuthorizedClientService.class);
|
||||
this.saveAuthorizedClientProbe = PublisherProbe.empty();
|
||||
given(this.authorizedClientService.saveAuthorizedClient(any(), any()))
|
||||
.willReturn(this.saveAuthorizedClientProbe.mono());
|
||||
.willReturn(this.saveAuthorizedClientProbe.mono());
|
||||
this.removeAuthorizedClientProbe = PublisherProbe.empty();
|
||||
given(this.authorizedClientService.removeAuthorizedClient(any(), any()))
|
||||
.willReturn(this.removeAuthorizedClientProbe.mono());
|
||||
.willReturn(this.removeAuthorizedClientProbe.mono());
|
||||
this.authorizedClientProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
|
||||
this.contextAttributesMapper = mock(Function.class);
|
||||
given(this.contextAttributesMapper.apply(any())).willReturn(Mono.empty());
|
||||
@@ -106,68 +106,69 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(null,
|
||||
this.authorizedClientService))
|
||||
.withMessage("clientRegistrationRepository cannot be null");
|
||||
.isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(null,
|
||||
this.authorizedClientService))
|
||||
.withMessage("clientRegistrationRepository cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
|
||||
this.clientRegistrationRepository, null))
|
||||
.withMessage("authorizedClientService cannot be null");
|
||||
.isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
|
||||
this.clientRegistrationRepository, null))
|
||||
.withMessage("authorizedClientService cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null))
|
||||
.withMessage("authorizedClientProvider cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null))
|
||||
.withMessage("authorizedClientProvider cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null))
|
||||
.withMessage("contextAttributesMapper cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null))
|
||||
.withMessage("contextAttributesMapper cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null))
|
||||
.withMessage("authorizationSuccessHandler cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null))
|
||||
.withMessage("authorizationSuccessHandler cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null))
|
||||
.withMessage("authorizationFailureHandler cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null))
|
||||
.withMessage("authorizationFailureHandler cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null))
|
||||
.withMessage("authorizeRequest cannot be null");
|
||||
.withMessage("authorizeRequest cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() {
|
||||
String clientRegistrationId = "invalid-registration-id";
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId)
|
||||
.principal(this.principal).build();
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(Mono.empty());
|
||||
StepVerifier.create(this.authorizedClientManager.authorize(authorizeRequest))
|
||||
.verifyError(IllegalArgumentException.class);
|
||||
.verifyError(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void authorizeWhenNotAuthorizedAndUnsupportedProviderThenNotAuthorized() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
|
||||
given(this.authorizedClientProvider.authorize(any())).willReturn(Mono.empty());
|
||||
// @formatter:off
|
||||
@@ -192,13 +193,14 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(Mono.just(this.authorizedClient));
|
||||
.willReturn(Mono.just(this.authorizedClient));
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
|
||||
.build();
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
|
||||
StepVerifier.create(authorizedClient).expectNext(this.authorizedClient).verifyComplete();
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
@@ -216,10 +218,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenNotAuthorizedAndSupportedProviderAndCustomSuccessHandlerThenInvokeCustomSuccessHandler() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(Mono.just(this.authorizedClient));
|
||||
.willReturn(Mono.just(this.authorizedClient));
|
||||
// @formatter:off
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
|
||||
@@ -227,8 +229,8 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
PublisherProbe<Void> authorizationSuccessHandlerProbe = PublisherProbe.empty();
|
||||
this.authorizedClientManager.setAuthorizationSuccessHandler(
|
||||
(client, principal, attributes) -> authorizationSuccessHandlerProbe.mono());
|
||||
this.authorizedClientManager
|
||||
.setAuthorizationSuccessHandler((client, principal, attributes) -> authorizationSuccessHandlerProbe.mono());
|
||||
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
|
||||
StepVerifier.create(authorizedClient).expectNext(this.authorizedClient).verifyComplete();
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
@@ -245,7 +247,7 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenInvalidTokenThenRemoveAuthorizedClient() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
|
||||
// @formatter:off
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
@@ -257,10 +259,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, null, null),
|
||||
this.clientRegistration.getRegistrationId());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(Mono.error(exception));
|
||||
.willReturn(Mono.error(exception));
|
||||
assertThatExceptionOfType(ClientAuthorizationException.class)
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
|
||||
.isEqualTo(exception);
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
|
||||
.isEqualTo(exception);
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
|
||||
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
|
||||
@@ -276,7 +278,7 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenInvalidGrantThenRemoveAuthorizedClient() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
|
||||
// @formatter:off
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
@@ -288,10 +290,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null),
|
||||
this.clientRegistration.getRegistrationId());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(Mono.error(exception));
|
||||
.willReturn(Mono.error(exception));
|
||||
assertThatExceptionOfType(ClientAuthorizationException.class)
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
|
||||
.isEqualTo(exception);
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
|
||||
.isEqualTo(exception);
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
|
||||
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
|
||||
@@ -307,7 +309,7 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenServerErrorThenDoNotRemoveAuthorizedClient() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
|
||||
// @formatter:off
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
@@ -319,10 +321,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, null, null),
|
||||
this.clientRegistration.getRegistrationId());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(Mono.error(exception));
|
||||
.willReturn(Mono.error(exception));
|
||||
assertThatExceptionOfType(ClientAuthorizationException.class)
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
|
||||
.isEqualTo(exception);
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
|
||||
.isEqualTo(exception);
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
|
||||
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
|
||||
@@ -336,7 +338,7 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedClient() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
|
||||
// @formatter:off
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
@@ -347,10 +349,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(
|
||||
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(Mono.error(exception));
|
||||
.willReturn(Mono.error(exception));
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
|
||||
.isEqualTo(exception);
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
|
||||
.isEqualTo(exception);
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
|
||||
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
|
||||
@@ -364,7 +366,7 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenOAuth2AuthorizationExceptionAndCustomFailureHandlerThenInvokeCustomFailureHandler() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
|
||||
// @formatter:off
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
@@ -375,13 +377,13 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(
|
||||
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(Mono.error(exception));
|
||||
.willReturn(Mono.error(exception));
|
||||
PublisherProbe<Void> authorizationFailureHandlerProbe = PublisherProbe.empty();
|
||||
this.authorizedClientManager.setAuthorizationFailureHandler(
|
||||
(client, principal, attributes) -> authorizationFailureHandlerProbe.mono());
|
||||
this.authorizedClientManager
|
||||
.setAuthorizationFailureHandler((client, principal, attributes) -> authorizationFailureHandlerProbe.mono());
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
|
||||
.isEqualTo(exception);
|
||||
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
|
||||
.isEqualTo(exception);
|
||||
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
|
||||
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
|
||||
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
|
||||
@@ -397,16 +399,18 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
given(this.authorizedClientService.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
|
||||
eq(this.principal.getName()))).willReturn(Mono.just(this.authorizedClient));
|
||||
eq(this.principal.getName())))
|
||||
.willReturn(Mono.just(this.authorizedClient));
|
||||
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
|
||||
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(Mono.just(reauthorizedClient));
|
||||
.willReturn(Mono.just(reauthorizedClient));
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
|
||||
.build();
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
|
||||
// @formatter:off
|
||||
StepVerifier.create(authorizedClient)
|
||||
@@ -451,7 +455,7 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
|
||||
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(Mono.just(reauthorizedClient));
|
||||
.willReturn(Mono.just(reauthorizedClient));
|
||||
// @formatter:off
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal)
|
||||
@@ -476,9 +480,11 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
|
||||
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
|
||||
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
|
||||
.willReturn(Mono.just(reauthorizedClient));
|
||||
.willReturn(Mono.just(reauthorizedClient));
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).attribute(OAuth2ParameterNames.SCOPE, "read write").build();
|
||||
.principal(this.principal)
|
||||
.attribute(OAuth2ParameterNames.SCOPE, "read write")
|
||||
.build();
|
||||
this.authorizedClientManager.setContextAttributesMapper(
|
||||
new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.DefaultContextAttributesMapper());
|
||||
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
|
||||
@@ -496,9 +502,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
|
||||
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
|
||||
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
|
||||
assertThat(authorizationContext.getAttributes())
|
||||
.containsKey(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
|
||||
.containsKey(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
|
||||
String[] requestScopeAttribute = authorizationContext
|
||||
.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
|
||||
.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
|
||||
assertThat(requestScopeAttribute).contains("read", "write");
|
||||
}
|
||||
|
||||
|
||||
@@ -194,7 +194,7 @@ public class ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext)
|
||||
.block();
|
||||
.block();
|
||||
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
|
||||
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
|
||||
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
|
||||
|
||||
@@ -42,9 +42,9 @@ public class DelegatingOAuth2AuthorizedClientProviderTests {
|
||||
@Test
|
||||
public void constructorWhenProvidersIsEmptyThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(new OAuth2AuthorizedClientProvider[0]));
|
||||
.isThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(new OAuth2AuthorizedClientProvider[0]));
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(Collections.emptyList()));
|
||||
.isThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(Collections.emptyList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -52,7 +52,7 @@ public class DelegatingOAuth2AuthorizedClientProviderTests {
|
||||
DelegatingOAuth2AuthorizedClientProvider delegate = new DelegatingOAuth2AuthorizedClientProvider(
|
||||
mock(OAuth2AuthorizedClientProvider.class));
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> delegate.authorize(null))
|
||||
.withMessage("context cannot be null");
|
||||
.withMessage("context cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -67,7 +67,8 @@ public class DelegatingOAuth2AuthorizedClientProviderTests {
|
||||
mock(OAuth2AuthorizedClientProvider.class), mock(OAuth2AuthorizedClientProvider.class),
|
||||
authorizedClientProvider);
|
||||
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
|
||||
.principal(principal).build();
|
||||
.principal(principal)
|
||||
.build();
|
||||
OAuth2AuthorizedClient reauthorizedClient = delegate.authorize(context);
|
||||
assertThat(reauthorizedClient).isSameAs(authorizedClient);
|
||||
}
|
||||
@@ -76,7 +77,8 @@ public class DelegatingOAuth2AuthorizedClientProviderTests {
|
||||
public void authorizeWhenProviderCantAuthorizeThenReturnNull() {
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
|
||||
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
|
||||
.principal(new TestingAuthenticationToken("principal", "password")).build();
|
||||
.principal(new TestingAuthenticationToken("principal", "password"))
|
||||
.build();
|
||||
DelegatingOAuth2AuthorizedClientProvider delegate = new DelegatingOAuth2AuthorizedClientProvider(
|
||||
mock(OAuth2AuthorizedClientProvider.class), mock(OAuth2AuthorizedClientProvider.class));
|
||||
assertThat(delegate.authorize(context)).isNull();
|
||||
|
||||
@@ -45,7 +45,7 @@ public class DelegatingReactiveOAuth2AuthorizedClientProviderTests {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(
|
||||
new ReactiveOAuth2AuthorizedClientProvider[0]));
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(Collections.emptyList()));
|
||||
.isThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(Collections.emptyList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -53,7 +53,7 @@ public class DelegatingReactiveOAuth2AuthorizedClientProviderTests {
|
||||
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(
|
||||
mock(ReactiveOAuth2AuthorizedClientProvider.class));
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> delegate.authorize(null).block())
|
||||
.withMessage("context cannot be null");
|
||||
.withMessage("context cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -74,7 +74,8 @@ public class DelegatingReactiveOAuth2AuthorizedClientProviderTests {
|
||||
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(
|
||||
authorizedClientProvider1, authorizedClientProvider2, authorizedClientProvider3);
|
||||
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
|
||||
.principal(principal).build();
|
||||
.principal(principal)
|
||||
.build();
|
||||
OAuth2AuthorizedClient reauthorizedClient = delegate.authorize(context).block();
|
||||
assertThat(reauthorizedClient).isSameAs(authorizedClient);
|
||||
}
|
||||
@@ -83,7 +84,8 @@ public class DelegatingReactiveOAuth2AuthorizedClientProviderTests {
|
||||
public void authorizeWhenProviderCantAuthorizeThenReturnNull() {
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
|
||||
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
|
||||
.principal(new TestingAuthenticationToken("principal", "password")).build();
|
||||
.principal(new TestingAuthenticationToken("principal", "password"))
|
||||
.build();
|
||||
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(
|
||||
ReactiveOAuth2AuthorizedClientProvider.class);
|
||||
given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
|
||||
|
||||
@@ -51,8 +51,10 @@ public class InMemoryOAuth2AuthorizedClientServiceTests {
|
||||
|
||||
private ClientRegistration registration2 = TestClientRegistrations.clientRegistration2().build();
|
||||
|
||||
private ClientRegistration registration3 = TestClientRegistrations.clientRegistration().clientId("client-3")
|
||||
.registrationId("registration-3").build();
|
||||
private ClientRegistration registration3 = TestClientRegistrations.clientRegistration()
|
||||
.clientId("client-3")
|
||||
.registrationId("registration-3")
|
||||
.build();
|
||||
|
||||
private ClientRegistrationRepository clientRegistrationRepository = new InMemoryClientRegistrationRepository(
|
||||
this.registration1, this.registration2, this.registration3);
|
||||
@@ -90,7 +92,7 @@ public class InMemoryOAuth2AuthorizedClientServiceTests {
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, this.principalName1));
|
||||
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, this.principalName1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -102,14 +104,14 @@ public class InMemoryOAuth2AuthorizedClientServiceTests {
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenClientRegistrationNotFoundThenReturnNull() {
|
||||
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient("registration-not-found", this.principalName1);
|
||||
.loadAuthorizedClient("registration-not-found", this.principalName1);
|
||||
assertThat(authorizedClient).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenClientRegistrationFoundButNotAssociatedToPrincipalThenReturnNull() {
|
||||
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.registration1.getRegistrationId(), "principal-not-found");
|
||||
.loadAuthorizedClient(this.registration1.getRegistrationId(), "principal-not-found");
|
||||
assertThat(authorizedClient).isNull();
|
||||
}
|
||||
|
||||
@@ -121,14 +123,14 @@ public class InMemoryOAuth2AuthorizedClientServiceTests {
|
||||
mock(OAuth2AccessToken.class));
|
||||
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
|
||||
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.registration1.getRegistrationId(), this.principalName1);
|
||||
.loadAuthorizedClient(this.registration1.getRegistrationId(), this.principalName1);
|
||||
assertThat(loadedAuthorizedClient).isEqualTo(authorizedClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, mock(Authentication.class)));
|
||||
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, mock(Authentication.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -145,20 +147,20 @@ public class InMemoryOAuth2AuthorizedClientServiceTests {
|
||||
mock(OAuth2AccessToken.class));
|
||||
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
|
||||
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.registration3.getRegistrationId(), this.principalName2);
|
||||
.loadAuthorizedClient(this.registration3.getRegistrationId(), this.principalName2);
|
||||
assertThat(loadedAuthorizedClient).isEqualTo(authorizedClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, this.principalName2));
|
||||
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, this.principalName2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removeAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientService
|
||||
.removeAuthorizedClient(this.registration3.getRegistrationId(), null));
|
||||
.removeAuthorizedClient(this.registration3.getRegistrationId(), null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -169,12 +171,12 @@ public class InMemoryOAuth2AuthorizedClientServiceTests {
|
||||
mock(OAuth2AccessToken.class));
|
||||
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
|
||||
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
|
||||
.loadAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
|
||||
assertThat(loadedAuthorizedClient).isNotNull();
|
||||
this.authorizedClientService.removeAuthorizedClient(this.registration2.getRegistrationId(),
|
||||
this.principalName2);
|
||||
loadedAuthorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
|
||||
.loadAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
|
||||
assertThat(loadedAuthorizedClient).isNull();
|
||||
}
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
|
||||
public void constructorNullClientRegistrationRepositoryThenThrowsIllegalArgumentException() {
|
||||
this.clientRegistrationRepository = null;
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new InMemoryReactiveOAuth2AuthorizedClientService(this.clientRegistrationRepository));
|
||||
.isThrownBy(() -> new InMemoryReactiveOAuth2AuthorizedClientService(this.clientRegistrationRepository));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -127,25 +127,25 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenClientRegistrationIdNotFoundThenEmpty() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId))
|
||||
.willReturn(Mono.empty());
|
||||
StepVerifier.create(
|
||||
this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
|
||||
.verifyComplete();
|
||||
.willReturn(Mono.empty());
|
||||
StepVerifier
|
||||
.create(this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenClientRegistrationFoundAndNotAuthorizedClientThenEmpty() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
StepVerifier.create(
|
||||
this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
|
||||
.verifyComplete();
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
StepVerifier
|
||||
.create(this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenClientRegistrationFoundThenFound() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
|
||||
this.principalName, this.accessToken);
|
||||
// @formatter:off
|
||||
@@ -217,7 +217,7 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
|
||||
@Test
|
||||
public void removeAuthorizedClientWhenClientIdThenNoException() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId))
|
||||
.willReturn(Mono.empty());
|
||||
.willReturn(Mono.empty());
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
|
||||
this.principalName, this.accessToken);
|
||||
// @formatter:off
|
||||
@@ -233,7 +233,7 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
|
||||
@Test
|
||||
public void removeAuthorizedClientWhenClientRegistrationFoundRemovedThenNotFound() {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
|
||||
this.principalName, this.accessToken);
|
||||
// @formatter:off
|
||||
|
||||
@@ -114,8 +114,8 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
@Test
|
||||
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new JdbcOAuth2AuthorizedClientService(this.jdbcOperations, null))
|
||||
.withMessage("clientRegistrationRepository cannot be null");
|
||||
.isThrownBy(() -> new JdbcOAuth2AuthorizedClientService(this.jdbcOperations, null))
|
||||
.withMessage("clientRegistrationRepository cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -158,7 +158,7 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenDoesNotExistThenReturnNull() {
|
||||
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient("registration-not-found", "principalName");
|
||||
.loadAuthorizedClient("registration-not-found", "principalName");
|
||||
assertThat(authorizedClient).isNull();
|
||||
}
|
||||
|
||||
@@ -168,21 +168,21 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
|
||||
this.authorizedClientService.saveAuthorizedClient(expected, principal);
|
||||
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
|
||||
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(expected.getAccessToken().getTokenType());
|
||||
.isEqualTo(expected.getAccessToken().getTokenType());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(expected.getAccessToken().getTokenValue());
|
||||
.isEqualTo(expected.getAccessToken().getTokenValue());
|
||||
assertThat(authorizedClient.getAccessToken().getIssuedAt()).isCloseTo(expected.getAccessToken().getIssuedAt(),
|
||||
within(1, ChronoUnit.MILLIS));
|
||||
assertThat(authorizedClient.getAccessToken().getExpiresAt()).isCloseTo(expected.getAccessToken().getExpiresAt(),
|
||||
within(1, ChronoUnit.MILLIS));
|
||||
assertThat(authorizedClient.getAccessToken().getScopes()).isEqualTo(expected.getAccessToken().getScopes());
|
||||
assertThat(authorizedClient.getRefreshToken().getTokenValue())
|
||||
.isEqualTo(expected.getRefreshToken().getTokenValue());
|
||||
.isEqualTo(expected.getRefreshToken().getTokenValue());
|
||||
assertThat(authorizedClient.getRefreshToken().getIssuedAt()).isCloseTo(expected.getRefreshToken().getIssuedAt(),
|
||||
within(1, ChronoUnit.MILLIS));
|
||||
}
|
||||
@@ -194,18 +194,18 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
|
||||
this.authorizedClientService.saveAuthorizedClient(expected, principal);
|
||||
assertThatExceptionOfType(DataRetrievalFailureException.class)
|
||||
.isThrownBy(() -> this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName()))
|
||||
.withMessage("The ClientRegistration with id '" + this.clientRegistration.getRegistrationId()
|
||||
+ "' exists in the data source, however, it was not found in the ClientRegistrationRepository.");
|
||||
.isThrownBy(() -> this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName()))
|
||||
.withMessage("The ClientRegistration with id '" + this.clientRegistration.getRegistrationId()
|
||||
+ "' exists in the data source, however, it was not found in the ClientRegistrationRepository.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
|
||||
Authentication principal = createPrincipal();
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, principal))
|
||||
.withMessage("authorizedClient cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, principal))
|
||||
.withMessage("authorizedClient cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -213,8 +213,8 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
Authentication principal = createPrincipal();
|
||||
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, null))
|
||||
.withMessage("principal cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, null))
|
||||
.withMessage("principal cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -223,21 +223,21 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
|
||||
this.authorizedClientService.saveAuthorizedClient(expected, principal);
|
||||
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
|
||||
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(expected.getAccessToken().getTokenType());
|
||||
.isEqualTo(expected.getAccessToken().getTokenType());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(expected.getAccessToken().getTokenValue());
|
||||
.isEqualTo(expected.getAccessToken().getTokenValue());
|
||||
assertThat(authorizedClient.getAccessToken().getIssuedAt()).isCloseTo(expected.getAccessToken().getIssuedAt(),
|
||||
within(1, ChronoUnit.MILLIS));
|
||||
assertThat(authorizedClient.getAccessToken().getExpiresAt()).isCloseTo(expected.getAccessToken().getExpiresAt(),
|
||||
within(1, ChronoUnit.MILLIS));
|
||||
assertThat(authorizedClient.getAccessToken().getScopes()).isEqualTo(expected.getAccessToken().getScopes());
|
||||
assertThat(authorizedClient.getRefreshToken().getTokenValue())
|
||||
.isEqualTo(expected.getRefreshToken().getTokenValue());
|
||||
.isEqualTo(expected.getRefreshToken().getTokenValue());
|
||||
assertThat(authorizedClient.getRefreshToken().getIssuedAt()).isCloseTo(expected.getRefreshToken().getIssuedAt(),
|
||||
within(1, ChronoUnit.MILLIS));
|
||||
// Test save/load of NOT NULL attributes only
|
||||
@@ -245,14 +245,14 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
expected = createAuthorizedClient(principal, this.clientRegistration, true);
|
||||
this.authorizedClientService.saveAuthorizedClient(expected, principal);
|
||||
authorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
|
||||
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(expected.getAccessToken().getTokenType());
|
||||
.isEqualTo(expected.getAccessToken().getTokenType());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(expected.getAccessToken().getTokenValue());
|
||||
.isEqualTo(expected.getAccessToken().getTokenValue());
|
||||
assertThat(authorizedClient.getAccessToken().getIssuedAt()).isCloseTo(expected.getAccessToken().getIssuedAt(),
|
||||
within(1, ChronoUnit.MILLIS));
|
||||
assertThat(authorizedClient.getAccessToken().getExpiresAt()).isCloseTo(expected.getAccessToken().getExpiresAt(),
|
||||
@@ -272,21 +272,21 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
this.authorizedClientService.saveAuthorizedClient(updatedClient, principal);
|
||||
// Then the saved client is updated
|
||||
OAuth2AuthorizedClient savedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
assertThat(savedClient).isNotNull();
|
||||
assertThat(savedClient.getClientRegistration()).isEqualTo(updatedClient.getClientRegistration());
|
||||
assertThat(savedClient.getPrincipalName()).isEqualTo(updatedClient.getPrincipalName());
|
||||
assertThat(savedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(updatedClient.getAccessToken().getTokenType());
|
||||
.isEqualTo(updatedClient.getAccessToken().getTokenType());
|
||||
assertThat(savedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(updatedClient.getAccessToken().getTokenValue());
|
||||
.isEqualTo(updatedClient.getAccessToken().getTokenValue());
|
||||
assertThat(savedClient.getAccessToken().getIssuedAt()).isCloseTo(updatedClient.getAccessToken().getIssuedAt(),
|
||||
within(1, ChronoUnit.MILLIS));
|
||||
assertThat(savedClient.getAccessToken().getExpiresAt()).isCloseTo(updatedClient.getAccessToken().getExpiresAt(),
|
||||
within(1, ChronoUnit.MILLIS));
|
||||
assertThat(savedClient.getAccessToken().getScopes()).isEqualTo(updatedClient.getAccessToken().getScopes());
|
||||
assertThat(savedClient.getRefreshToken().getTokenValue())
|
||||
.isEqualTo(updatedClient.getRefreshToken().getTokenValue());
|
||||
.isEqualTo(updatedClient.getRefreshToken().getTokenValue());
|
||||
assertThat(savedClient.getRefreshToken().getIssuedAt()).isCloseTo(updatedClient.getRefreshToken().getIssuedAt(),
|
||||
within(1, ChronoUnit.MILLIS));
|
||||
}
|
||||
@@ -312,16 +312,16 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
@Test
|
||||
public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, "principalName"))
|
||||
.withMessage("clientRegistrationId cannot be empty");
|
||||
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, "principalName"))
|
||||
.withMessage("clientRegistrationId cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removeAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientService
|
||||
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
|
||||
.withMessage("principalName cannot be empty");
|
||||
.isThrownBy(() -> this.authorizedClientService
|
||||
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
|
||||
.withMessage("principalName cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -330,12 +330,12 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
|
||||
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal);
|
||||
authorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
this.authorizedClientService.removeAuthorizedClient(this.clientRegistration.getRegistrationId(),
|
||||
principal.getName());
|
||||
authorizedClient = this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
assertThat(authorizedClient).isNull();
|
||||
}
|
||||
|
||||
@@ -347,12 +347,12 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
|
||||
customAuthorizedClientService.saveAuthorizedClient(authorizedClient, principal);
|
||||
authorizedClient = customAuthorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
customAuthorizedClientService.removeAuthorizedClient(this.clientRegistration.getRegistrationId(),
|
||||
principal.getName());
|
||||
authorizedClient = customAuthorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
|
||||
assertThat(authorizedClient).isNull();
|
||||
}
|
||||
|
||||
@@ -437,7 +437,7 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
@Override
|
||||
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
|
||||
List<SqlParameterValue> parameters = this.authorizedClientParametersMapper
|
||||
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal));
|
||||
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal));
|
||||
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray());
|
||||
this.jdbcOperations.update(SAVE_AUTHORIZED_CLIENT_SQL, pss);
|
||||
}
|
||||
@@ -464,7 +464,7 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
|
||||
public OAuth2AuthorizedClient mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
String clientRegistrationId = rs.getString("clientRegistrationId");
|
||||
ClientRegistration clientRegistration = this.clientRegistrationRepository
|
||||
.findByRegistrationId(clientRegistrationId);
|
||||
.findByRegistrationId(clientRegistrationId);
|
||||
if (clientRegistration == null) {
|
||||
throw new DataRetrievalFailureException(
|
||||
"The ClientRegistration with id '" + clientRegistrationId + "' exists in the data source, "
|
||||
|
||||
@@ -85,15 +85,15 @@ public class JwtBearerOAuth2AuthorizedClientProviderTests {
|
||||
@Test
|
||||
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
|
||||
.withMessage("accessTokenResponseClient cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
|
||||
.withMessage("accessTokenResponseClient cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setJwtAssertionResolverWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setJwtAssertionResolver(null))
|
||||
.withMessage("jwtAssertionResolver cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setJwtAssertionResolver(null))
|
||||
.withMessage("jwtAssertionResolver cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -90,15 +90,15 @@ public class JwtBearerReactiveOAuth2AuthorizedClientProviderTests {
|
||||
@Test
|
||||
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
|
||||
.withMessage("accessTokenResponseClient cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
|
||||
.withMessage("accessTokenResponseClient cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setJwtAssertionResolverWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setJwtAssertionResolver(null))
|
||||
.withMessage("jwtAssertionResolver cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setJwtAssertionResolver(null))
|
||||
.withMessage("jwtAssertionResolver cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -223,7 +223,7 @@ public class JwtBearerReactiveOAuth2AuthorizedClientProviderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext)
|
||||
.block();
|
||||
.block();
|
||||
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
|
||||
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
|
||||
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
|
||||
|
||||
@@ -53,22 +53,22 @@ public class OAuth2AuthorizationContextTests {
|
||||
@Test
|
||||
public void withClientRegistrationWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(null).build())
|
||||
.withMessage("clientRegistration cannot be null");
|
||||
.isThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(null).build())
|
||||
.withMessage("clientRegistration cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withAuthorizedClientWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> OAuth2AuthorizationContext.withAuthorizedClient(null).build())
|
||||
.withMessage("authorizedClient cannot be null");
|
||||
.isThrownBy(() -> OAuth2AuthorizationContext.withAuthorizedClient(null).build())
|
||||
.withMessage("authorizedClient cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withClientRegistrationWhenPrincipalIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).build())
|
||||
.withMessage("principal cannot be null");
|
||||
.isThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).build())
|
||||
.withMessage("principal cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -47,38 +47,44 @@ public class OAuth2AuthorizeRequestTests {
|
||||
@Test
|
||||
public void withClientRegistrationIdWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest.withClientRegistrationId(null))
|
||||
.withMessage("clientRegistrationId cannot be empty");
|
||||
.withMessage("clientRegistrationId cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest.withAuthorizedClient(null))
|
||||
.withMessage("authorizedClient cannot be null");
|
||||
.withMessage("authorizedClient cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withClientRegistrationIdWhenPrincipalIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).build())
|
||||
.withMessage("principal cannot be null");
|
||||
.isThrownBy(
|
||||
() -> OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId())
|
||||
.build())
|
||||
.withMessage("principal cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withClientRegistrationIdWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal((String) null).build())
|
||||
.withMessage("principalName cannot be empty");
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(
|
||||
() -> OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId())
|
||||
.principal((String) null)
|
||||
.build())
|
||||
.withMessage("principalName cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withClientRegistrationIdWhenAllValuesProvidedThenAllValuesAreSet() {
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
|
||||
.attributes((attrs) -> {
|
||||
attrs.put("name1", "value1");
|
||||
attrs.put("name2", "value2");
|
||||
}).build();
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
|
||||
.principal(this.principal)
|
||||
.attributes((attrs) -> {
|
||||
attrs.put("name1", "value1");
|
||||
attrs.put("name2", "value2");
|
||||
})
|
||||
.build();
|
||||
assertThat(authorizeRequest.getClientRegistrationId()).isEqualTo(this.clientRegistration.getRegistrationId());
|
||||
assertThat(authorizeRequest.getAuthorizedClient()).isNull();
|
||||
assertThat(authorizeRequest.getPrincipal()).isEqualTo(this.principal);
|
||||
@@ -88,12 +94,14 @@ public class OAuth2AuthorizeRequestTests {
|
||||
@Test
|
||||
public void withAuthorizedClientWhenAllValuesProvidedThenAllValuesAreSet() {
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).attributes((attrs) -> {
|
||||
attrs.put("name1", "value1");
|
||||
attrs.put("name2", "value2");
|
||||
}).build();
|
||||
.principal(this.principal)
|
||||
.attributes((attrs) -> {
|
||||
attrs.put("name1", "value1");
|
||||
attrs.put("name2", "value2");
|
||||
})
|
||||
.build();
|
||||
assertThat(authorizeRequest.getClientRegistrationId())
|
||||
.isEqualTo(this.authorizedClient.getClientRegistration().getRegistrationId());
|
||||
.isEqualTo(this.authorizedClient.getClientRegistration().getRegistrationId());
|
||||
assertThat(authorizeRequest.getAuthorizedClient()).isEqualTo(this.authorizedClient);
|
||||
assertThat(authorizeRequest.getPrincipal()).isEqualTo(this.principal);
|
||||
assertThat(authorizeRequest.getAttributes()).contains(entry("name1", "value1"), entry("name2", "value2"));
|
||||
@@ -102,8 +110,9 @@ public class OAuth2AuthorizeRequestTests {
|
||||
@Test
|
||||
public void withClientRegistrationIdWhenPrincipalNameProvidedThenPrincipalCreated() {
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal("principalName")
|
||||
.build();
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
|
||||
.principal("principalName")
|
||||
.build();
|
||||
assertThat(authorizeRequest.getClientRegistrationId()).isEqualTo(this.clientRegistration.getRegistrationId());
|
||||
assertThat(authorizeRequest.getAuthorizedClient()).isNull();
|
||||
assertThat(authorizeRequest.getPrincipal().getName()).isEqualTo("principalName");
|
||||
|
||||
@@ -31,13 +31,13 @@ public class OAuth2AuthorizedClientIdTests {
|
||||
@Test
|
||||
public void constructorWhenRegistrationIdNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientId(null, "test-principal"))
|
||||
.withMessage("clientRegistrationId cannot be empty");
|
||||
.withMessage("clientRegistrationId cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorWhenPrincipalNameNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientId("test-client", null))
|
||||
.withMessage("principalName cannot be empty");
|
||||
.withMessage("principalName cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -71,7 +71,7 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
this.accessTokenClient = mock(RestOperations.class);
|
||||
given(this.accessTokenClient.exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class)))
|
||||
.willReturn(new ResponseEntity(accessTokenResponse, HttpStatus.OK));
|
||||
.willReturn(new ResponseEntity(accessTokenResponse, HttpStatus.OK));
|
||||
this.refreshTokenTokenResponseClient = new DefaultRefreshTokenTokenResponseClient();
|
||||
this.refreshTokenTokenResponseClient.setRestOperations(this.accessTokenClient);
|
||||
this.clientCredentialsTokenResponseClient = new DefaultClientCredentialsTokenResponseClient();
|
||||
@@ -84,7 +84,7 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
|
||||
@Test
|
||||
public void providerWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> OAuth2AuthorizedClientProviderBuilder.builder().provider(null));
|
||||
.isThrownBy(() -> OAuth2AuthorizedClientProviderBuilder.builder().provider(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -99,15 +99,14 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
|
||||
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext));
|
||||
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void buildWhenRefreshTokenProviderThenProviderReauthorizes() {
|
||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.refreshToken(
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.build();
|
||||
.refreshToken((configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.build();
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
|
||||
TestClientRegistrations.clientRegistration().build(), this.principal.getName(), expiredAccessToken(),
|
||||
TestOAuth2RefreshTokens.refreshToken());
|
||||
@@ -125,9 +124,9 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
|
||||
@Test
|
||||
public void buildWhenClientCredentialsProviderThenProviderAuthorizes() {
|
||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.clientCredentials(
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.build();
|
||||
.clientCredentials(
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.build();
|
||||
// @formatter:off
|
||||
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
|
||||
.withClientRegistration(TestClientRegistrations.clientCredentials().build())
|
||||
@@ -160,13 +159,12 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
|
||||
@Test
|
||||
public void buildWhenAllProvidersThenProvidersAuthorize() {
|
||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.authorizationCode()
|
||||
.refreshToken(
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.clientCredentials(
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient))
|
||||
.build();
|
||||
.authorizationCode()
|
||||
.refreshToken((configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.clientCredentials(
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient))
|
||||
.build();
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
|
||||
// authorization_code
|
||||
// @formatter:off
|
||||
@@ -176,12 +174,14 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
|
||||
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext));
|
||||
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext));
|
||||
// refresh_token
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration,
|
||||
this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());
|
||||
OAuth2AuthorizationContext refreshTokenContext = OAuth2AuthorizationContext
|
||||
.withAuthorizedClient(authorizedClient).principal(this.principal).build();
|
||||
.withAuthorizedClient(authorizedClient)
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
OAuth2AuthorizedClient reauthorizedClient = authorizedClientProvider.authorize(refreshTokenContext);
|
||||
assertThat(reauthorizedClient).isNotNull();
|
||||
verify(this.accessTokenClient, times(1)).exchange(any(RequestEntity.class),
|
||||
|
||||
@@ -50,19 +50,19 @@ public class OAuth2AuthorizedClientTests {
|
||||
@Test
|
||||
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2AuthorizedClient(null, this.principalName, this.accessToken));
|
||||
.isThrownBy(() -> new OAuth2AuthorizedClient(null, this.principalName, this.accessToken));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2AuthorizedClient(this.clientRegistration, null, this.accessToken));
|
||||
.isThrownBy(() -> new OAuth2AuthorizedClient(this.clientRegistration, null, this.accessToken));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2AuthorizedClient(this.clientRegistration, this.principalName, null));
|
||||
.isThrownBy(() -> new OAuth2AuthorizedClient(this.clientRegistration, this.principalName, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -66,8 +66,8 @@ public class PasswordOAuth2AuthorizedClientProviderTests {
|
||||
@Test
|
||||
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
|
||||
.withMessage("accessTokenResponseClient cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
|
||||
.withMessage("accessTokenResponseClient cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -67,8 +67,8 @@ public class PasswordReactiveOAuth2AuthorizedClientProviderTests {
|
||||
@Test
|
||||
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
|
||||
.withMessage("accessTokenResponseClient cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
|
||||
.withMessage("accessTokenResponseClient cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -233,7 +233,7 @@ public class PasswordReactiveOAuth2AuthorizedClientProviderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext)
|
||||
.block();
|
||||
.block();
|
||||
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
|
||||
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
|
||||
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
|
||||
|
||||
@@ -77,7 +77,7 @@ public class R2dbcReactiveOAuth2AuthorizedClientServiceTests {
|
||||
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
|
||||
this.clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(anyString()))
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
.willReturn(Mono.just(this.clientRegistration));
|
||||
this.databaseClient = DatabaseClient.create(connectionFactory);
|
||||
this.authorizedClientService = new R2dbcReactiveOAuth2AuthorizedClientService(this.databaseClient,
|
||||
this.clientRegistrationRepository);
|
||||
@@ -86,67 +86,71 @@ public class R2dbcReactiveOAuth2AuthorizedClientServiceTests {
|
||||
@Test
|
||||
public void constructorWhenDatabaseClientIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(
|
||||
() -> new R2dbcReactiveOAuth2AuthorizedClientService(null, this.clientRegistrationRepository))
|
||||
.withMessageContaining("databaseClient cannot be null");
|
||||
.isThrownBy(() -> new R2dbcReactiveOAuth2AuthorizedClientService(null, this.clientRegistrationRepository))
|
||||
.withMessageContaining("databaseClient cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> new R2dbcReactiveOAuth2AuthorizedClientService(this.databaseClient, null))
|
||||
.withMessageContaining("clientRegistrationRepository cannot be null");
|
||||
.isThrownBy(() -> new R2dbcReactiveOAuth2AuthorizedClientService(this.databaseClient, null))
|
||||
.withMessageContaining("clientRegistrationRepository cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, "principalName"))
|
||||
.withMessageContaining("clientRegistrationId cannot be empty");
|
||||
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, "principalName"))
|
||||
.withMessageContaining("clientRegistrationId cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
|
||||
.withMessageContaining("principalName cannot be empty");
|
||||
.isThrownBy(() -> this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
|
||||
.withMessageContaining("principalName cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenDoesNotExistThenReturnNull() {
|
||||
this.authorizedClientService.loadAuthorizedClient("registration-not-found", "principalName")
|
||||
.as(StepVerifier::create).expectNextCount(0).verifyComplete();
|
||||
.as(StepVerifier::create)
|
||||
.expectNextCount(0)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAuthorizedClientWhenExistsThenReturnAuthorizedClient() {
|
||||
Authentication principal = createPrincipal();
|
||||
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
|
||||
this.authorizedClientService.saveAuthorizedClient(expected, principal).as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
this.authorizedClientService.saveAuthorizedClient(expected, principal)
|
||||
.as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
|
||||
this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create).assertNext((authorizedClient) -> {
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
|
||||
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(expected.getAccessToken().getTokenType());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(expected.getAccessToken().getTokenValue());
|
||||
assertThat(authorizedClient.getAccessToken().getIssuedAt())
|
||||
.isEqualTo(expected.getAccessToken().getIssuedAt());
|
||||
assertThat(authorizedClient.getAccessToken().getExpiresAt())
|
||||
.isEqualTo(expected.getAccessToken().getExpiresAt());
|
||||
assertThat(authorizedClient.getAccessToken().getScopes())
|
||||
.isEqualTo(expected.getAccessToken().getScopes());
|
||||
assertThat(authorizedClient.getRefreshToken().getTokenValue())
|
||||
.isEqualTo(expected.getRefreshToken().getTokenValue());
|
||||
assertThat(authorizedClient.getRefreshToken().getIssuedAt())
|
||||
.isEqualTo(expected.getRefreshToken().getIssuedAt());
|
||||
}).verifyComplete();
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create)
|
||||
.assertNext((authorizedClient) -> {
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
|
||||
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(expected.getAccessToken().getTokenType());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(expected.getAccessToken().getTokenValue());
|
||||
assertThat(authorizedClient.getAccessToken().getIssuedAt())
|
||||
.isEqualTo(expected.getAccessToken().getIssuedAt());
|
||||
assertThat(authorizedClient.getAccessToken().getExpiresAt())
|
||||
.isEqualTo(expected.getAccessToken().getExpiresAt());
|
||||
assertThat(authorizedClient.getAccessToken().getScopes())
|
||||
.isEqualTo(expected.getAccessToken().getScopes());
|
||||
assertThat(authorizedClient.getRefreshToken().getTokenValue())
|
||||
.isEqualTo(expected.getRefreshToken().getTokenValue());
|
||||
assertThat(authorizedClient.getRefreshToken().getIssuedAt())
|
||||
.isEqualTo(expected.getRefreshToken().getIssuedAt());
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -155,16 +159,16 @@ public class R2dbcReactiveOAuth2AuthorizedClientServiceTests {
|
||||
Authentication principal = createPrincipal();
|
||||
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
|
||||
|
||||
this.authorizedClientService.saveAuthorizedClient(expected, principal).as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
this.authorizedClientService.saveAuthorizedClient(expected, principal)
|
||||
.as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
|
||||
this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create)
|
||||
.verifyErrorSatisfies((exception) -> assertThat(exception)
|
||||
.isInstanceOf(DataRetrievalFailureException.class)
|
||||
.hasMessage("The ClientRegistration with id '" + this.clientRegistration.getRegistrationId()
|
||||
+ "' exists in the data source, however, it was not found in the ReactiveClientRegistrationRepository."));
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create)
|
||||
.verifyErrorSatisfies((exception) -> assertThat(exception).isInstanceOf(DataRetrievalFailureException.class)
|
||||
.hasMessage("The ClientRegistration with id '" + this.clientRegistration.getRegistrationId()
|
||||
+ "' exists in the data source, however, it was not found in the ReactiveClientRegistrationRepository."));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -172,8 +176,8 @@ public class R2dbcReactiveOAuth2AuthorizedClientServiceTests {
|
||||
Authentication principal = createPrincipal();
|
||||
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, principal))
|
||||
.withMessageContaining("authorizedClient cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, principal))
|
||||
.withMessageContaining("authorizedClient cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -181,8 +185,8 @@ public class R2dbcReactiveOAuth2AuthorizedClientServiceTests {
|
||||
Authentication principal = createPrincipal();
|
||||
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, null))
|
||||
.withMessageContaining("principal cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, null))
|
||||
.withMessageContaining("principal cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -190,57 +194,62 @@ public class R2dbcReactiveOAuth2AuthorizedClientServiceTests {
|
||||
Authentication principal = createPrincipal();
|
||||
final OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
|
||||
|
||||
this.authorizedClientService.saveAuthorizedClient(expected, principal).as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
this.authorizedClientService.saveAuthorizedClient(expected, principal)
|
||||
.as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
|
||||
this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create).assertNext((authorizedClient) -> {
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
|
||||
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(expected.getAccessToken().getTokenType());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(expected.getAccessToken().getTokenValue());
|
||||
assertThat(authorizedClient.getAccessToken().getIssuedAt())
|
||||
.isEqualTo(expected.getAccessToken().getIssuedAt());
|
||||
assertThat(authorizedClient.getAccessToken().getExpiresAt())
|
||||
.isEqualTo(expected.getAccessToken().getExpiresAt());
|
||||
assertThat(authorizedClient.getAccessToken().getScopes())
|
||||
.isEqualTo(expected.getAccessToken().getScopes());
|
||||
assertThat(authorizedClient.getRefreshToken().getTokenValue())
|
||||
.isEqualTo(expected.getRefreshToken().getTokenValue());
|
||||
assertThat(authorizedClient.getRefreshToken().getIssuedAt())
|
||||
.isEqualTo(expected.getRefreshToken().getIssuedAt());
|
||||
}).verifyComplete();
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create)
|
||||
.assertNext((authorizedClient) -> {
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
|
||||
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(expected.getAccessToken().getTokenType());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(expected.getAccessToken().getTokenValue());
|
||||
assertThat(authorizedClient.getAccessToken().getIssuedAt())
|
||||
.isEqualTo(expected.getAccessToken().getIssuedAt());
|
||||
assertThat(authorizedClient.getAccessToken().getExpiresAt())
|
||||
.isEqualTo(expected.getAccessToken().getExpiresAt());
|
||||
assertThat(authorizedClient.getAccessToken().getScopes())
|
||||
.isEqualTo(expected.getAccessToken().getScopes());
|
||||
assertThat(authorizedClient.getRefreshToken().getTokenValue())
|
||||
.isEqualTo(expected.getRefreshToken().getTokenValue());
|
||||
assertThat(authorizedClient.getRefreshToken().getIssuedAt())
|
||||
.isEqualTo(expected.getRefreshToken().getIssuedAt());
|
||||
})
|
||||
.verifyComplete();
|
||||
|
||||
// Test save/load of NOT NULL attributes only
|
||||
principal = createPrincipal();
|
||||
OAuth2AuthorizedClient updatedExpectedPrincipal = createAuthorizedClient(principal, this.clientRegistration,
|
||||
true);
|
||||
this.authorizedClientService.saveAuthorizedClient(updatedExpectedPrincipal, principal).as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
this.authorizedClientService.saveAuthorizedClient(updatedExpectedPrincipal, principal)
|
||||
.as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
|
||||
this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create).assertNext((authorizedClient) -> {
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
assertThat(authorizedClient.getClientRegistration())
|
||||
.isEqualTo(updatedExpectedPrincipal.getClientRegistration());
|
||||
assertThat(authorizedClient.getPrincipalName())
|
||||
.isEqualTo(updatedExpectedPrincipal.getPrincipalName());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getTokenType());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getTokenValue());
|
||||
assertThat(authorizedClient.getAccessToken().getIssuedAt())
|
||||
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getIssuedAt());
|
||||
assertThat(authorizedClient.getAccessToken().getExpiresAt())
|
||||
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getExpiresAt());
|
||||
assertThat(authorizedClient.getAccessToken().getScopes()).isEmpty();
|
||||
assertThat(authorizedClient.getRefreshToken()).isNull();
|
||||
}).verifyComplete();
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create)
|
||||
.assertNext((authorizedClient) -> {
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
assertThat(authorizedClient.getClientRegistration())
|
||||
.isEqualTo(updatedExpectedPrincipal.getClientRegistration());
|
||||
assertThat(authorizedClient.getPrincipalName()).isEqualTo(updatedExpectedPrincipal.getPrincipalName());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getTokenType());
|
||||
assertThat(authorizedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getTokenValue());
|
||||
assertThat(authorizedClient.getAccessToken().getIssuedAt())
|
||||
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getIssuedAt());
|
||||
assertThat(authorizedClient.getAccessToken().getExpiresAt())
|
||||
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getExpiresAt());
|
||||
assertThat(authorizedClient.getAccessToken().getScopes()).isEmpty();
|
||||
assertThat(authorizedClient.getRefreshToken()).isNull();
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -248,52 +257,55 @@ public class R2dbcReactiveOAuth2AuthorizedClientServiceTests {
|
||||
// Given a saved authorized client
|
||||
Authentication principal = createPrincipal();
|
||||
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
|
||||
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal).as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal)
|
||||
.as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
|
||||
// When a client with the same principal and registration id is saved
|
||||
OAuth2AuthorizedClient updatedAuthorizedClient = createAuthorizedClient(principal, this.clientRegistration);
|
||||
this.authorizedClientService.saveAuthorizedClient(updatedAuthorizedClient, principal).as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
this.authorizedClientService.saveAuthorizedClient(updatedAuthorizedClient, principal)
|
||||
.as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
|
||||
// Then the saved client is updated
|
||||
this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create).assertNext((savedClient) -> {
|
||||
assertThat(savedClient).isNotNull();
|
||||
assertThat(savedClient.getClientRegistration())
|
||||
.isEqualTo(updatedAuthorizedClient.getClientRegistration());
|
||||
assertThat(savedClient.getPrincipalName()).isEqualTo(updatedAuthorizedClient.getPrincipalName());
|
||||
assertThat(savedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(updatedAuthorizedClient.getAccessToken().getTokenType());
|
||||
assertThat(savedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(updatedAuthorizedClient.getAccessToken().getTokenValue());
|
||||
assertThat(savedClient.getAccessToken().getIssuedAt())
|
||||
.isEqualTo(updatedAuthorizedClient.getAccessToken().getIssuedAt());
|
||||
assertThat(savedClient.getAccessToken().getExpiresAt())
|
||||
.isEqualTo(updatedAuthorizedClient.getAccessToken().getExpiresAt());
|
||||
assertThat(savedClient.getAccessToken().getScopes())
|
||||
.isEqualTo(updatedAuthorizedClient.getAccessToken().getScopes());
|
||||
assertThat(savedClient.getRefreshToken().getTokenValue())
|
||||
.isEqualTo(updatedAuthorizedClient.getRefreshToken().getTokenValue());
|
||||
assertThat(savedClient.getRefreshToken().getIssuedAt())
|
||||
.isEqualTo(updatedAuthorizedClient.getRefreshToken().getIssuedAt());
|
||||
});
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create)
|
||||
.assertNext((savedClient) -> {
|
||||
assertThat(savedClient).isNotNull();
|
||||
assertThat(savedClient.getClientRegistration())
|
||||
.isEqualTo(updatedAuthorizedClient.getClientRegistration());
|
||||
assertThat(savedClient.getPrincipalName()).isEqualTo(updatedAuthorizedClient.getPrincipalName());
|
||||
assertThat(savedClient.getAccessToken().getTokenType())
|
||||
.isEqualTo(updatedAuthorizedClient.getAccessToken().getTokenType());
|
||||
assertThat(savedClient.getAccessToken().getTokenValue())
|
||||
.isEqualTo(updatedAuthorizedClient.getAccessToken().getTokenValue());
|
||||
assertThat(savedClient.getAccessToken().getIssuedAt())
|
||||
.isEqualTo(updatedAuthorizedClient.getAccessToken().getIssuedAt());
|
||||
assertThat(savedClient.getAccessToken().getExpiresAt())
|
||||
.isEqualTo(updatedAuthorizedClient.getAccessToken().getExpiresAt());
|
||||
assertThat(savedClient.getAccessToken().getScopes())
|
||||
.isEqualTo(updatedAuthorizedClient.getAccessToken().getScopes());
|
||||
assertThat(savedClient.getRefreshToken().getTokenValue())
|
||||
.isEqualTo(updatedAuthorizedClient.getRefreshToken().getTokenValue());
|
||||
assertThat(savedClient.getRefreshToken().getIssuedAt())
|
||||
.isEqualTo(updatedAuthorizedClient.getRefreshToken().getIssuedAt());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, "principalName"))
|
||||
.withMessageContaining("clientRegistrationId cannot be empty");
|
||||
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, "principalName"))
|
||||
.withMessageContaining("clientRegistrationId cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void removeAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.authorizedClientService
|
||||
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
|
||||
.withMessageContaining("principalName cannot be empty");
|
||||
.isThrownBy(() -> this.authorizedClientService
|
||||
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
|
||||
.withMessageContaining("principalName cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -301,46 +313,53 @@ public class R2dbcReactiveOAuth2AuthorizedClientServiceTests {
|
||||
Authentication principal = createPrincipal();
|
||||
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
|
||||
|
||||
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal).as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal)
|
||||
.as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
|
||||
this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create).assertNext((dbAuthorizedClient) -> assertThat(dbAuthorizedClient).isNotNull())
|
||||
.verifyComplete();
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create)
|
||||
.assertNext((dbAuthorizedClient) -> assertThat(dbAuthorizedClient).isNotNull())
|
||||
.verifyComplete();
|
||||
|
||||
this.authorizedClientService
|
||||
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create).verifyComplete();
|
||||
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
|
||||
this.authorizedClientService
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create).expectNextCount(0).verifyComplete();
|
||||
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
|
||||
.as(StepVerifier::create)
|
||||
.expectNextCount(0)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setAuthorizedClientRowMapperWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.authorizedClientService.setAuthorizedClientRowMapper(null))
|
||||
.withMessageContaining("authorizedClientRowMapper cannot be nul");
|
||||
.isThrownBy(() -> this.authorizedClientService.setAuthorizedClientRowMapper(null))
|
||||
.withMessageContaining("authorizedClientRowMapper cannot be nul");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setAuthorizedClientParametersMapperWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.authorizedClientService.setAuthorizedClientParametersMapper(null))
|
||||
.withMessageContaining("authorizedClientParametersMapper cannot be nul");
|
||||
.isThrownBy(() -> this.authorizedClientService.setAuthorizedClientParametersMapper(null))
|
||||
.withMessageContaining("authorizedClientParametersMapper cannot be nul");
|
||||
}
|
||||
|
||||
private static ConnectionFactory createDb() {
|
||||
ConnectionFactory connectionFactory = H2ConnectionFactory.inMemory("oauth-test");
|
||||
|
||||
Mono.from(connectionFactory.create())
|
||||
.flatMapMany((connection) -> Flux
|
||||
.from(connection.createStatement("drop table oauth2_authorized_client").execute())
|
||||
.flatMap(Result::getRowsUpdated).onErrorResume((e) -> Mono.empty())
|
||||
.thenMany(connection.close()))
|
||||
.as(StepVerifier::create).verifyComplete();
|
||||
.flatMapMany((connection) -> Flux
|
||||
.from(connection.createStatement("drop table oauth2_authorized_client").execute())
|
||||
.flatMap(Result::getRowsUpdated)
|
||||
.onErrorResume((e) -> Mono.empty())
|
||||
.thenMany(connection.close()))
|
||||
.as(StepVerifier::create)
|
||||
.verifyComplete();
|
||||
ConnectionFactoryInitializer createDb = createDb(OAUTH2_CLIENT_SCHEMA_SQL_RESOURCE);
|
||||
createDb.setConnectionFactory(connectionFactory);
|
||||
createDb.afterPropertiesSet();
|
||||
|
||||
@@ -75,7 +75,7 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
|
||||
@Test
|
||||
public void providerWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(null));
|
||||
.isThrownBy(() -> ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -91,7 +91,7 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
|
||||
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext).block());
|
||||
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext).block());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -151,7 +151,9 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
|
||||
+ " \"token_type\": \"bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n";
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
|
||||
.builder().password().build();
|
||||
.builder()
|
||||
.password()
|
||||
.build();
|
||||
// @formatter:off
|
||||
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
|
||||
.withClientRegistration(
|
||||
@@ -178,7 +180,12 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
|
||||
.builder().authorizationCode().refreshToken().clientCredentials().password().build();
|
||||
.builder()
|
||||
.authorizationCode()
|
||||
.refreshToken()
|
||||
.clientCredentials()
|
||||
.password()
|
||||
.build();
|
||||
// authorization_code
|
||||
// @formatter:off
|
||||
OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext
|
||||
@@ -187,12 +194,14 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
|
||||
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext).block());
|
||||
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext).block());
|
||||
// refresh_token
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
|
||||
this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());
|
||||
OAuth2AuthorizationContext refreshTokenContext = OAuth2AuthorizationContext
|
||||
.withAuthorizedClient(authorizedClient).principal(this.principal).build();
|
||||
.withAuthorizedClient(authorizedClient)
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
OAuth2AuthorizedClient reauthorizedClient = authorizedClientProvider.authorize(refreshTokenContext).block();
|
||||
assertThat(reauthorizedClient).isNotNull();
|
||||
assertThat(this.server.getRequestCount()).isEqualTo(1);
|
||||
|
||||
@@ -162,7 +162,8 @@ public class RefreshTokenOAuth2AuthorizedClientProviderTests {
|
||||
@Test
|
||||
public void authorizeWhenAuthorizedAndAccessTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
|
||||
.refreshToken("new-refresh-token").build();
|
||||
.refreshToken("new-refresh-token")
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
Instant now = Instant.now();
|
||||
Instant issuedAt = now.minus(Duration.ofMinutes(60));
|
||||
@@ -228,10 +229,10 @@ public class RefreshTokenOAuth2AuthorizedClientProviderTests {
|
||||
// @formatter:on
|
||||
this.authorizedClientProvider.authorize(authorizationContext);
|
||||
ArgumentCaptor<OAuth2RefreshTokenGrantRequest> refreshTokenGrantRequestArgCaptor = ArgumentCaptor
|
||||
.forClass(OAuth2RefreshTokenGrantRequest.class);
|
||||
.forClass(OAuth2RefreshTokenGrantRequest.class);
|
||||
verify(this.accessTokenResponseClient).getTokenResponse(refreshTokenGrantRequestArgCaptor.capture());
|
||||
assertThat(refreshTokenGrantRequestArgCaptor.getValue().getScopes())
|
||||
.isEqualTo(new HashSet<>(Arrays.asList(requestScope)));
|
||||
.isEqualTo(new HashSet<>(Arrays.asList(requestScope)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -245,9 +246,9 @@ public class RefreshTokenOAuth2AuthorizedClientProviderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext))
|
||||
.withMessageStartingWith("The context attribute must be of type String[] '"
|
||||
+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
|
||||
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext))
|
||||
.withMessageStartingWith("The context attribute must be of type String[] '"
|
||||
+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -80,8 +80,8 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
|
||||
@Test
|
||||
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
|
||||
.withMessage("accessTokenResponseClient cannot be null");
|
||||
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
|
||||
.withMessage("accessTokenResponseClient cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -161,7 +161,8 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
|
||||
@Test
|
||||
public void authorizeWhenAuthorizedAndAccessTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
|
||||
.refreshToken("new-refresh-token").build();
|
||||
.refreshToken("new-refresh-token")
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
Instant now = Instant.now();
|
||||
Instant issuedAt = now.minus(Duration.ofMinutes(60));
|
||||
@@ -174,9 +175,11 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
|
||||
// force it to expire on the client
|
||||
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
|
||||
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
|
||||
.withAuthorizedClient(authorizedClient).principal(this.principal).build();
|
||||
.withAuthorizedClient(authorizedClient)
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext)
|
||||
.block();
|
||||
.block();
|
||||
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
|
||||
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
|
||||
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
|
||||
@@ -186,12 +189,15 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
|
||||
@Test
|
||||
public void authorizeWhenAuthorizedAndAccessTokenExpiredThenReauthorize() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
|
||||
.refreshToken("new-refresh-token").build();
|
||||
.refreshToken("new-refresh-token")
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
|
||||
.withAuthorizedClient(this.authorizedClient).principal(this.principal).build();
|
||||
.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal)
|
||||
.build();
|
||||
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext)
|
||||
.block();
|
||||
.block();
|
||||
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
|
||||
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
|
||||
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
|
||||
@@ -201,7 +207,8 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
|
||||
@Test
|
||||
public void authorizeWhenAuthorizedAndRequestScopeProvidedThenScopeRequested() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
|
||||
.refreshToken("new-refresh-token").build();
|
||||
.refreshToken("new-refresh-token")
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
String[] requestScope = new String[] { "read", "write" };
|
||||
// @formatter:off
|
||||
@@ -213,10 +220,10 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
|
||||
// @formatter:on
|
||||
this.authorizedClientProvider.authorize(authorizationContext).block();
|
||||
ArgumentCaptor<OAuth2RefreshTokenGrantRequest> refreshTokenGrantRequestArgCaptor = ArgumentCaptor
|
||||
.forClass(OAuth2RefreshTokenGrantRequest.class);
|
||||
.forClass(OAuth2RefreshTokenGrantRequest.class);
|
||||
verify(this.accessTokenResponseClient).getTokenResponse(refreshTokenGrantRequestArgCaptor.capture());
|
||||
assertThat(refreshTokenGrantRequestArgCaptor.getValue().getScopes())
|
||||
.isEqualTo(new HashSet<>(Arrays.asList(requestScope)));
|
||||
.isEqualTo(new HashSet<>(Arrays.asList(requestScope)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -230,9 +237,9 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block())
|
||||
.withMessageStartingWith("The context attribute must be of type String[] '"
|
||||
+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
|
||||
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block())
|
||||
.withMessageStartingWith("The context attribute must be of type String[] '"
|
||||
+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ public class OAuth2AuthenticationTokenTests {
|
||||
@Test
|
||||
public void constructorWhenAuthorizedClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2AuthenticationToken(this.principal, this.authorities, null));
|
||||
.isThrownBy(() -> new OAuth2AuthenticationToken(this.principal, this.authorities, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -81,41 +81,44 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
||||
@Test
|
||||
public void authenticateWhenAuthorizationErrorResponseThenThrowOAuth2AuthorizationException() {
|
||||
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error()
|
||||
.errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build();
|
||||
.errorCode(OAuth2ErrorCodes.INVALID_REQUEST)
|
||||
.build();
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
|
||||
authorizationResponse);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.authenticationProvider.authenticate(
|
||||
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)))
|
||||
.withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
|
||||
.isThrownBy(() -> this.authenticationProvider.authenticate(
|
||||
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)))
|
||||
.withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthorizationException() {
|
||||
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().state("67890")
|
||||
.build();
|
||||
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success()
|
||||
.state("67890")
|
||||
.build();
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
|
||||
authorizationResponse);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.authenticationProvider.authenticate(
|
||||
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)))
|
||||
.withMessageContaining("invalid_state_parameter");
|
||||
.isThrownBy(() -> this.authenticationProvider.authenticate(
|
||||
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)))
|
||||
.withMessageContaining("invalid_state_parameter");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenAuthorizationSuccessResponseThenExchangedForAccessToken() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
|
||||
.refreshToken("refresh").build();
|
||||
.refreshToken("refresh")
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
|
||||
TestOAuth2AuthorizationResponses.success().build());
|
||||
OAuth2AuthorizationCodeAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationProvider
|
||||
.authenticate(
|
||||
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange));
|
||||
.authenticate(
|
||||
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange));
|
||||
assertThat(authenticationResult.isAuthenticated()).isTrue();
|
||||
assertThat(authenticationResult.getPrincipal()).isEqualTo(this.clientRegistration.getClientId());
|
||||
assertThat(authenticationResult.getCredentials())
|
||||
.isEqualTo(accessTokenResponse.getAccessToken().getTokenValue());
|
||||
.isEqualTo(accessTokenResponse.getAccessToken().getTokenValue());
|
||||
assertThat(authenticationResult.getAuthorities()).isEqualTo(Collections.emptyList());
|
||||
assertThat(authenticationResult.getClientRegistration()).isEqualTo(this.clientRegistration);
|
||||
assertThat(authenticationResult.getAuthorizationExchange()).isEqualTo(authorizationExchange);
|
||||
@@ -130,15 +133,16 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
||||
additionalParameters.put("param1", "value1");
|
||||
additionalParameters.put("param2", "value2");
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
|
||||
.additionalParameters(additionalParameters).build();
|
||||
.additionalParameters(additionalParameters)
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
|
||||
TestOAuth2AuthorizationResponses.success().build());
|
||||
OAuth2AuthorizationCodeAuthenticationToken authentication = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationProvider
|
||||
.authenticate(
|
||||
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange));
|
||||
.authenticate(
|
||||
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange));
|
||||
assertThat(authentication.getAdditionalParameters())
|
||||
.containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
|
||||
.containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -56,13 +56,13 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests {
|
||||
@Test
|
||||
public void constructorAuthorizationRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange));
|
||||
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorAuthorizationRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null));
|
||||
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -71,7 +71,7 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests {
|
||||
this.clientRegistration, this.authorizationExchange);
|
||||
assertThat(authentication.getPrincipal()).isEqualTo(this.clientRegistration.getClientId());
|
||||
assertThat(authentication.getCredentials())
|
||||
.isEqualTo(this.authorizationExchange.getAuthorizationResponse().getCode());
|
||||
.isEqualTo(this.authorizationExchange.getAuthorizationResponse().getCode());
|
||||
assertThat(authentication.getAuthorities()).isEqualTo(Collections.emptyList());
|
||||
assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
|
||||
assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
|
||||
@@ -94,8 +94,8 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests {
|
||||
@Test
|
||||
public void constructorTokenRequestResponseWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration,
|
||||
this.authorizationExchange, null));
|
||||
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration,
|
||||
this.authorizationExchange, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -96,7 +96,7 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests {
|
||||
@Test
|
||||
public void authenticateWhenOAuth2AuthorizationExceptionThenOAuth2AuthorizationException() {
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any()))
|
||||
.willReturn(Mono.error(() -> new OAuth2AuthorizationException(new OAuth2Error("error"))));
|
||||
.willReturn(Mono.error(() -> new OAuth2AuthorizationException(new OAuth2Error("error"))));
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
|
||||
}
|
||||
|
||||
|
||||
@@ -95,13 +95,13 @@ public class OAuth2LoginAuthenticationProviderTests {
|
||||
@Test
|
||||
public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationProvider(null, this.userService));
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationProvider(null, this.userService));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorWhenUserServiceIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationProvider(this.accessTokenResponseClient, null));
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationProvider(this.accessTokenResponseClient, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -116,37 +116,40 @@ public class OAuth2LoginAuthenticationProviderTests {
|
||||
|
||||
@Test
|
||||
public void authenticateWhenAuthorizationRequestContainsOpenidScopeThenReturnNull() {
|
||||
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().scope("openid")
|
||||
.build();
|
||||
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
|
||||
.scope("openid")
|
||||
.build();
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
|
||||
this.authorizationResponse);
|
||||
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange));
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange));
|
||||
assertThat(authentication).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenAuthorizationErrorResponseThenThrowOAuth2AuthenticationException() {
|
||||
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error()
|
||||
.errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build();
|
||||
.errorCode(OAuth2ErrorCodes.INVALID_REQUEST)
|
||||
.build();
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
|
||||
authorizationResponse);
|
||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||
.isThrownBy(() -> this.authenticationProvider.authenticate(
|
||||
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
|
||||
.withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
|
||||
.isThrownBy(() -> this.authenticationProvider
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
|
||||
.withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthenticationException() {
|
||||
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().state("67890")
|
||||
.build();
|
||||
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success()
|
||||
.state("67890")
|
||||
.build();
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
|
||||
authorizationResponse);
|
||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||
.isThrownBy(() -> this.authenticationProvider.authenticate(
|
||||
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
|
||||
.withMessageContaining("invalid_state_parameter");
|
||||
.isThrownBy(() -> this.authenticationProvider
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
|
||||
.withMessageContaining("invalid_state_parameter");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -158,7 +161,7 @@ public class OAuth2LoginAuthenticationProviderTests {
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
|
||||
given(this.userService.loadUser(any())).willReturn(principal);
|
||||
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
|
||||
assertThat(authentication.isAuthenticated()).isTrue();
|
||||
assertThat(authentication.getPrincipal()).isEqualTo(principal);
|
||||
assertThat(authentication.getCredentials()).isEqualTo("");
|
||||
@@ -180,10 +183,10 @@ public class OAuth2LoginAuthenticationProviderTests {
|
||||
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER");
|
||||
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
|
||||
given(authoritiesMapper.mapAuthorities(anyCollection()))
|
||||
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
|
||||
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
|
||||
this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper);
|
||||
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
|
||||
assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities);
|
||||
}
|
||||
|
||||
@@ -198,9 +201,9 @@ public class OAuth2LoginAuthenticationProviderTests {
|
||||
ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
|
||||
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
|
||||
this.authenticationProvider
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
|
||||
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters())
|
||||
.containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
|
||||
.containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
|
||||
}
|
||||
|
||||
private OAuth2AccessTokenResponse accessTokenSuccessResponse() {
|
||||
|
||||
@@ -66,13 +66,13 @@ public class OAuth2LoginAuthenticationTokenTests {
|
||||
@Test
|
||||
public void constructorAuthorizationRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(null, this.authorizationExchange));
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(null, this.authorizationExchange));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorAuthorizationRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration, null));
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -97,15 +97,15 @@ public class OAuth2LoginAuthenticationTokenTests {
|
||||
@Test
|
||||
public void constructorTokenRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration, null, this.principal,
|
||||
this.authorities, this.accessToken));
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration, null, this.principal,
|
||||
this.authorities, this.accessToken));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorTokenRequestResponseWhenPrincipalIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration,
|
||||
this.authorizationExchange, null, this.authorities, this.accessToken));
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange,
|
||||
null, this.authorities, this.accessToken));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -123,8 +123,8 @@ public class OAuth2LoginAuthenticationTokenTests {
|
||||
@Test
|
||||
public void constructorTokenRequestResponseWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration,
|
||||
this.authorizationExchange, this.principal, this.authorities, null));
|
||||
.isThrownBy(() -> new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange,
|
||||
this.principal, this.authorities, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -78,7 +78,7 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
|
||||
private ClientRegistration.Builder registration = TestClientRegistrations.clientRegistration();
|
||||
|
||||
OAuth2AuthorizationResponse.Builder authorizationResponseBldr = OAuth2AuthorizationResponse.success("code")
|
||||
.state("state");
|
||||
.state("state");
|
||||
|
||||
private OAuth2LoginReactiveAuthenticationManager manager;
|
||||
|
||||
@@ -130,20 +130,21 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
|
||||
.state("state");
|
||||
// @formatter:on
|
||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
|
||||
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() {
|
||||
this.authorizationResponseBldr.state("notmatch");
|
||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
|
||||
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticationWhenOAuth2UserNotFoundThenEmpty() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER).build();
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER)
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
given(this.userService.loadUser(any())).willReturn(Mono.empty());
|
||||
assertThat(this.manager.authenticate(loginToken()).block()).isNull();
|
||||
@@ -152,13 +153,14 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
|
||||
@Test
|
||||
public void authenticationWhenOAuth2UserFoundThenSuccess() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER).build();
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER)
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
|
||||
Collections.singletonMap("user", "rob"), "user");
|
||||
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
|
||||
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken())
|
||||
.block();
|
||||
.block();
|
||||
assertThat(result.getPrincipal()).isEqualTo(user);
|
||||
assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities());
|
||||
assertThat(result.isAuthenticated()).isTrue();
|
||||
@@ -171,7 +173,9 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
|
||||
additionalParameters.put("param1", "value1");
|
||||
additionalParameters.put("param2", "value2");
|
||||
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(additionalParameters).build();
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER)
|
||||
.additionalParameters(additionalParameters)
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
|
||||
Collections.singletonMap("user", "rob"), "user");
|
||||
@@ -179,13 +183,14 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
|
||||
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
|
||||
this.manager.authenticate(loginToken()).block();
|
||||
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters())
|
||||
.containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
|
||||
.containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo")
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER).build();
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER)
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
|
||||
Collections.singletonMap("user", "rob"), "user");
|
||||
@@ -193,21 +198,25 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
|
||||
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH_USER");
|
||||
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
|
||||
given(authoritiesMapper.mapAuthorities(anyCollection()))
|
||||
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
|
||||
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
|
||||
this.manager.setAuthoritiesMapper(authoritiesMapper);
|
||||
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken())
|
||||
.block();
|
||||
.block();
|
||||
assertThat(result.getAuthorities()).isEqualTo(mappedAuthorities);
|
||||
}
|
||||
|
||||
private OAuth2AuthorizationCodeAuthenticationToken loginToken() {
|
||||
ClientRegistration clientRegistration = this.registration.build();
|
||||
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode().state("state")
|
||||
.clientId(clientRegistration.getClientId())
|
||||
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
|
||||
.redirectUri(clientRegistration.getRedirectUri()).scopes(clientRegistration.getScopes()).build();
|
||||
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
|
||||
.state("state")
|
||||
.clientId(clientRegistration.getClientId())
|
||||
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
|
||||
.redirectUri(clientRegistration.getRedirectUri())
|
||||
.scopes(clientRegistration.getScopes())
|
||||
.build();
|
||||
OAuth2AuthorizationResponse authorizationResponse = this.authorizationResponseBldr
|
||||
.redirectUri(clientRegistration.getRedirectUri()).build();
|
||||
.redirectUri(clientRegistration.getRedirectUri())
|
||||
.build();
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
|
||||
authorizationResponse);
|
||||
return new OAuth2AuthorizationCodeAuthenticationToken(clientRegistration, authorizationExchange);
|
||||
|
||||
@@ -114,13 +114,13 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build()));
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build()));
|
||||
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
|
||||
RecordedRequest recordedRequest = this.server.takeRequest();
|
||||
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
|
||||
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters).contains("grant_type=authorization_code");
|
||||
assertThat(formParameters).contains("code=code-1234");
|
||||
@@ -161,7 +161,8 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
ClientRegistration clientRegistration = this.clientRegistration
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
|
||||
.build();
|
||||
this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration));
|
||||
RecordedRequest recordedRequest = this.server.takeRequest();
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
|
||||
@@ -200,7 +201,7 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters)
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
assertThat(formParameters).contains("client_assertion=");
|
||||
}
|
||||
|
||||
@@ -231,7 +232,7 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters)
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
assertThat(formParameters).contains("client_assertion=");
|
||||
}
|
||||
|
||||
@@ -263,11 +264,11 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
.isThrownBy(() -> this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -279,11 +280,11 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
.isThrownBy(() -> this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -299,7 +300,7 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build()));
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build()));
|
||||
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
|
||||
}
|
||||
|
||||
@@ -315,7 +316,7 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build()));
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build()));
|
||||
assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty();
|
||||
}
|
||||
|
||||
@@ -323,10 +324,11 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
public void getTokenResponseWhenTokenUriInvalidThenThrowOAuth2AuthorizationException() {
|
||||
String invalidTokenUri = "https://invalid-provider.com/oauth2/token";
|
||||
ClientRegistration clientRegistration = this.clientRegistration.tokenUri(invalidTokenUri).build();
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(
|
||||
() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration)))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(
|
||||
() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest(clientRegistration)))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -344,10 +346,10 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
|
||||
.isThrownBy(() -> this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -355,28 +357,33 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
|
||||
String accessTokenErrorResponse = "{\n" + " \"error\": \"unauthorized_client\"\n" + "}\n";
|
||||
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
|
||||
.withMessageContaining("[unauthorized_client]");
|
||||
.isThrownBy(() -> this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
|
||||
.withMessageContaining("[unauthorized_client]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
|
||||
this.server.enqueue(new MockResponse().setResponseCode(500));
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
|
||||
.withMessageContaining("[invalid_token_response] An error occurred while attempting to retrieve "
|
||||
+ "the OAuth 2.0 Access Token Response");
|
||||
.isThrownBy(() -> this.tokenResponseClient
|
||||
.getTokenResponse(authorizationCodeGrantRequest(this.clientRegistration.build())))
|
||||
.withMessageContaining("[invalid_token_response] An error occurred while attempting to retrieve "
|
||||
+ "the OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
private OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest(ClientRegistration clientRegistration) {
|
||||
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
|
||||
.clientId(clientRegistration.getClientId()).state("state-1234")
|
||||
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
|
||||
.redirectUri(clientRegistration.getRedirectUri()).scopes(clientRegistration.getScopes()).build();
|
||||
.clientId(clientRegistration.getClientId())
|
||||
.state("state-1234")
|
||||
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
|
||||
.redirectUri(clientRegistration.getRedirectUri())
|
||||
.scopes(clientRegistration.getScopes())
|
||||
.build();
|
||||
OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponse.success("code-1234")
|
||||
.state("state-1234").redirectUri(clientRegistration.getRedirectUri()).build();
|
||||
.state("state-1234")
|
||||
.redirectUri(clientRegistration.getRedirectUri())
|
||||
.build();
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
|
||||
authorizationResponse);
|
||||
return new OAuth2AuthorizationCodeGrantRequest(clientRegistration, authorizationExchange);
|
||||
|
||||
@@ -117,13 +117,13 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
this.clientRegistration.build());
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(clientCredentialsGrantRequest);
|
||||
.getTokenResponse(clientCredentialsGrantRequest);
|
||||
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
|
||||
RecordedRequest recordedRequest = this.server.takeRequest();
|
||||
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
|
||||
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters).contains("grant_type=client_credentials");
|
||||
assertThat(formParameters).contains("scope=read+write");
|
||||
@@ -165,7 +165,8 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
ClientRegistration clientRegistration = this.clientRegistration
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
|
||||
.build();
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
clientRegistration);
|
||||
this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest);
|
||||
@@ -208,7 +209,7 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters)
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
assertThat(formParameters).contains("client_assertion=");
|
||||
}
|
||||
|
||||
@@ -241,7 +242,7 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters)
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
assertThat(formParameters).contains("client_assertion=");
|
||||
}
|
||||
|
||||
@@ -266,10 +267,10 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
this.clientRegistration.build());
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -279,10 +280,10 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
this.clientRegistration.build());
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -299,7 +300,7 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
this.clientRegistration.build());
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(clientCredentialsGrantRequest);
|
||||
.getTokenResponse(clientCredentialsGrantRequest);
|
||||
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
|
||||
}
|
||||
|
||||
@@ -316,7 +317,7 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
this.clientRegistration.build());
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(clientCredentialsGrantRequest);
|
||||
.getTokenResponse(clientCredentialsGrantRequest);
|
||||
assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty();
|
||||
}
|
||||
|
||||
@@ -327,9 +328,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
clientRegistration);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -348,9 +349,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
this.clientRegistration.build());
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -364,8 +365,8 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
this.clientRegistration.build());
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining("[unauthorized_client]");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining("[unauthorized_client]");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -374,9 +375,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
this.clientRegistration.build());
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
private MockResponse jsonResponse(String json) {
|
||||
|
||||
@@ -111,16 +111,16 @@ public class DefaultJwtBearerTokenResponseClientTests {
|
||||
ClientRegistration clientRegistration = this.clientRegistration.build();
|
||||
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(jwtBearerGrantRequest);
|
||||
.getTokenResponse(jwtBearerGrantRequest);
|
||||
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
|
||||
RecordedRequest recordedRequest = this.server.takeRequest();
|
||||
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
|
||||
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters)
|
||||
.contains("grant_type=" + URLEncoder.encode(AuthorizationGrantType.JWT_BEARER.getValue(), "UTF-8"));
|
||||
.contains("grant_type=" + URLEncoder.encode(AuthorizationGrantType.JWT_BEARER.getValue(), "UTF-8"));
|
||||
assertThat(formParameters).contains("scope=read+write");
|
||||
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
|
||||
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
|
||||
@@ -157,7 +157,8 @@ public class DefaultJwtBearerTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
ClientRegistration clientRegistration = this.clientRegistration
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
|
||||
.build();
|
||||
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
|
||||
this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest);
|
||||
RecordedRequest recordedRequest = this.server.takeRequest();
|
||||
@@ -180,10 +181,10 @@ public class DefaultJwtBearerTokenResponseClientTests {
|
||||
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
|
||||
this.jwtAssertion);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -200,7 +201,7 @@ public class DefaultJwtBearerTokenResponseClientTests {
|
||||
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
|
||||
this.jwtAssertion);
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(jwtBearerGrantRequest);
|
||||
.getTokenResponse(jwtBearerGrantRequest);
|
||||
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
|
||||
}
|
||||
|
||||
@@ -217,7 +218,7 @@ public class DefaultJwtBearerTokenResponseClientTests {
|
||||
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
|
||||
this.jwtAssertion);
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(jwtBearerGrantRequest);
|
||||
.getTokenResponse(jwtBearerGrantRequest);
|
||||
assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty();
|
||||
}
|
||||
|
||||
@@ -228,8 +229,8 @@ public class DefaultJwtBearerTokenResponseClientTests {
|
||||
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
|
||||
this.jwtAssertion);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest))
|
||||
.withMessageContaining("[invalid_grant]");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest))
|
||||
.withMessageContaining("[invalid_grant]");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -238,9 +239,9 @@ public class DefaultJwtBearerTokenResponseClientTests {
|
||||
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(this.clientRegistration.build(),
|
||||
this.jwtAssertion);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest))
|
||||
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
|
||||
+ "retrieve the OAuth 2.0 Access Token Response");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(jwtBearerGrantRequest))
|
||||
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
|
||||
+ "retrieve the OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
private MockResponse jsonResponse(String json) {
|
||||
|
||||
@@ -117,7 +117,7 @@ public class DefaultPasswordTokenResponseClientTests {
|
||||
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
|
||||
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters).contains("grant_type=password");
|
||||
assertThat(formParameters).contains("username=user1");
|
||||
@@ -127,7 +127,7 @@ public class DefaultPasswordTokenResponseClientTests {
|
||||
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
|
||||
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
|
||||
assertThat(accessTokenResponse.getAccessToken().getScopes())
|
||||
.containsExactly(clientRegistration.getScopes().toArray(new String[0]));
|
||||
.containsExactly(clientRegistration.getScopes().toArray(new String[0]));
|
||||
assertThat(accessTokenResponse.getRefreshToken()).isNull();
|
||||
}
|
||||
|
||||
@@ -143,7 +143,8 @@ public class DefaultPasswordTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
ClientRegistration clientRegistration = this.clientRegistration
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
|
||||
.build();
|
||||
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration,
|
||||
this.username, this.password);
|
||||
this.tokenResponseClient.getTokenResponse(passwordGrantRequest);
|
||||
@@ -186,7 +187,7 @@ public class DefaultPasswordTokenResponseClientTests {
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters)
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
assertThat(formParameters).contains("client_assertion=");
|
||||
}
|
||||
|
||||
@@ -219,7 +220,7 @@ public class DefaultPasswordTokenResponseClientTests {
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters)
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
assertThat(formParameters).contains("client_assertion=");
|
||||
}
|
||||
|
||||
@@ -244,10 +245,10 @@ public class DefaultPasswordTokenResponseClientTests {
|
||||
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
|
||||
this.clientRegistration.build(), this.username, this.password);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
|
||||
.withMessageContaining(
|
||||
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -293,8 +294,8 @@ public class DefaultPasswordTokenResponseClientTests {
|
||||
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
|
||||
this.clientRegistration.build(), this.username, this.password);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
|
||||
.withMessageContaining("[unauthorized_client]");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
|
||||
.withMessageContaining("[unauthorized_client]");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -303,9 +304,9 @@ public class DefaultPasswordTokenResponseClientTests {
|
||||
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
|
||||
this.clientRegistration.build(), this.username, this.password);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
|
||||
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
|
||||
+ "retrieve the OAuth 2.0 Access Token Response");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
|
||||
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
|
||||
+ "retrieve the OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
private MockResponse jsonResponse(String json) {
|
||||
|
||||
@@ -113,13 +113,13 @@ public class DefaultRefreshTokenTokenResponseClientTests {
|
||||
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
|
||||
this.clientRegistration.build(), this.accessToken, this.refreshToken);
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(refreshTokenGrantRequest);
|
||||
.getTokenResponse(refreshTokenGrantRequest);
|
||||
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
|
||||
RecordedRequest recordedRequest = this.server.takeRequest();
|
||||
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
|
||||
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters).contains("grant_type=refresh_token");
|
||||
@@ -128,7 +128,7 @@ public class DefaultRefreshTokenTokenResponseClientTests {
|
||||
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
|
||||
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
|
||||
assertThat(accessTokenResponse.getAccessToken().getScopes())
|
||||
.containsExactly(this.accessToken.getScopes().toArray(new String[0]));
|
||||
.containsExactly(this.accessToken.getScopes().toArray(new String[0]));
|
||||
assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo(this.refreshToken.getTokenValue());
|
||||
}
|
||||
|
||||
@@ -143,13 +143,14 @@ public class DefaultRefreshTokenTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
ClientRegistration clientRegistration = this.clientRegistration
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
|
||||
.build();
|
||||
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
|
||||
this.accessToken, this.refreshToken);
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(refreshTokenGrantRequest);
|
||||
.getTokenResponse(refreshTokenGrantRequest);
|
||||
assertThat(accessTokenResponse.getAccessToken().getScopes())
|
||||
.containsExactly(this.accessToken.getScopes().toArray(new String[0]));
|
||||
.containsExactly(this.accessToken.getScopes().toArray(new String[0]));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -163,7 +164,8 @@ public class DefaultRefreshTokenTokenResponseClientTests {
|
||||
// @formatter:on
|
||||
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
|
||||
ClientRegistration clientRegistration = this.clientRegistration
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST).build();
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
|
||||
.build();
|
||||
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration,
|
||||
this.accessToken, this.refreshToken);
|
||||
this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest);
|
||||
@@ -206,7 +208,7 @@ public class DefaultRefreshTokenTokenResponseClientTests {
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters)
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
assertThat(formParameters).contains("client_assertion=");
|
||||
}
|
||||
|
||||
@@ -239,7 +241,7 @@ public class DefaultRefreshTokenTokenResponseClientTests {
|
||||
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters)
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
.contains("client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer");
|
||||
assertThat(formParameters).contains("client_assertion=");
|
||||
}
|
||||
|
||||
@@ -264,10 +266,10 @@ public class DefaultRefreshTokenTokenResponseClientTests {
|
||||
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
|
||||
this.clientRegistration.build(), this.accessToken, this.refreshToken);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
|
||||
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
|
||||
+ "retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
|
||||
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
|
||||
+ "retrieve the OAuth 2.0 Access Token Response")
|
||||
.withMessageContaining("tokenType cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -284,7 +286,7 @@ public class DefaultRefreshTokenTokenResponseClientTests {
|
||||
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
|
||||
this.clientRegistration.build(), this.accessToken, this.refreshToken, Collections.singleton("read"));
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(refreshTokenGrantRequest);
|
||||
.getTokenResponse(refreshTokenGrantRequest);
|
||||
RecordedRequest recordedRequest = this.server.takeRequest();
|
||||
String formParameters = recordedRequest.getBody().readUtf8();
|
||||
assertThat(formParameters).contains("scope=read");
|
||||
@@ -298,8 +300,8 @@ public class DefaultRefreshTokenTokenResponseClientTests {
|
||||
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
|
||||
this.clientRegistration.build(), this.accessToken, this.refreshToken);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
|
||||
.withMessageContaining("[unauthorized_client]");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
|
||||
.withMessageContaining("[unauthorized_client]");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -308,9 +310,9 @@ public class DefaultRefreshTokenTokenResponseClientTests {
|
||||
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
|
||||
this.clientRegistration.build(), this.accessToken, this.refreshToken);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
|
||||
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
|
||||
+ "retrieve the OAuth 2.0 Access Token Response");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
|
||||
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
|
||||
+ "retrieve the OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
private MockResponse jsonResponse(String json) {
|
||||
|
||||
@@ -57,25 +57,25 @@ public class JwtBearerGrantRequestEntityConverterTests {
|
||||
@Test
|
||||
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setHeadersConverter(null))
|
||||
.withMessage("headersConverter cannot be null");
|
||||
.withMessage("headersConverter cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addHeadersConverter(null))
|
||||
.withMessage("headersConverter cannot be null");
|
||||
.withMessage("headersConverter cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setParametersConverter(null))
|
||||
.withMessage("parametersConverter cannot be null");
|
||||
.withMessage("parametersConverter cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.addParametersConverter(null))
|
||||
.withMessage("parametersConverter cannot be null");
|
||||
.withMessage("parametersConverter cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -132,15 +132,15 @@ public class JwtBearerGrantRequestEntityConverterTests {
|
||||
RequestEntity<?> requestEntity = this.converter.convert(jwtBearerGrantRequest);
|
||||
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
|
||||
assertThat(requestEntity.getUrl().toASCIIString())
|
||||
.isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
|
||||
.isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
|
||||
HttpHeaders headers = requestEntity.getHeaders();
|
||||
assertThat(headers.getAccept()).contains(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
|
||||
assertThat(headers.getContentType())
|
||||
.isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
|
||||
.isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
|
||||
assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
|
||||
MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
|
||||
assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE))
|
||||
.isEqualTo(AuthorizationGrantType.JWT_BEARER.getValue());
|
||||
.isEqualTo(AuthorizationGrantType.JWT_BEARER.getValue());
|
||||
assertThat(formParameters.getFirst(OAuth2ParameterNames.ASSERTION)).isEqualTo(jwtAssertion.getTokenValue());
|
||||
assertThat(formParameters.getFirst(OAuth2ParameterNames.SCOPE)).isEqualTo("read write");
|
||||
}
|
||||
|
||||
@@ -35,28 +35,29 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
|
||||
public class JwtBearerGrantRequestTests {
|
||||
|
||||
private final ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
|
||||
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER).build();
|
||||
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
|
||||
.build();
|
||||
|
||||
private final Jwt jwtAssertion = TestJwts.jwt().build();
|
||||
|
||||
@Test
|
||||
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new JwtBearerGrantRequest(null, this.jwtAssertion))
|
||||
.withMessage("clientRegistration cannot be null");
|
||||
.withMessage("clientRegistration cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorWhenJwtIsNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> new JwtBearerGrantRequest(this.clientRegistration, null))
|
||||
.withMessage("jwt cannot be null");
|
||||
.withMessage("jwt cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException() {
|
||||
ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new JwtBearerGrantRequest(registration, this.jwtAssertion))
|
||||
.withMessage("clientRegistration.authorizationGrantType must be AuthorizationGrantType.JWT_BEARER");
|
||||
.isThrownBy(() -> new JwtBearerGrantRequest(registration, this.jwtAssertion))
|
||||
.withMessage("clientRegistration.authorizationGrantType must be AuthorizationGrantType.JWT_BEARER");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -61,7 +61,7 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration()
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
|
||||
this.authorizationRequest = TestOAuth2AuthorizationRequests.request().build();
|
||||
this.authorizationResponse = TestOAuth2AuthorizationResponses.success().build();
|
||||
this.authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
|
||||
@@ -83,14 +83,14 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
+ "}\n";
|
||||
// @formatter:on
|
||||
server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.setBody(accessTokenSuccessResponse));
|
||||
.setBody(accessTokenSuccessResponse));
|
||||
server.start();
|
||||
String tokenUri = server.url("/oauth2/token").toString();
|
||||
this.clientRegistrationBuilder.tokenUri(tokenUri);
|
||||
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient
|
||||
.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(this.clientRegistrationBuilder.build(),
|
||||
this.authorizationExchange));
|
||||
.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(this.clientRegistrationBuilder.build(),
|
||||
this.authorizationExchange));
|
||||
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
|
||||
server.shutdown();
|
||||
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
|
||||
@@ -107,12 +107,13 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
public void getTokenResponseWhenRedirectUriMalformedThenThrowIllegalArgumentException() {
|
||||
String redirectUri = "http:\\example.com";
|
||||
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
|
||||
.redirectUri(redirectUri).build();
|
||||
.redirectUri(redirectUri)
|
||||
.build();
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
|
||||
this.authorizationResponse);
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), authorizationExchange)));
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), authorizationExchange)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -120,8 +121,8 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
String tokenUri = "http:\\provider.com\\oauth2\\token";
|
||||
this.clientRegistrationBuilder.tokenUri(tokenUri);
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)));
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -138,15 +139,15 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
// "}\n"; // Make the JSON invalid/malformed
|
||||
// @formatter:on
|
||||
server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.setBody(accessTokenSuccessResponse));
|
||||
.setBody(accessTokenSuccessResponse));
|
||||
server.start();
|
||||
String tokenUri = server.url("/oauth2/token").toString();
|
||||
this.clientRegistrationBuilder.tokenUri(tokenUri);
|
||||
try {
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
|
||||
.withMessageContaining("invalid_token_response");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
|
||||
.withMessageContaining("invalid_token_response");
|
||||
}
|
||||
finally {
|
||||
server.shutdown();
|
||||
@@ -158,8 +159,8 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
String tokenUri = "https://invalid-provider.com/oauth2/token";
|
||||
this.clientRegistrationBuilder.tokenUri(tokenUri);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)));
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -171,15 +172,16 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
+ "}\n";
|
||||
// @formatter:on
|
||||
server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.setResponseCode(500).setBody(accessTokenErrorResponse));
|
||||
.setResponseCode(500)
|
||||
.setBody(accessTokenErrorResponse));
|
||||
server.start();
|
||||
String tokenUri = server.url("/oauth2/token").toString();
|
||||
this.clientRegistrationBuilder.tokenUri(tokenUri);
|
||||
try {
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
|
||||
.withMessageContaining("unauthorized_client");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
|
||||
.withMessageContaining("unauthorized_client");
|
||||
}
|
||||
finally {
|
||||
server.shutdown();
|
||||
@@ -196,9 +198,9 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
this.clientRegistrationBuilder.tokenUri(tokenUri);
|
||||
try {
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
|
||||
.withMessageContaining("server_error");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
|
||||
.withMessageContaining("server_error");
|
||||
}
|
||||
finally {
|
||||
server.shutdown();
|
||||
@@ -217,15 +219,15 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
+ "}\n";
|
||||
// @formatter:on
|
||||
server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.setBody(accessTokenSuccessResponse));
|
||||
.setBody(accessTokenSuccessResponse));
|
||||
server.start();
|
||||
String tokenUri = server.url("/oauth2/token").toString();
|
||||
this.clientRegistrationBuilder.tokenUri(tokenUri);
|
||||
try {
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
|
||||
.withMessageContaining("invalid_token_response");
|
||||
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
|
||||
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
|
||||
.withMessageContaining("invalid_token_response");
|
||||
}
|
||||
finally {
|
||||
server.shutdown();
|
||||
@@ -245,12 +247,13 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
+ "}\n";
|
||||
// @formatter:on
|
||||
server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.setBody(accessTokenSuccessResponse));
|
||||
.setBody(accessTokenSuccessResponse));
|
||||
server.start();
|
||||
String tokenUri = server.url("/oauth2/token").toString();
|
||||
this.clientRegistrationBuilder.tokenUri(tokenUri);
|
||||
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
|
||||
.scope("openid", "profile", "email", "address").build();
|
||||
.scope("openid", "profile", "email", "address")
|
||||
.build();
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
|
||||
this.authorizationResponse);
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(
|
||||
@@ -271,12 +274,13 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
|
||||
+ "}\n";
|
||||
// @formatter:on
|
||||
server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.setBody(accessTokenSuccessResponse));
|
||||
.setBody(accessTokenSuccessResponse));
|
||||
server.start();
|
||||
String tokenUri = server.url("/oauth2/token").toString();
|
||||
this.clientRegistrationBuilder.tokenUri(tokenUri);
|
||||
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
|
||||
.scope("openid", "profile", "email", "address").build();
|
||||
.scope("openid", "profile", "email", "address")
|
||||
.build();
|
||||
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
|
||||
this.authorizationResponse);
|
||||
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(
|
||||
|
||||
@@ -73,20 +73,20 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
|
||||
@Test
|
||||
public void constructorWhenJwkResolverNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> new NimbusJwtClientAuthenticationParametersConverter<>(null))
|
||||
.withMessage("jwkResolver cannot be null");
|
||||
.isThrownBy(() -> new NimbusJwtClientAuthenticationParametersConverter<>(null))
|
||||
.withMessage("jwkResolver cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void convertWhenAuthorizationGrantRequestNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.convert(null))
|
||||
.withMessage("authorizationGrantRequest cannot be null");
|
||||
.withMessage("authorizationGrantRequest cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setJwtClientAssertionCustomizerWhenNullThenThrowIllegalArgumentException() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.converter.setJwtClientAssertionCustomizer(null))
|
||||
.withMessage("jwtClientAssertionCustomizer cannot be null");
|
||||
.withMessage("jwtClientAssertionCustomizer cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -112,9 +112,9 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
|
||||
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
|
||||
clientRegistration);
|
||||
assertThatExceptionOfType(OAuth2AuthorizationException.class)
|
||||
.isThrownBy(() -> this.converter.convert(clientCredentialsGrantRequest))
|
||||
.withMessage("[invalid_key] Failed to resolve JWK signing key for client registration '"
|
||||
+ clientRegistration.getRegistrationId() + "'.");
|
||||
.isThrownBy(() -> this.converter.convert(clientCredentialsGrantRequest))
|
||||
.withMessage("[invalid_key] Failed to resolve JWK signing key for client registration '"
|
||||
+ clientRegistration.getRegistrationId() + "'.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -133,7 +133,7 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
|
||||
MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
|
||||
|
||||
assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE))
|
||||
.isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
|
||||
.isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
|
||||
String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
|
||||
assertThat(encodedJws).isNotNull();
|
||||
|
||||
@@ -145,7 +145,7 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
|
||||
assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
|
||||
assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
|
||||
assertThat(jws.getAudience())
|
||||
.isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
|
||||
.isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
|
||||
assertThat(jws.getId()).isNotNull();
|
||||
assertThat(jws.getIssuedAt()).isNotNull();
|
||||
assertThat(jws.getExpiresAt()).isNotNull();
|
||||
@@ -167,7 +167,7 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
|
||||
MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
|
||||
|
||||
assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE))
|
||||
.isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
|
||||
.isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
|
||||
String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
|
||||
assertThat(encodedJws).isNotNull();
|
||||
|
||||
@@ -179,7 +179,7 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
|
||||
assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
|
||||
assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
|
||||
assertThat(jws.getAudience())
|
||||
.isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
|
||||
.isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
|
||||
assertThat(jws.getId()).isNotNull();
|
||||
assertThat(jws.getIssuedAt()).isNotNull();
|
||||
assertThat(jws.getExpiresAt()).isNotNull();
|
||||
@@ -210,7 +210,7 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
|
||||
MultiValueMap<String, String> parameters = this.converter.convert(clientCredentialsGrantRequest);
|
||||
|
||||
assertThat(parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE))
|
||||
.isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
|
||||
.isEqualTo("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
|
||||
String encodedJws = parameters.getFirst(OAuth2ParameterNames.CLIENT_ASSERTION);
|
||||
assertThat(encodedJws).isNotNull();
|
||||
|
||||
@@ -223,7 +223,7 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
|
||||
assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
|
||||
assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
|
||||
assertThat(jws.getAudience())
|
||||
.isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
|
||||
.isEqualTo(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()));
|
||||
assertThat(jws.getId()).isNotNull();
|
||||
assertThat(jws.getIssuedAt()).isNotNull();
|
||||
assertThat(jws.getExpiresAt()).isNotNull();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user