Use parenthesis with single-arg lambdas
Use regular expression search/replace to ensure all single-arg lambdas have parenthesis. This aligns with the style used in Spring Boot and ensure that single-arg and multi-arg lambdas are consistent. Issue gh-8945
This commit is contained in:
+7
-6
@@ -138,12 +138,13 @@ public final class AuthorizedClientServiceOAuth2AuthorizedClientManager implemen
|
||||
contextBuilder = OAuth2AuthorizationContext.withClientRegistration(clientRegistration);
|
||||
}
|
||||
}
|
||||
OAuth2AuthorizationContext authorizationContext = contextBuilder.principal(principal).attributes(attributes -> {
|
||||
Map<String, Object> contextAttributes = this.contextAttributesMapper.apply(authorizeRequest);
|
||||
if (!CollectionUtils.isEmpty(contextAttributes)) {
|
||||
attributes.putAll(contextAttributes);
|
||||
}
|
||||
}).build();
|
||||
OAuth2AuthorizationContext authorizationContext = contextBuilder.principal(principal)
|
||||
.attributes((attributes) -> {
|
||||
Map<String, Object> contextAttributes = this.contextAttributesMapper.apply(authorizeRequest);
|
||||
if (!CollectionUtils.isEmpty(contextAttributes)) {
|
||||
attributes.putAll(contextAttributes);
|
||||
}
|
||||
}).build();
|
||||
|
||||
try {
|
||||
authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
|
||||
|
||||
+7
-7
@@ -122,7 +122,7 @@ public final class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager
|
||||
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) {
|
||||
@@ -132,18 +132,18 @@ public final class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager
|
||||
.map(OAuth2AuthorizationContext::withAuthorizedClient)
|
||||
.switchIfEmpty(Mono.defer(() -> this.clientRegistrationRepository
|
||||
.findByRegistrationId(clientRegistrationId)
|
||||
.flatMap(clientRegistration -> this.authorizedClientService
|
||||
.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 -> {
|
||||
.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));
|
||||
builder = builder.attributes((attributes) -> attributes.putAll(contextAttributes));
|
||||
}
|
||||
return builder.build();
|
||||
}));
|
||||
@@ -165,12 +165,12 @@ public final class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager
|
||||
return this.authorizedClientProvider.authorize(authorizationContext)
|
||||
// Delegate to the authorizationSuccessHandler of the successful
|
||||
// authorization
|
||||
.flatMap(authorizedClient -> this.authorizationSuccessHandler
|
||||
.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
|
||||
(authorizationException) -> this.authorizationFailureHandler
|
||||
.onAuthorizationFailure(authorizationException, principal, Collections.emptyMap())
|
||||
.then(Mono.error(authorizationException)))
|
||||
.switchIfEmpty(Mono.defer(() -> Mono.justOrEmpty(authorizationContext.getAuthorizedClient())));
|
||||
|
||||
+3
-2
@@ -87,8 +87,9 @@ public final class ClientCredentialsReactiveOAuth2AuthorizedClientProvider
|
||||
return Mono.just(new OAuth2ClientCredentialsGrantRequest(clientRegistration))
|
||||
.flatMap(this.accessTokenResponseClient::getTokenResponse)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
e -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(), e))
|
||||
.map(tokenResponse -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
|
||||
(e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(),
|
||||
e))
|
||||
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
|
||||
tokenResponse.getAccessToken()));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -73,7 +73,7 @@ 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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+3
-3
@@ -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
|
||||
@@ -82,7 +82,7 @@ public final class InMemoryReactiveOAuth2AuthorizedClientService implements Reac
|
||||
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
|
||||
Assert.hasText(principalName, "principalName cannot be empty");
|
||||
return this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)
|
||||
.map(clientRegistration -> new OAuth2AuthorizedClientId(clientRegistrationId, principalName))
|
||||
.map((clientRegistration) -> new OAuth2AuthorizedClientId(clientRegistrationId, principalName))
|
||||
.doOnNext(this.authorizedClients::remove).then(Mono.empty());
|
||||
}
|
||||
|
||||
|
||||
+9
-9
@@ -73,7 +73,7 @@ public final class OAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
public OAuth2AuthorizedClientProviderBuilder provider(OAuth2AuthorizedClientProvider provider) {
|
||||
Assert.notNull(provider, "provider cannot be null");
|
||||
this.builders.computeIfAbsent(provider.getClass(), k -> () -> provider);
|
||||
this.builders.computeIfAbsent(provider.getClass(), (k) -> () -> provider);
|
||||
return OAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ public final class OAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
public OAuth2AuthorizedClientProviderBuilder authorizationCode() {
|
||||
this.builders.computeIfAbsent(AuthorizationCodeOAuth2AuthorizedClientProvider.class,
|
||||
k -> new AuthorizationCodeGrantBuilder());
|
||||
(k) -> new AuthorizationCodeGrantBuilder());
|
||||
return OAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ public final class OAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
public OAuth2AuthorizedClientProviderBuilder refreshToken() {
|
||||
this.builders.computeIfAbsent(RefreshTokenOAuth2AuthorizedClientProvider.class,
|
||||
k -> new RefreshTokenGrantBuilder());
|
||||
(k) -> new RefreshTokenGrantBuilder());
|
||||
return OAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -116,7 +116,7 @@ public final class OAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
public OAuth2AuthorizedClientProviderBuilder clientCredentials() {
|
||||
this.builders.computeIfAbsent(ClientCredentialsOAuth2AuthorizedClientProvider.class,
|
||||
k -> new ClientCredentialsGrantBuilder());
|
||||
(k) -> new ClientCredentialsGrantBuilder());
|
||||
return OAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ public final class OAuth2AuthorizedClientProviderBuilder {
|
||||
public OAuth2AuthorizedClientProviderBuilder clientCredentials(
|
||||
Consumer<ClientCredentialsGrantBuilder> builderConsumer) {
|
||||
ClientCredentialsGrantBuilder builder = (ClientCredentialsGrantBuilder) this.builders.computeIfAbsent(
|
||||
ClientCredentialsOAuth2AuthorizedClientProvider.class, k -> new ClientCredentialsGrantBuilder());
|
||||
ClientCredentialsOAuth2AuthorizedClientProvider.class, (k) -> new ClientCredentialsGrantBuilder());
|
||||
builderConsumer.accept(builder);
|
||||
return OAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
@@ -139,7 +139,7 @@ public final class OAuth2AuthorizedClientProviderBuilder {
|
||||
* @return the {@link OAuth2AuthorizedClientProviderBuilder}
|
||||
*/
|
||||
public OAuth2AuthorizedClientProviderBuilder password() {
|
||||
this.builders.computeIfAbsent(PasswordOAuth2AuthorizedClientProvider.class, k -> new PasswordGrantBuilder());
|
||||
this.builders.computeIfAbsent(PasswordOAuth2AuthorizedClientProvider.class, (k) -> new PasswordGrantBuilder());
|
||||
return OAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ public final class OAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
+3
-2
@@ -111,8 +111,9 @@ public final class PasswordReactiveOAuth2AuthorizedClientProvider implements Rea
|
||||
|
||||
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(),
|
||||
(e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(),
|
||||
e))
|
||||
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
|
||||
tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()));
|
||||
}
|
||||
|
||||
|
||||
+9
-9
@@ -73,7 +73,7 @@ public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
public ReactiveOAuth2AuthorizedClientProviderBuilder provider(ReactiveOAuth2AuthorizedClientProvider provider) {
|
||||
Assert.notNull(provider, "provider cannot be null");
|
||||
this.builders.computeIfAbsent(provider.getClass(), k -> () -> provider);
|
||||
this.builders.computeIfAbsent(provider.getClass(), (k) -> () -> provider);
|
||||
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
public ReactiveOAuth2AuthorizedClientProviderBuilder authorizationCode() {
|
||||
this.builders.computeIfAbsent(AuthorizationCodeReactiveOAuth2AuthorizedClientProvider.class,
|
||||
k -> new AuthorizationCodeGrantBuilder());
|
||||
(k) -> new AuthorizationCodeGrantBuilder());
|
||||
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
public ReactiveOAuth2AuthorizedClientProviderBuilder refreshToken() {
|
||||
this.builders.computeIfAbsent(RefreshTokenReactiveOAuth2AuthorizedClientProvider.class,
|
||||
k -> new RefreshTokenGrantBuilder());
|
||||
(k) -> new RefreshTokenGrantBuilder());
|
||||
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
|
||||
public ReactiveOAuth2AuthorizedClientProviderBuilder refreshToken(
|
||||
Consumer<RefreshTokenGrantBuilder> builderConsumer) {
|
||||
RefreshTokenGrantBuilder builder = (RefreshTokenGrantBuilder) this.builders.computeIfAbsent(
|
||||
RefreshTokenReactiveOAuth2AuthorizedClientProvider.class, k -> new RefreshTokenGrantBuilder());
|
||||
RefreshTokenReactiveOAuth2AuthorizedClientProvider.class, (k) -> new RefreshTokenGrantBuilder());
|
||||
builderConsumer.accept(builder);
|
||||
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
@@ -117,7 +117,7 @@ public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
public ReactiveOAuth2AuthorizedClientProviderBuilder clientCredentials() {
|
||||
this.builders.computeIfAbsent(ClientCredentialsReactiveOAuth2AuthorizedClientProvider.class,
|
||||
k -> new ClientCredentialsGrantBuilder());
|
||||
(k) -> new ClientCredentialsGrantBuilder());
|
||||
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
|
||||
Consumer<ClientCredentialsGrantBuilder> builderConsumer) {
|
||||
ClientCredentialsGrantBuilder builder = (ClientCredentialsGrantBuilder) this.builders.computeIfAbsent(
|
||||
ClientCredentialsReactiveOAuth2AuthorizedClientProvider.class,
|
||||
k -> new ClientCredentialsGrantBuilder());
|
||||
(k) -> new ClientCredentialsGrantBuilder());
|
||||
builderConsumer.accept(builder);
|
||||
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
@@ -142,7 +142,7 @@ public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
|
||||
*/
|
||||
public ReactiveOAuth2AuthorizedClientProviderBuilder password() {
|
||||
this.builders.computeIfAbsent(PasswordReactiveOAuth2AuthorizedClientProvider.class,
|
||||
k -> new PasswordGrantBuilder());
|
||||
(k) -> new PasswordGrantBuilder());
|
||||
return ReactiveOAuth2AuthorizedClientProviderBuilder.this;
|
||||
}
|
||||
|
||||
@@ -153,8 +153,8 @@ public final class ReactiveOAuth2AuthorizedClientProviderBuilder {
|
||||
* @return the {@link ReactiveOAuth2AuthorizedClientProviderBuilder}
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
+3
-2
@@ -98,8 +98,9 @@ public final class RefreshTokenReactiveOAuth2AuthorizedClientProvider
|
||||
|
||||
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(),
|
||||
(e) -> new ClientAuthorizationException(e.getError(), clientRegistration.getRegistrationId(),
|
||||
e))
|
||||
.map((tokenResponse) -> new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(),
|
||||
tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -107,7 +107,7 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManager implements Rea
|
||||
|
||||
private Function<OAuth2AccessTokenResponse, OAuth2AuthorizationCodeAuthenticationToken> onSuccess(
|
||||
OAuth2AuthorizationCodeAuthenticationToken token) {
|
||||
return accessTokenResponse -> {
|
||||
return (accessTokenResponse) -> {
|
||||
ClientRegistration registration = token.getClientRegistration();
|
||||
OAuth2AuthorizationExchange exchange = token.getAuthorizationExchange();
|
||||
OAuth2AccessToken accessToken = accessTokenResponse.getAccessToken();
|
||||
|
||||
+1
-1
@@ -70,7 +70,7 @@ public class OAuth2LoginAuthenticationProvider implements AuthenticationProvider
|
||||
|
||||
private final OAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
|
||||
|
||||
private GrantedAuthoritiesMapper authoritiesMapper = (authorities -> authorities);
|
||||
private GrantedAuthoritiesMapper authoritiesMapper = ((authorities) -> authorities);
|
||||
|
||||
/**
|
||||
* Constructs an {@code OAuth2LoginAuthenticationProvider} using the provided
|
||||
|
||||
+3
-3
@@ -72,7 +72,7 @@ public class OAuth2LoginReactiveAuthenticationManager implements ReactiveAuthent
|
||||
|
||||
private final ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
|
||||
|
||||
private GrantedAuthoritiesMapper authoritiesMapper = (authorities -> authorities);
|
||||
private GrantedAuthoritiesMapper authoritiesMapper = ((authorities) -> authorities);
|
||||
|
||||
public OAuth2LoginReactiveAuthenticationManager(
|
||||
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient,
|
||||
@@ -102,7 +102,7 @@ public class OAuth2LoginReactiveAuthenticationManager implements ReactiveAuthent
|
||||
|
||||
return this.authorizationCodeManager.authenticate(token)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
e -> new OAuth2AuthenticationException(e.getError(), e.getError().toString()))
|
||||
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString()))
|
||||
.cast(OAuth2AuthorizationCodeAuthenticationToken.class).flatMap(this::onSuccess);
|
||||
});
|
||||
}
|
||||
@@ -125,7 +125,7 @@ public class OAuth2LoginReactiveAuthenticationManager implements ReactiveAuthent
|
||||
Map<String, Object> additionalParameters = authentication.getAdditionalParameters();
|
||||
OAuth2UserRequest userRequest = new OAuth2UserRequest(authentication.getClientRegistration(), accessToken,
|
||||
additionalParameters);
|
||||
return this.userService.loadUser(userRequest).map(oauth2User -> {
|
||||
return this.userService.loadUser(userRequest).map((oauth2User) -> {
|
||||
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
|
||||
.mapAuthorities(oauth2User.getAuthorities());
|
||||
|
||||
|
||||
+3
-3
@@ -67,9 +67,9 @@ abstract class AbstractWebClientReactiveOAuth2AccessTokenResponseClient<T extend
|
||||
Assert.notNull(grantRequest, "grantRequest cannot be null");
|
||||
return Mono.defer(
|
||||
() -> this.webClient.post().uri(clientRegistration(grantRequest).getProviderDetails().getTokenUri())
|
||||
.headers(headers -> populateTokenRequestHeaders(grantRequest, headers))
|
||||
.headers((headers) -> populateTokenRequestHeaders(grantRequest, headers))
|
||||
.body(createTokenRequestBody(grantRequest)).exchange()
|
||||
.flatMap(response -> readTokenResponse(grantRequest, response)));
|
||||
.flatMap((response) -> readTokenResponse(grantRequest, response)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -170,7 +170,7 @@ abstract class AbstractWebClientReactiveOAuth2AccessTokenResponseClient<T extend
|
||||
*/
|
||||
private Mono<OAuth2AccessTokenResponse> readTokenResponse(T grantRequest, ClientResponse response) {
|
||||
return response.body(OAuth2BodyExtractors.oauth2AccessTokenResponse())
|
||||
.map(tokenResponse -> populateTokenResponse(grantRequest, tokenResponse));
|
||||
.map((tokenResponse) -> populateTokenResponse(grantRequest, tokenResponse));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -97,7 +97,7 @@ public class OidcAuthorizationCodeAuthenticationProvider implements Authenticati
|
||||
|
||||
private JwtDecoderFactory<ClientRegistration> jwtDecoderFactory = new OidcIdTokenDecoderFactory();
|
||||
|
||||
private GrantedAuthoritiesMapper authoritiesMapper = (authorities -> authorities);
|
||||
private GrantedAuthoritiesMapper authoritiesMapper = ((authorities) -> authorities);
|
||||
|
||||
/**
|
||||
* Constructs an {@code OidcAuthorizationCodeAuthenticationProvider} using the
|
||||
|
||||
+8
-8
@@ -97,7 +97,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManager implements React
|
||||
|
||||
private final ReactiveOAuth2UserService<OidcUserRequest, OidcUser> userService;
|
||||
|
||||
private GrantedAuthoritiesMapper authoritiesMapper = (authorities -> authorities);
|
||||
private GrantedAuthoritiesMapper authoritiesMapper = ((authorities) -> authorities);
|
||||
|
||||
private ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = new ReactiveOidcIdTokenDecoderFactory();
|
||||
|
||||
@@ -146,10 +146,10 @@ public class OidcAuthorizationCodeReactiveAuthenticationManager implements React
|
||||
authorizationCodeAuthentication.getAuthorizationExchange());
|
||||
|
||||
return this.accessTokenResponseClient.getTokenResponse(authzRequest).flatMap(
|
||||
accessTokenResponse -> authenticationResult(authorizationCodeAuthentication, accessTokenResponse))
|
||||
(accessTokenResponse) -> authenticationResult(authorizationCodeAuthentication, accessTokenResponse))
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
e -> new OAuth2AuthenticationException(e.getError(), e.getError().toString()))
|
||||
.onErrorMap(JwtException.class, e -> {
|
||||
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString()))
|
||||
.onErrorMap(JwtException.class, (e) -> {
|
||||
OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, e.getMessage(),
|
||||
null);
|
||||
return new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(),
|
||||
@@ -200,9 +200,9 @@ public class OidcAuthorizationCodeReactiveAuthenticationManager implements React
|
||||
}
|
||||
|
||||
return createOidcToken(clientRegistration, accessTokenResponse)
|
||||
.doOnNext(idToken -> validateNonce(authorizationCodeAuthentication, idToken))
|
||||
.map(idToken -> new OidcUserRequest(clientRegistration, accessToken, idToken, additionalParameters))
|
||||
.flatMap(this.userService::loadUser).map(oauth2User -> {
|
||||
.doOnNext((idToken) -> validateNonce(authorizationCodeAuthentication, idToken))
|
||||
.map((idToken) -> new OidcUserRequest(clientRegistration, accessToken, idToken, additionalParameters))
|
||||
.flatMap(this.userService::loadUser).map((oauth2User) -> {
|
||||
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
|
||||
.mapAuthorities(oauth2User.getAuthorities());
|
||||
|
||||
@@ -217,7 +217,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManager implements React
|
||||
ReactiveJwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(clientRegistration);
|
||||
String rawIdToken = (String) accessTokenResponse.getAdditionalParameters().get(OidcParameterNames.ID_TOKEN);
|
||||
return jwtDecoder.decode(rawIdToken).map(
|
||||
jwt -> new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), jwt.getClaims()));
|
||||
(jwt) -> new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), jwt.getClaims()));
|
||||
}
|
||||
|
||||
private static Mono<OidcIdToken> validateNonce(
|
||||
|
||||
+7
-4
@@ -81,9 +81,11 @@ public final class OidcIdTokenDecoderFactory implements JwtDecoderFactory<Client
|
||||
|
||||
private Function<ClientRegistration, OAuth2TokenValidator<Jwt>> jwtValidatorFactory = new DefaultOidcIdTokenValidatorFactory();
|
||||
|
||||
private Function<ClientRegistration, JwsAlgorithm> jwsAlgorithmResolver = clientRegistration -> SignatureAlgorithm.RS256;
|
||||
private Function<ClientRegistration, JwsAlgorithm> jwsAlgorithmResolver = (
|
||||
clientRegistration) -> SignatureAlgorithm.RS256;
|
||||
|
||||
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = clientRegistration -> DEFAULT_CLAIM_TYPE_CONVERTER;
|
||||
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = (
|
||||
clientRegistration) -> DEFAULT_CLAIM_TYPE_CONVERTER;
|
||||
|
||||
/**
|
||||
* Returns the default {@link Converter}'s used for type conversion of claim values
|
||||
@@ -115,13 +117,14 @@ public final class OidcIdTokenDecoderFactory implements JwtDecoderFactory<Client
|
||||
|
||||
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
|
||||
public JwtDecoder createDecoder(ClientRegistration clientRegistration) {
|
||||
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
|
||||
return this.jwtDecoders.computeIfAbsent(clientRegistration.getRegistrationId(), key -> {
|
||||
return this.jwtDecoders.computeIfAbsent(clientRegistration.getRegistrationId(), (key) -> {
|
||||
NimbusJwtDecoder jwtDecoder = buildDecoder(clientRegistration);
|
||||
jwtDecoder.setJwtValidator(this.jwtValidatorFactory.apply(clientRegistration));
|
||||
Converter<Map<String, Object>, Map<String, Object>> claimTypeConverter = this.claimTypeConverterFactory
|
||||
|
||||
+7
-4
@@ -81,9 +81,11 @@ public final class ReactiveOidcIdTokenDecoderFactory implements ReactiveJwtDecod
|
||||
|
||||
private Function<ClientRegistration, OAuth2TokenValidator<Jwt>> jwtValidatorFactory = new DefaultOidcIdTokenValidatorFactory();
|
||||
|
||||
private Function<ClientRegistration, JwsAlgorithm> jwsAlgorithmResolver = clientRegistration -> SignatureAlgorithm.RS256;
|
||||
private Function<ClientRegistration, JwsAlgorithm> jwsAlgorithmResolver = (
|
||||
clientRegistration) -> SignatureAlgorithm.RS256;
|
||||
|
||||
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = clientRegistration -> DEFAULT_CLAIM_TYPE_CONVERTER;
|
||||
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = (
|
||||
clientRegistration) -> DEFAULT_CLAIM_TYPE_CONVERTER;
|
||||
|
||||
/**
|
||||
* Returns the default {@link Converter}'s used for type conversion of claim values
|
||||
@@ -115,13 +117,14 @@ 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
|
||||
public ReactiveJwtDecoder createDecoder(ClientRegistration clientRegistration) {
|
||||
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
|
||||
return this.jwtDecoders.computeIfAbsent(clientRegistration.getRegistrationId(), key -> {
|
||||
return this.jwtDecoders.computeIfAbsent(clientRegistration.getRegistrationId(), (key) -> {
|
||||
NimbusReactiveJwtDecoder jwtDecoder = buildDecoder(clientRegistration);
|
||||
jwtDecoder.setJwtValidator(this.jwtValidatorFactory.apply(clientRegistration));
|
||||
Converter<Map<String, Object>, Map<String, Object>> claimTypeConverter = this.claimTypeConverterFactory
|
||||
|
||||
+8
-6
@@ -68,7 +68,8 @@ public class OidcReactiveOAuth2UserService implements ReactiveOAuth2UserService<
|
||||
|
||||
private ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService = new DefaultReactiveOAuth2UserService();
|
||||
|
||||
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = clientRegistration -> DEFAULT_CLAIM_TYPE_CONVERTER;
|
||||
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = (
|
||||
clientRegistration) -> DEFAULT_CLAIM_TYPE_CONVERTER;
|
||||
|
||||
/**
|
||||
* Returns the default {@link Converter}'s used for type conversion of claim values
|
||||
@@ -90,14 +91,15 @@ 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
|
||||
public Mono<OidcUser> loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
|
||||
Assert.notNull(userRequest, "userRequest cannot be null");
|
||||
return getUserInfo(userRequest).map(userInfo -> new OidcUserAuthority(userRequest.getIdToken(), userInfo))
|
||||
.defaultIfEmpty(new OidcUserAuthority(userRequest.getIdToken(), null)).map(authority -> {
|
||||
return getUserInfo(userRequest).map((userInfo) -> new OidcUserAuthority(userRequest.getIdToken(), userInfo))
|
||||
.defaultIfEmpty(new OidcUserAuthority(userRequest.getIdToken(), null)).map((authority) -> {
|
||||
OidcUserInfo userInfo = authority.getUserInfo();
|
||||
Set<GrantedAuthority> authorities = new HashSet<>();
|
||||
authorities.add(authority);
|
||||
@@ -123,8 +125,8 @@ public class OidcReactiveOAuth2UserService implements ReactiveOAuth2UserService<
|
||||
}
|
||||
|
||||
return this.oauth2UserService.loadUser(userRequest).map(OAuth2User::getAttributes)
|
||||
.map(claims -> convertClaims(claims, userRequest.getClientRegistration())).map(OidcUserInfo::new)
|
||||
.doOnNext(userInfo -> {
|
||||
.map((claims) -> convertClaims(claims, userRequest.getClientRegistration())).map(OidcUserInfo::new)
|
||||
.doOnNext((userInfo) -> {
|
||||
String subject = userInfo.getSubject();
|
||||
if (subject == null || !subject.equals(userRequest.getIdToken().getSubject())) {
|
||||
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE);
|
||||
|
||||
+4
-2
@@ -74,7 +74,8 @@ public class OidcUserService implements OAuth2UserService<OidcUserRequest, OidcU
|
||||
|
||||
private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService = new DefaultOAuth2UserService();
|
||||
|
||||
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = clientRegistration -> DEFAULT_CLAIM_TYPE_CONVERTER;
|
||||
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = (
|
||||
clientRegistration) -> DEFAULT_CLAIM_TYPE_CONVERTER;
|
||||
|
||||
/**
|
||||
* Returns the default {@link Converter}'s used for type conversion of claim values
|
||||
@@ -96,7 +97,8 @@ public class OidcUserService implements OAuth2UserService<OidcUserRequest, OidcU
|
||||
|
||||
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
|
||||
|
||||
+3
-3
@@ -77,10 +77,10 @@ public class OidcClientInitiatedServerLogoutSuccessHandler implements ServerLogo
|
||||
@Override
|
||||
public Mono<Void> onLogoutSuccess(WebFilterExchange exchange, Authentication authentication) {
|
||||
return Mono.just(authentication).filter(OAuth2AuthenticationToken.class::isInstance)
|
||||
.filter(token -> authentication.getPrincipal() instanceof OidcUser)
|
||||
.filter((token) -> authentication.getPrincipal() instanceof OidcUser)
|
||||
.map(OAuth2AuthenticationToken.class::cast)
|
||||
.map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId)
|
||||
.flatMap(this.clientRegistrationRepository::findByRegistrationId).flatMap(clientRegistration -> {
|
||||
.flatMap(this.clientRegistrationRepository::findByRegistrationId).flatMap((clientRegistration) -> {
|
||||
URI endSessionEndpoint = endSessionEndpoint(clientRegistration);
|
||||
if (endSessionEndpoint == null) {
|
||||
return Mono.empty();
|
||||
@@ -91,7 +91,7 @@ public class OidcClientInitiatedServerLogoutSuccessHandler implements ServerLogo
|
||||
})
|
||||
.switchIfEmpty(
|
||||
this.serverLogoutSuccessHandler.onLogoutSuccess(exchange, authentication).then(Mono.empty()))
|
||||
.flatMap(endpointUri -> this.redirectStrategy.sendRedirect(exchange.getExchange(), endpointUri));
|
||||
.flatMap((endpointUri) -> this.redirectStrategy.sendRedirect(exchange.getExchange(), endpointUri));
|
||||
}
|
||||
|
||||
private URI endSessionEndpoint(ClientRegistration clientRegistration) {
|
||||
|
||||
+1
-1
@@ -703,7 +703,7 @@ public final class ClientRegistration implements Serializable {
|
||||
}
|
||||
|
||||
private static boolean validateScope(String scope) {
|
||||
return scope == null || scope.chars().allMatch(c -> withinTheRangeOf(c, 0x21, 0x21)
|
||||
return scope == null || scope.chars().allMatch((c) -> withinTheRangeOf(c, 0x21, 0x21)
|
||||
|| withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
|
||||
}
|
||||
|
||||
|
||||
+8
-7
@@ -115,17 +115,17 @@ public class DefaultReactiveOAuth2UserService implements ReactiveOAuth2UserServi
|
||||
else {
|
||||
requestHeadersSpec = this.webClient.get().uri(userInfoUri)
|
||||
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.headers(headers -> headers.setBearerAuth(userRequest.getAccessToken().getTokenValue()));
|
||||
.headers((headers) -> headers.setBearerAuth(userRequest.getAccessToken().getTokenValue()));
|
||||
}
|
||||
Mono<Map<String, Object>> userAttributes = requestHeadersSpec.retrieve()
|
||||
.onStatus(s -> s != HttpStatus.OK, response -> parse(response).map(userInfoErrorResponse -> {
|
||||
.onStatus((s) -> s != HttpStatus.OK, (response) -> parse(response).map((userInfoErrorResponse) -> {
|
||||
String description = userInfoErrorResponse.getErrorObject().getDescription();
|
||||
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, description,
|
||||
null);
|
||||
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
|
||||
})).bodyToMono(typeReference);
|
||||
|
||||
return userAttributes.map(attrs -> {
|
||||
return userAttributes.map((attrs) -> {
|
||||
GrantedAuthority authority = new OAuth2UserAuthority(attrs);
|
||||
Set<GrantedAuthority> authorities = new HashSet<>();
|
||||
authorities.add(authority);
|
||||
@@ -136,8 +136,9 @@ public class DefaultReactiveOAuth2UserService implements ReactiveOAuth2UserServi
|
||||
|
||||
return new DefaultOAuth2User(authorities, attrs, userNameAttributeName);
|
||||
}).onErrorMap(IOException.class,
|
||||
e -> new AuthenticationServiceException("Unable to access the userInfoEndpoint " + userInfoUri, e))
|
||||
.onErrorMap(UnsupportedMediaTypeException.class, e -> {
|
||||
(e) -> new AuthenticationServiceException("Unable to access the userInfoEndpoint " + userInfoUri,
|
||||
e))
|
||||
.onErrorMap(UnsupportedMediaTypeException.class, (e) -> {
|
||||
String errorMessage = "An error occurred while attempting to retrieve the UserInfo Resource from '"
|
||||
+ userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint()
|
||||
.getUri()
|
||||
@@ -151,7 +152,7 @@ public class DefaultReactiveOAuth2UserService implements ReactiveOAuth2UserServi
|
||||
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, errorMessage,
|
||||
null);
|
||||
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), e);
|
||||
}).onErrorMap(t -> !(t instanceof AuthenticationServiceException), t -> {
|
||||
}).onErrorMap((t) -> !(t instanceof AuthenticationServiceException), (t) -> {
|
||||
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE,
|
||||
"An error occurred reading the UserInfo Success response: " + t.getMessage(), null);
|
||||
return new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), t);
|
||||
@@ -181,7 +182,7 @@ public class DefaultReactiveOAuth2UserService implements ReactiveOAuth2UserServi
|
||||
};
|
||||
// Other error?
|
||||
return httpResponse.bodyToMono(typeReference)
|
||||
.map(body -> new UserInfoErrorResponse(ErrorObject.parse(new JSONObject(body))));
|
||||
.map((body) -> new UserInfoErrorResponse(ErrorObject.parse(new JSONObject(body))));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -58,8 +58,8 @@ public class DelegatingOAuth2UserService<R extends OAuth2UserRequest, U extends
|
||||
@Override
|
||||
public U loadUser(R userRequest) throws OAuth2AuthenticationException {
|
||||
Assert.notNull(userRequest, "userRequest cannot be null");
|
||||
return this.userServices.stream().map(userService -> userService.loadUser(userRequest)).filter(Objects::nonNull)
|
||||
.findFirst().orElse(null);
|
||||
return this.userServices.stream().map((userService) -> userService.loadUser(userRequest))
|
||||
.filter(Objects::nonNull).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -79,7 +79,7 @@ public final class DefaultOAuth2AuthorizationRequestResolver implements OAuth2Au
|
||||
private final StringKeyGenerator secureKeyGenerator = new Base64StringKeyGenerator(
|
||||
Base64.getUrlEncoder().withoutPadding(), 96);
|
||||
|
||||
private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer = customizer -> {
|
||||
private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer = (customizer) -> {
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+7
-6
@@ -159,12 +159,13 @@ public final class DefaultOAuth2AuthorizedClientManager implements OAuth2Authori
|
||||
contextBuilder = OAuth2AuthorizationContext.withClientRegistration(clientRegistration);
|
||||
}
|
||||
}
|
||||
OAuth2AuthorizationContext authorizationContext = contextBuilder.principal(principal).attributes(attributes -> {
|
||||
Map<String, Object> contextAttributes = this.contextAttributesMapper.apply(authorizeRequest);
|
||||
if (!CollectionUtils.isEmpty(contextAttributes)) {
|
||||
attributes.putAll(contextAttributes);
|
||||
}
|
||||
}).build();
|
||||
OAuth2AuthorizationContext authorizationContext = contextBuilder.principal(principal)
|
||||
.attributes((attributes) -> {
|
||||
Map<String, Object> contextAttributes = this.contextAttributesMapper.apply(authorizeRequest);
|
||||
if (!CollectionUtils.isEmpty(contextAttributes)) {
|
||||
attributes.putAll(contextAttributes);
|
||||
}
|
||||
}).build();
|
||||
|
||||
try {
|
||||
authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
|
||||
|
||||
+23
-22
@@ -97,7 +97,7 @@ public final class DefaultReactiveOAuth2AuthorizedClientManager implements React
|
||||
.builder().authorizationCode().refreshToken().clientCredentials().password().build();
|
||||
|
||||
private static final Mono<ServerWebExchange> currentServerWebExchangeMono = Mono.subscriberContext()
|
||||
.filter(c -> c.hasKey(ServerWebExchange.class)).map(c -> c.get(ServerWebExchange.class));
|
||||
.filter((c) -> c.hasKey(ServerWebExchange.class)).map((c) -> c.get(ServerWebExchange.class));
|
||||
|
||||
private final ReactiveClientRegistrationRepository clientRegistrationRepository;
|
||||
|
||||
@@ -143,13 +143,13 @@ public final class DefaultReactiveOAuth2AuthorizedClientManager implements React
|
||||
return Mono.justOrEmpty(authorizeRequest.<ServerWebExchange>getAttribute(ServerWebExchange.class.getName()))
|
||||
.switchIfEmpty(currentServerWebExchangeMono)
|
||||
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException("serverWebExchange cannot be null")))
|
||||
.flatMap(serverWebExchange -> Mono.justOrEmpty(authorizeRequest.getAuthorizedClient())
|
||||
.flatMap((serverWebExchange) -> Mono.justOrEmpty(authorizeRequest.getAuthorizedClient())
|
||||
.switchIfEmpty(Mono
|
||||
.defer(() -> loadAuthorizedClient(clientRegistrationId, principal, serverWebExchange)))
|
||||
.flatMap(authorizedClient -> {
|
||||
.flatMap((authorizedClient) -> {
|
||||
// Re-authorize
|
||||
return authorizationContext(authorizeRequest, authorizedClient)
|
||||
.flatMap(authorizationContext -> authorize(authorizationContext, principal,
|
||||
.flatMap((authorizationContext) -> authorize(authorizationContext, principal,
|
||||
serverWebExchange))
|
||||
// Default to the existing authorizedClient if the
|
||||
// client was not re-authorized
|
||||
@@ -160,9 +160,9 @@ public final class DefaultReactiveOAuth2AuthorizedClientManager implements React
|
||||
this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)
|
||||
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(
|
||||
"Could not find ClientRegistration with id '" + clientRegistrationId + "'")))
|
||||
.flatMap(clientRegistration -> authorizationContext(authorizeRequest,
|
||||
.flatMap((clientRegistration) -> authorizationContext(authorizeRequest,
|
||||
clientRegistration))
|
||||
.flatMap(authorizationContext -> authorize(authorizationContext, principal,
|
||||
.flatMap((authorizationContext) -> authorize(authorizationContext, principal,
|
||||
serverWebExchange)))));
|
||||
}
|
||||
|
||||
@@ -189,12 +189,12 @@ public final class DefaultReactiveOAuth2AuthorizedClientManager implements React
|
||||
return this.authorizedClientProvider.authorize(authorizationContext)
|
||||
// Delegate to the authorizationSuccessHandler of the successful
|
||||
// authorization
|
||||
.flatMap(authorizedClient -> this.authorizationSuccessHandler
|
||||
.flatMap((authorizedClient) -> this.authorizationSuccessHandler
|
||||
.onAuthorizationSuccess(authorizedClient, principal, createAttributes(serverWebExchange))
|
||||
.thenReturn(authorizedClient))
|
||||
// Delegate to the authorizationFailureHandler of the failed authorization
|
||||
.onErrorResume(OAuth2AuthorizationException.class,
|
||||
authorizationException -> this.authorizationFailureHandler
|
||||
(authorizationException) -> this.authorizationFailureHandler
|
||||
.onAuthorizationFailure(authorizationException, principal,
|
||||
createAttributes(serverWebExchange))
|
||||
.then(Mono.error(authorizationException)));
|
||||
@@ -207,8 +207,8 @@ public final class DefaultReactiveOAuth2AuthorizedClientManager implements React
|
||||
private Mono<OAuth2AuthorizationContext> authorizationContext(OAuth2AuthorizeRequest authorizeRequest,
|
||||
OAuth2AuthorizedClient authorizedClient) {
|
||||
return Mono.just(authorizeRequest).flatMap(this.contextAttributesMapper)
|
||||
.map(attrs -> OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient)
|
||||
.principal(authorizeRequest.getPrincipal()).attributes(attributes -> {
|
||||
.map((attrs) -> OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient)
|
||||
.principal(authorizeRequest.getPrincipal()).attributes((attributes) -> {
|
||||
if (!CollectionUtils.isEmpty(attrs)) {
|
||||
attributes.putAll(attrs);
|
||||
}
|
||||
@@ -218,8 +218,8 @@ public final class DefaultReactiveOAuth2AuthorizedClientManager implements React
|
||||
private Mono<OAuth2AuthorizationContext> authorizationContext(OAuth2AuthorizeRequest authorizeRequest,
|
||||
ClientRegistration clientRegistration) {
|
||||
return Mono.just(authorizeRequest).flatMap(this.contextAttributesMapper)
|
||||
.map(attrs -> OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
|
||||
.principal(authorizeRequest.getPrincipal()).attributes(attributes -> {
|
||||
.map((attrs) -> OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
|
||||
.principal(authorizeRequest.getPrincipal()).attributes((attributes) -> {
|
||||
if (!CollectionUtils.isEmpty(attrs)) {
|
||||
attributes.putAll(attrs);
|
||||
}
|
||||
@@ -291,16 +291,17 @@ public final class DefaultReactiveOAuth2AuthorizedClientManager implements React
|
||||
@Override
|
||||
public Mono<Map<String, Object>> apply(OAuth2AuthorizeRequest authorizeRequest) {
|
||||
ServerWebExchange serverWebExchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
|
||||
return Mono.justOrEmpty(serverWebExchange).switchIfEmpty(currentServerWebExchangeMono).flatMap(exchange -> {
|
||||
Map<String, Object> contextAttributes = Collections.emptyMap();
|
||||
String scope = exchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.SCOPE);
|
||||
if (StringUtils.hasText(scope)) {
|
||||
contextAttributes = new HashMap<>();
|
||||
contextAttributes.put(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME,
|
||||
StringUtils.delimitedListToStringArray(scope, " "));
|
||||
}
|
||||
return Mono.just(contextAttributes);
|
||||
}).defaultIfEmpty(Collections.emptyMap());
|
||||
return Mono.justOrEmpty(serverWebExchange).switchIfEmpty(currentServerWebExchangeMono)
|
||||
.flatMap((exchange) -> {
|
||||
Map<String, Object> contextAttributes = Collections.emptyMap();
|
||||
String scope = exchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.SCOPE);
|
||||
if (StringUtils.hasText(scope)) {
|
||||
contextAttributes = new HashMap<>();
|
||||
contextAttributes.put(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME,
|
||||
StringUtils.delimitedListToStringArray(scope, " "));
|
||||
}
|
||||
return Mono.just(contextAttributes);
|
||||
}).defaultIfEmpty(Collections.emptyMap());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -239,7 +239,7 @@ public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilt
|
||||
@Override
|
||||
protected void initExtractorMap() {
|
||||
super.initExtractorMap();
|
||||
registerExtractor(ServletException.class, throwable -> {
|
||||
registerExtractor(ServletException.class, (throwable) -> {
|
||||
ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class);
|
||||
return ((ServletException) throwable).getRootCause();
|
||||
});
|
||||
|
||||
+1
-1
@@ -188,7 +188,7 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
|
||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.authorizationCode().refreshToken()
|
||||
.clientCredentials(
|
||||
configurer -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
|
||||
(configurer) -> configurer.accessTokenResponseClient(clientCredentialsTokenResponseClient))
|
||||
.password().build();
|
||||
((DefaultOAuth2AuthorizedClientManager) this.authorizedClientManager)
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
|
||||
+40
-38
@@ -132,11 +132,11 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
.map(SecurityContext::getAuthentication).defaultIfEmpty(ANONYMOUS_USER_TOKEN);
|
||||
|
||||
private final Mono<String> clientRegistrationIdMono = this.currentAuthenticationMono
|
||||
.filter(t -> this.defaultOAuth2AuthorizedClient && t instanceof OAuth2AuthenticationToken)
|
||||
.filter((t) -> this.defaultOAuth2AuthorizedClient && t instanceof OAuth2AuthenticationToken)
|
||||
.cast(OAuth2AuthenticationToken.class).map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId);
|
||||
|
||||
private final Mono<ServerWebExchange> currentServerWebExchangeMono = Mono.subscriberContext()
|
||||
.filter(c -> c.hasKey(ServerWebExchange.class)).map(c -> c.get(ServerWebExchange.class));
|
||||
.filter((c) -> c.hasKey(ServerWebExchange.class)).map((c) -> c.get(ServerWebExchange.class));
|
||||
|
||||
private final ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
|
||||
|
||||
@@ -275,7 +275,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
* @return the {@link Consumer} to populate the
|
||||
*/
|
||||
public static Consumer<Map<String, Object>> oauth2AuthorizedClient(OAuth2AuthorizedClient authorizedClient) {
|
||||
return attributes -> attributes.put(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME, authorizedClient);
|
||||
return (attributes) -> attributes.put(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME, authorizedClient);
|
||||
}
|
||||
|
||||
private static OAuth2AuthorizedClient oauth2AuthorizedClient(ClientRequest request) {
|
||||
@@ -302,7 +302,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
* @return the {@link Consumer} to populate the client request attributes
|
||||
*/
|
||||
public static Consumer<Map<String, Object>> serverWebExchange(ServerWebExchange serverWebExchange) {
|
||||
return attributes -> attributes.put(SERVER_WEB_EXCHANGE_ATTR_NAME, serverWebExchange);
|
||||
return (attributes) -> attributes.put(SERVER_WEB_EXCHANGE_ATTR_NAME, serverWebExchange);
|
||||
}
|
||||
|
||||
private static ServerWebExchange serverWebExchange(ClientRequest request) {
|
||||
@@ -318,7 +318,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
* @return the {@link Consumer} to populate the attributes
|
||||
*/
|
||||
public static Consumer<Map<String, Object>> clientRegistrationId(String clientRegistrationId) {
|
||||
return attributes -> attributes.put(CLIENT_REGISTRATION_ID_ATTR_NAME, clientRegistrationId);
|
||||
return (attributes) -> attributes.put(CLIENT_REGISTRATION_ID_ATTR_NAME, clientRegistrationId);
|
||||
}
|
||||
|
||||
private static String clientRegistrationId(ClientRequest request) {
|
||||
@@ -379,9 +379,9 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
private void updateDefaultAuthorizedClientManager() {
|
||||
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
|
||||
.builder().authorizationCode()
|
||||
.refreshToken(configurer -> configurer.clockSkew(this.accessTokenExpiresSkew))
|
||||
.refreshToken((configurer) -> configurer.clockSkew(this.accessTokenExpiresSkew))
|
||||
.clientCredentials(this::updateClientCredentialsProvider)
|
||||
.password(configurer -> configurer.clockSkew(this.accessTokenExpiresSkew)).build();
|
||||
.password((configurer) -> configurer.clockSkew(this.accessTokenExpiresSkew)).build();
|
||||
if (this.authorizedClientManager instanceof UnAuthenticatedReactiveOAuth2AuthorizedClientManager) {
|
||||
((UnAuthenticatedReactiveOAuth2AuthorizedClientManager) this.authorizedClientManager)
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
@@ -423,14 +423,14 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
|
||||
@Override
|
||||
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
|
||||
return authorizedClient(request).map(authorizedClient -> bearer(request, authorizedClient))
|
||||
.flatMap(requestWithBearer -> exchangeAndHandleResponse(requestWithBearer, next))
|
||||
return authorizedClient(request).map((authorizedClient) -> bearer(request, authorizedClient))
|
||||
.flatMap((requestWithBearer) -> exchangeAndHandleResponse(requestWithBearer, next))
|
||||
.switchIfEmpty(Mono.defer(() -> exchangeAndHandleResponse(request, next)));
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -438,7 +438,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
return Mono.justOrEmpty(authorizedClientFromAttrs)
|
||||
.switchIfEmpty(
|
||||
Mono.defer(() -> authorizeRequest(request).flatMap(this.authorizedClientManager::authorize)))
|
||||
.flatMap(authorizedClient -> reauthorizeRequest(request, authorizedClient)
|
||||
.flatMap((authorizedClient) -> reauthorizeRequest(request, authorizedClient)
|
||||
.flatMap(this.authorizedClientManager::authorize));
|
||||
}
|
||||
|
||||
@@ -447,10 +447,10 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
|
||||
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
|
||||
|
||||
return Mono.zip(clientRegistrationId, this.currentAuthenticationMono, serverWebExchange).map(t3 -> {
|
||||
return Mono.zip(clientRegistrationId, this.currentAuthenticationMono, serverWebExchange).map((t3) -> {
|
||||
OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withClientRegistrationId(t3.getT1())
|
||||
.principal(t3.getT2());
|
||||
t3.getT3().ifPresent(exchange -> builder.attribute(ServerWebExchange.class.getName(), exchange));
|
||||
t3.getT3().ifPresent((exchange) -> builder.attribute(ServerWebExchange.class.getName(), exchange));
|
||||
return builder.build();
|
||||
});
|
||||
}
|
||||
@@ -489,17 +489,17 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
OAuth2AuthorizedClient authorizedClient) {
|
||||
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
|
||||
|
||||
return Mono.zip(this.currentAuthenticationMono, serverWebExchange).map(t2 -> {
|
||||
return Mono.zip(this.currentAuthenticationMono, serverWebExchange).map((t2) -> {
|
||||
OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withAuthorizedClient(authorizedClient)
|
||||
.principal(t2.getT1());
|
||||
t2.getT2().ifPresent(exchange -> builder.attribute(ServerWebExchange.class.getName(), exchange));
|
||||
t2.getT2().ifPresent((exchange) -> builder.attribute(ServerWebExchange.class.getName(), exchange));
|
||||
return builder.build();
|
||||
});
|
||||
}
|
||||
|
||||
private ClientRequest bearer(ClientRequest request, OAuth2AuthorizedClient authorizedClient) {
|
||||
return ClientRequest.from(request)
|
||||
.headers(headers -> headers.setBearerAuth(authorizedClient.getAccessToken().getTokenValue())).build();
|
||||
.headers((headers) -> headers.setBearerAuth(authorizedClient.getAccessToken().getTokenValue())).build();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -565,14 +565,15 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
String clientRegistrationId = authorizeRequest.getClientRegistrationId();
|
||||
Authentication principal = authorizeRequest.getPrincipal();
|
||||
|
||||
return Mono.justOrEmpty(authorizeRequest.getAuthorizedClient()).switchIfEmpty(Mono.defer(
|
||||
() -> this.authorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal, null)))
|
||||
.flatMap(authorizedClient -> {
|
||||
return Mono.justOrEmpty(authorizeRequest.getAuthorizedClient())
|
||||
.switchIfEmpty(Mono.defer(() -> this.authorizedClientRepository
|
||||
.loadAuthorizedClient(clientRegistrationId, principal, null)))
|
||||
.flatMap((authorizedClient) -> {
|
||||
// Re-authorize
|
||||
return Mono
|
||||
.just(OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient)
|
||||
.principal(principal).build())
|
||||
.flatMap(authorizationContext -> authorize(authorizationContext, principal))
|
||||
.flatMap((authorizationContext) -> authorize(authorizationContext, principal))
|
||||
// Default to the existing authorizedClient if the client
|
||||
// was not re-authorized
|
||||
.defaultIfEmpty(authorizeRequest.getAuthorizedClient() != null
|
||||
@@ -582,9 +583,9 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)
|
||||
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(
|
||||
"Could not find ClientRegistration with id '" + clientRegistrationId + "'")))
|
||||
.flatMap(clientRegistration -> Mono.just(OAuth2AuthorizationContext
|
||||
.flatMap((clientRegistration) -> Mono.just(OAuth2AuthorizationContext
|
||||
.withClientRegistration(clientRegistration).principal(principal).build()))
|
||||
.flatMap(authorizationContext -> authorize(authorizationContext, principal))));
|
||||
.flatMap((authorizationContext) -> authorize(authorizationContext, principal))));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -604,13 +605,13 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
return this.authorizedClientProvider.authorize(authorizationContext)
|
||||
// Delegates to the authorizationSuccessHandler of the successful
|
||||
// authorization
|
||||
.flatMap(authorizedClient -> this.authorizationSuccessHandler
|
||||
.flatMap((authorizedClient) -> this.authorizationSuccessHandler
|
||||
.onAuthorizationSuccess(authorizedClient, principal, Collections.emptyMap())
|
||||
.thenReturn(authorizedClient))
|
||||
// Delegates to the authorizationFailureHandler of the failed
|
||||
// authorization
|
||||
.onErrorResume(OAuth2AuthorizationException.class,
|
||||
authorizationException -> this.authorizationFailureHandler
|
||||
(authorizationException) -> this.authorizationFailureHandler
|
||||
.onAuthorizationFailure(authorizationException, principal, Collections.emptyMap())
|
||||
.then(Mono.error(authorizationException)));
|
||||
}
|
||||
@@ -654,15 +655,15 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
|
||||
@Override
|
||||
public Mono<ClientResponse> handleResponse(ClientRequest request, Mono<ClientResponse> responseMono) {
|
||||
return responseMono.flatMap(response -> handleResponse(request, response).thenReturn(response))
|
||||
return responseMono.flatMap((response) -> handleResponse(request, response).thenReturn(response))
|
||||
.onErrorResume(WebClientResponseException.class,
|
||||
e -> handleWebClientResponseException(request, e).then(Mono.error(e)))
|
||||
(e) -> handleWebClientResponseException(request, e).then(Mono.error(e)))
|
||||
.onErrorResume(OAuth2AuthorizationException.class,
|
||||
e -> handleAuthorizationException(request, e).then(Mono.error(e)));
|
||||
(e) -> handleAuthorizationException(request, e).then(Mono.error(e)));
|
||||
}
|
||||
|
||||
private Mono<Void> handleResponse(ClientRequest request, ClientResponse response) {
|
||||
return Mono.justOrEmpty(resolveErrorIfPossible(response)).flatMap(oauth2Error -> {
|
||||
return Mono.justOrEmpty(resolveErrorIfPossible(response)).flatMap((oauth2Error) -> {
|
||||
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
|
||||
|
||||
Mono<String> clientRegistrationId = effectiveClientRegistrationId(request);
|
||||
@@ -670,7 +671,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
return Mono
|
||||
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
|
||||
serverWebExchange, clientRegistrationId)
|
||||
.flatMap(tuple3 -> handleAuthorizationFailure(tuple3.getT1(), // Authentication
|
||||
.flatMap((tuple3) -> handleAuthorizationFailure(tuple3.getT1(), // Authentication
|
||||
// principal
|
||||
tuple3.getT2().orElse(null), // ServerWebExchange exchange
|
||||
new ClientAuthorizationException(oauth2Error, tuple3.getT3()))); // String
|
||||
@@ -701,12 +702,13 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
}
|
||||
|
||||
private Map<String, String> parseAuthParameters(String wwwAuthenticateHeader) {
|
||||
return Stream.of(wwwAuthenticateHeader).filter(header -> !StringUtils.isEmpty(header))
|
||||
.filter(header -> header.toLowerCase().startsWith("bearer"))
|
||||
.map(header -> header.substring("bearer".length())).map(header -> header.split(","))
|
||||
.flatMap(Stream::of).map(parameter -> parameter.split("="))
|
||||
.filter(parameter -> parameter.length > 1).collect(Collectors.toMap(
|
||||
parameters -> parameters[0].trim(), parameters -> parameters[1].trim().replace("\"", "")));
|
||||
return Stream.of(wwwAuthenticateHeader).filter((header) -> !StringUtils.isEmpty(header))
|
||||
.filter((header) -> header.toLowerCase().startsWith("bearer"))
|
||||
.map((header) -> header.substring("bearer".length())).map((header) -> header.split(","))
|
||||
.flatMap(Stream::of).map((parameter) -> parameter.split("="))
|
||||
.filter((parameter) -> parameter.length > 1)
|
||||
.collect(Collectors.toMap((parameters) -> parameters[0].trim(),
|
||||
(parameters) -> parameters[1].trim().replace("\"", "")));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -720,7 +722,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
*/
|
||||
private Mono<Void> handleWebClientResponseException(ClientRequest request,
|
||||
WebClientResponseException exception) {
|
||||
return Mono.justOrEmpty(resolveErrorIfPossible(exception.getRawStatusCode())).flatMap(oauth2Error -> {
|
||||
return Mono.justOrEmpty(resolveErrorIfPossible(exception.getRawStatusCode())).flatMap((oauth2Error) -> {
|
||||
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
|
||||
|
||||
Mono<String> clientRegistrationId = effectiveClientRegistrationId(request);
|
||||
@@ -728,7 +730,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
return Mono
|
||||
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
|
||||
serverWebExchange, clientRegistrationId)
|
||||
.flatMap(tuple3 -> handleAuthorizationFailure(tuple3.getT1(), // Authentication
|
||||
.flatMap((tuple3) -> handleAuthorizationFailure(tuple3.getT1(), // Authentication
|
||||
// principal
|
||||
tuple3.getT2().orElse(null), // ServerWebExchange exchange
|
||||
new ClientAuthorizationException(oauth2Error, tuple3.getT3(), // String
|
||||
@@ -750,7 +752,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements
|
||||
|
||||
return Mono.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
|
||||
serverWebExchange).flatMap(
|
||||
tuple2 -> handleAuthorizationFailure(tuple2.getT1(), // Authentication
|
||||
(tuple2) -> handleAuthorizationFailure(tuple2.getT1(), // Authentication
|
||||
// principal
|
||||
tuple2.getT2().orElse(null), // ServerWebExchange
|
||||
// exchange
|
||||
|
||||
+34
-32
@@ -259,9 +259,9 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
|
||||
private void updateDefaultAuthorizedClientManager() {
|
||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.authorizationCode().refreshToken(configurer -> configurer.clockSkew(this.accessTokenExpiresSkew))
|
||||
.authorizationCode().refreshToken((configurer) -> configurer.clockSkew(this.accessTokenExpiresSkew))
|
||||
.clientCredentials(this::updateClientCredentialsProvider)
|
||||
.password(configurer -> configurer.clockSkew(this.accessTokenExpiresSkew)).build();
|
||||
.password((configurer) -> configurer.clockSkew(this.accessTokenExpiresSkew)).build();
|
||||
((DefaultOAuth2AuthorizedClientManager) this.authorizedClientManager)
|
||||
.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
}
|
||||
@@ -302,7 +302,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
* @return the {@link Consumer} to configure the builder
|
||||
*/
|
||||
public Consumer<WebClient.Builder> oauth2Configuration() {
|
||||
return builder -> builder.defaultRequest(defaultRequest()).filter(this);
|
||||
return (builder) -> builder.defaultRequest(defaultRequest()).filter(this);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -315,7 +315,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
* @return the {@link Consumer} to populate the attributes
|
||||
*/
|
||||
public Consumer<WebClient.RequestHeadersSpec<?>> defaultRequest() {
|
||||
return spec -> spec.attributes(attrs -> {
|
||||
return (spec) -> spec.attributes((attrs) -> {
|
||||
populateDefaultRequestResponse(attrs);
|
||||
populateDefaultAuthentication(attrs);
|
||||
});
|
||||
@@ -328,7 +328,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
* @return the {@link Consumer} to populate the attributes
|
||||
*/
|
||||
public static Consumer<Map<String, Object>> oauth2AuthorizedClient(OAuth2AuthorizedClient authorizedClient) {
|
||||
return attributes -> {
|
||||
return (attributes) -> {
|
||||
if (authorizedClient == null) {
|
||||
attributes.remove(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME);
|
||||
}
|
||||
@@ -347,7 +347,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
* @return the {@link Consumer} to populate the attributes
|
||||
*/
|
||||
public static Consumer<Map<String, Object>> clientRegistrationId(String clientRegistrationId) {
|
||||
return attributes -> attributes.put(CLIENT_REGISTRATION_ID_ATTR_NAME, clientRegistrationId);
|
||||
return (attributes) -> attributes.put(CLIENT_REGISTRATION_ID_ATTR_NAME, clientRegistrationId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -359,7 +359,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
* @return the {@link Consumer} to populate the attributes
|
||||
*/
|
||||
public static Consumer<Map<String, Object>> authentication(Authentication authentication) {
|
||||
return attributes -> attributes.put(AUTHENTICATION_ATTR_NAME, authentication);
|
||||
return (attributes) -> attributes.put(AUTHENTICATION_ATTR_NAME, authentication);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -371,7 +371,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
* @return the {@link Consumer} to populate the attributes
|
||||
*/
|
||||
public static Consumer<Map<String, Object>> httpServletRequest(HttpServletRequest request) {
|
||||
return attributes -> attributes.put(HTTP_SERVLET_REQUEST_ATTR_NAME, request);
|
||||
return (attributes) -> attributes.put(HTTP_SERVLET_REQUEST_ATTR_NAME, request);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -383,7 +383,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
* @return the {@link Consumer} to populate the attributes
|
||||
*/
|
||||
public static Consumer<Map<String, Object>> httpServletResponse(HttpServletResponse response) {
|
||||
return attributes -> attributes.put(HTTP_SERVLET_RESPONSE_ATTR_NAME, response);
|
||||
return (attributes) -> attributes.put(HTTP_SERVLET_RESPONSE_ATTR_NAME, response);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -432,19 +432,19 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
@Override
|
||||
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
|
||||
return mergeRequestAttributesIfNecessary(request)
|
||||
.filter(req -> req.attribute(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME).isPresent())
|
||||
.flatMap(req -> reauthorizeClient(getOAuth2AuthorizedClient(req.attributes()), req))
|
||||
.filter((req) -> req.attribute(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME).isPresent())
|
||||
.flatMap((req) -> reauthorizeClient(getOAuth2AuthorizedClient(req.attributes()), req))
|
||||
.switchIfEmpty(Mono.defer(() -> mergeRequestAttributesIfNecessary(request)
|
||||
.filter(req -> resolveClientRegistrationId(req) != null)
|
||||
.flatMap(req -> authorizeClient(resolveClientRegistrationId(req), req))))
|
||||
.map(authorizedClient -> bearer(request, authorizedClient))
|
||||
.flatMap(requestWithBearer -> exchangeAndHandleResponse(requestWithBearer, next))
|
||||
.filter((req) -> resolveClientRegistrationId(req) != null)
|
||||
.flatMap((req) -> authorizeClient(resolveClientRegistrationId(req), req))))
|
||||
.map((authorizedClient) -> bearer(request, authorizedClient))
|
||||
.flatMap((requestWithBearer) -> exchangeAndHandleResponse(requestWithBearer, next))
|
||||
.switchIfEmpty(Mono.defer(() -> exchangeAndHandleResponse(request, next)));
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -460,7 +460,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)))
|
||||
return Mono.subscriberContext()
|
||||
.map((ctx) -> builder.attributes((attrs) -> populateRequestAttributes(attrs, ctx)))
|
||||
.map(ClientRequest.Builder::build);
|
||||
}
|
||||
|
||||
@@ -532,7 +533,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
|
||||
OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId)
|
||||
.principal(authentication);
|
||||
builder.attributes(attributes -> {
|
||||
builder.attributes((attributes) -> {
|
||||
if (servletRequest != null) {
|
||||
attributes.put(HttpServletRequest.class.getName(), servletRequest);
|
||||
}
|
||||
@@ -565,7 +566,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
|
||||
OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withAuthorizedClient(authorizedClient)
|
||||
.principal(authentication);
|
||||
builder.attributes(attributes -> {
|
||||
builder.attributes((attributes) -> {
|
||||
if (servletRequest != null) {
|
||||
attributes.put(HttpServletRequest.class.getName(), servletRequest);
|
||||
}
|
||||
@@ -585,7 +586,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
|
||||
private ClientRequest bearer(ClientRequest request, OAuth2AuthorizedClient authorizedClient) {
|
||||
return ClientRequest.from(request)
|
||||
.headers(headers -> headers.setBearerAuth(authorizedClient.getAccessToken().getTokenValue()))
|
||||
.headers((headers) -> headers.setBearerAuth(authorizedClient.getAccessToken().getTokenValue()))
|
||||
.attributes(oauth2AuthorizedClient(authorizedClient)).build();
|
||||
}
|
||||
|
||||
@@ -664,15 +665,15 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
|
||||
@Override
|
||||
public Mono<ClientResponse> handleResponse(ClientRequest request, Mono<ClientResponse> responseMono) {
|
||||
return responseMono.flatMap(response -> handleResponse(request, response).thenReturn(response))
|
||||
return responseMono.flatMap((response) -> handleResponse(request, response).thenReturn(response))
|
||||
.onErrorResume(WebClientResponseException.class,
|
||||
e -> handleWebClientResponseException(request, e).then(Mono.error(e)))
|
||||
(e) -> handleWebClientResponseException(request, e).then(Mono.error(e)))
|
||||
.onErrorResume(OAuth2AuthorizationException.class,
|
||||
e -> handleAuthorizationException(request, e).then(Mono.error(e)));
|
||||
(e) -> handleAuthorizationException(request, e).then(Mono.error(e)));
|
||||
}
|
||||
|
||||
private Mono<Void> handleResponse(ClientRequest request, ClientResponse response) {
|
||||
return Mono.justOrEmpty(resolveErrorIfPossible(response)).flatMap(oauth2Error -> {
|
||||
return Mono.justOrEmpty(resolveErrorIfPossible(response)).flatMap((oauth2Error) -> {
|
||||
Map<String, Object> attrs = request.attributes();
|
||||
OAuth2AuthorizedClient authorizedClient = getOAuth2AuthorizedClient(attrs);
|
||||
if (authorizedClient == null) {
|
||||
@@ -713,12 +714,13 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
}
|
||||
|
||||
private Map<String, String> parseAuthParameters(String wwwAuthenticateHeader) {
|
||||
return Stream.of(wwwAuthenticateHeader).filter(header -> !StringUtils.isEmpty(header))
|
||||
.filter(header -> header.toLowerCase().startsWith("bearer"))
|
||||
.map(header -> header.substring("bearer".length())).map(header -> header.split(","))
|
||||
.flatMap(Stream::of).map(parameter -> parameter.split("="))
|
||||
.filter(parameter -> parameter.length > 1).collect(Collectors.toMap(
|
||||
parameters -> parameters[0].trim(), parameters -> parameters[1].trim().replace("\"", "")));
|
||||
return Stream.of(wwwAuthenticateHeader).filter((header) -> !StringUtils.isEmpty(header))
|
||||
.filter((header) -> header.toLowerCase().startsWith("bearer"))
|
||||
.map((header) -> header.substring("bearer".length())).map((header) -> header.split(","))
|
||||
.flatMap(Stream::of).map((parameter) -> parameter.split("="))
|
||||
.filter((parameter) -> parameter.length > 1)
|
||||
.collect(Collectors.toMap((parameters) -> parameters[0].trim(),
|
||||
(parameters) -> parameters[1].trim().replace("\"", "")));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -732,7 +734,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
*/
|
||||
private Mono<Void> handleWebClientResponseException(ClientRequest request,
|
||||
WebClientResponseException exception) {
|
||||
return Mono.justOrEmpty(resolveErrorIfPossible(exception.getRawStatusCode())).flatMap(oauth2Error -> {
|
||||
return Mono.justOrEmpty(resolveErrorIfPossible(exception.getRawStatusCode())).flatMap((oauth2Error) -> {
|
||||
Map<String, Object> attrs = request.attributes();
|
||||
OAuth2AuthorizedClient authorizedClient = getOAuth2AuthorizedClient(attrs);
|
||||
if (authorizedClient == null) {
|
||||
@@ -761,7 +763,7 @@ public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implement
|
||||
*/
|
||||
private Mono<Void> handleAuthorizationException(ClientRequest request,
|
||||
OAuth2AuthorizationException authorizationException) {
|
||||
return Mono.justOrEmpty(request).flatMap(req -> {
|
||||
return Mono.justOrEmpty(request).flatMap((req) -> {
|
||||
Map<String, Object> attrs = req.attributes();
|
||||
OAuth2AuthorizedClient authorizedClient = getOAuth2AuthorizedClient(attrs);
|
||||
if (authorizedClient == null) {
|
||||
|
||||
+5
-4
@@ -125,7 +125,7 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
|
||||
.switchIfEmpty(currentServerWebExchange());
|
||||
|
||||
return Mono.zip(defaultedRegistrationId, defaultedAuthentication, defaultedExchange)
|
||||
.map(t3 -> OAuth2AuthorizeRequest.withClientRegistrationId(t3.getT1()).principal(t3.getT2())
|
||||
.map((t3) -> OAuth2AuthorizeRequest.withClientRegistrationId(t3.getT1()).principal(t3.getT2())
|
||||
.attribute(ServerWebExchange.class.getName(), t3.getT3()).build());
|
||||
}
|
||||
|
||||
@@ -135,13 +135,14 @@ public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMeth
|
||||
}
|
||||
|
||||
private Mono<String> clientRegistrationId(Mono<Authentication> authentication) {
|
||||
return authentication.filter(t -> t instanceof OAuth2AuthenticationToken).cast(OAuth2AuthenticationToken.class)
|
||||
return authentication.filter((t) -> t instanceof OAuth2AuthenticationToken)
|
||||
.cast(OAuth2AuthenticationToken.class)
|
||||
.map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId);
|
||||
}
|
||||
|
||||
private Mono<ServerWebExchange> currentServerWebExchange() {
|
||||
return Mono.subscriberContext().filter(c -> c.hasKey(ServerWebExchange.class))
|
||||
.map(c -> c.get(ServerWebExchange.class));
|
||||
return Mono.subscriberContext().filter((c) -> c.hasKey(ServerWebExchange.class))
|
||||
.map((c) -> c.get(ServerWebExchange.class));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+5
-5
@@ -87,7 +87,7 @@ public class DefaultServerOAuth2AuthorizationRequestResolver implements ServerOA
|
||||
private final StringKeyGenerator secureKeyGenerator = new Base64StringKeyGenerator(
|
||||
Base64.getUrlEncoder().withoutPadding(), 96);
|
||||
|
||||
private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer = customizer -> {
|
||||
private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer = (customizer) -> {
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -120,16 +120,16 @@ public class DefaultServerOAuth2AuthorizationRequestResolver implements ServerOA
|
||||
|
||||
@Override
|
||||
public Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange) {
|
||||
return this.authorizationRequestMatcher.matches(exchange).filter(matchResult -> matchResult.isMatch())
|
||||
return this.authorizationRequestMatcher.matches(exchange).filter((matchResult) -> matchResult.isMatch())
|
||||
.map(ServerWebExchangeMatcher.MatchResult::getVariables)
|
||||
.map(variables -> variables.get(DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME)).cast(String.class)
|
||||
.flatMap(clientRegistrationId -> resolve(exchange, clientRegistrationId));
|
||||
.map((variables) -> variables.get(DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME)).cast(String.class)
|
||||
.flatMap((clientRegistrationId) -> resolve(exchange, clientRegistrationId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange, String clientRegistrationId) {
|
||||
return this.findByRegistrationId(exchange, clientRegistrationId)
|
||||
.map(clientRegistration -> authorizationRequest(exchange, clientRegistration));
|
||||
.map((clientRegistration) -> authorizationRequest(exchange, clientRegistration));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+11
-11
@@ -204,12 +204,12 @@ public class OAuth2AuthorizationCodeGrantWebFilter implements WebFilter {
|
||||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||
return this.requiresAuthenticationMatcher.matches(exchange)
|
||||
.filter(ServerWebExchangeMatcher.MatchResult::isMatch)
|
||||
.flatMap(matchResult -> this.authenticationConverter.convert(exchange).onErrorMap(
|
||||
.flatMap((matchResult) -> this.authenticationConverter.convert(exchange).onErrorMap(
|
||||
OAuth2AuthorizationException.class,
|
||||
e -> new OAuth2AuthenticationException(e.getError(), e.getError().toString())))
|
||||
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString())))
|
||||
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
|
||||
.flatMap(token -> authenticate(exchange, chain, token))
|
||||
.onErrorResume(AuthenticationException.class, e -> this.authenticationFailureHandler
|
||||
.flatMap((token) -> authenticate(exchange, chain, token))
|
||||
.onErrorResume(AuthenticationException.class, (e) -> this.authenticationFailureHandler
|
||||
.onAuthenticationFailure(new WebFilterExchange(exchange, chain), e));
|
||||
}
|
||||
|
||||
@@ -217,12 +217,12 @@ public class OAuth2AuthorizationCodeGrantWebFilter implements WebFilter {
|
||||
WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain);
|
||||
return this.authenticationManager.authenticate(token)
|
||||
.onErrorMap(OAuth2AuthorizationException.class,
|
||||
e -> new OAuth2AuthenticationException(e.getError(), e.getError().toString()))
|
||||
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString()))
|
||||
.switchIfEmpty(Mono.defer(
|
||||
() -> Mono.error(new IllegalStateException("No provider found for " + token.getClass()))))
|
||||
.flatMap(authentication -> onAuthenticationSuccess(authentication, webFilterExchange))
|
||||
.flatMap((authentication) -> onAuthenticationSuccess(authentication, webFilterExchange))
|
||||
.onErrorResume(AuthenticationException.class,
|
||||
e -> this.authenticationFailureHandler.onAuthenticationFailure(webFilterExchange, e));
|
||||
(e) -> this.authenticationFailureHandler.onAuthenticationFailure(webFilterExchange, e));
|
||||
}
|
||||
|
||||
private Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) {
|
||||
@@ -232,15 +232,15 @@ public class OAuth2AuthorizationCodeGrantWebFilter implements WebFilter {
|
||||
authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
|
||||
return this.authenticationSuccessHandler.onAuthenticationSuccess(webFilterExchange, authentication)
|
||||
.then(ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)
|
||||
.defaultIfEmpty(this.anonymousToken).flatMap(principal -> this.authorizedClientRepository
|
||||
.defaultIfEmpty(this.anonymousToken).flatMap((principal) -> this.authorizedClientRepository
|
||||
.saveAuthorizedClient(authorizedClient, principal, webFilterExchange.getExchange())));
|
||||
}
|
||||
|
||||
private Mono<ServerWebExchangeMatcher.MatchResult> matchesAuthorizationResponse(ServerWebExchange exchange) {
|
||||
return Mono.just(exchange).filter(
|
||||
exch -> OAuth2AuthorizationResponseUtils.isAuthorizationResponse(exch.getRequest().getQueryParams()))
|
||||
.flatMap(exch -> this.authorizationRequestRepository.loadAuthorizationRequest(exchange)
|
||||
.flatMap(authorizationRequest -> matchesRedirectUri(exch.getRequest().getURI(),
|
||||
(exch) -> OAuth2AuthorizationResponseUtils.isAuthorizationResponse(exch.getRequest().getQueryParams()))
|
||||
.flatMap((exch) -> this.authorizationRequestRepository.loadAuthorizationRequest(exchange)
|
||||
.flatMap((authorizationRequest) -> matchesRedirectUri(exch.getRequest().getURI(),
|
||||
authorizationRequest.getRedirectUri())))
|
||||
.switchIfEmpty(ServerWebExchangeMatcher.MatchResult.notMatch());
|
||||
}
|
||||
|
||||
+2
-2
@@ -130,9 +130,9 @@ public class OAuth2AuthorizationRequestRedirectWebFilter implements WebFilter {
|
||||
return this.authorizationRequestResolver.resolve(exchange)
|
||||
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
|
||||
.onErrorResume(ClientAuthorizationRequiredException.class,
|
||||
e -> this.requestCache.saveRequest(exchange)
|
||||
(e) -> this.requestCache.saveRequest(exchange)
|
||||
.then(this.authorizationRequestResolver.resolve(exchange, e.getClientRegistrationId())))
|
||||
.flatMap(clientRegistration -> sendRedirectForAuthorization(exchange, clientRegistration));
|
||||
.flatMap((clientRegistration) -> sendRedirectForAuthorization(exchange, clientRegistration));
|
||||
}
|
||||
|
||||
private Mono<Void> sendRedirectForAuthorization(ServerWebExchange exchange,
|
||||
|
||||
+3
-3
@@ -72,7 +72,7 @@ public class ServerOAuth2AuthorizationCodeAuthenticationTokenConverter implement
|
||||
public Mono<Authentication> convert(ServerWebExchange serverWebExchange) {
|
||||
return this.authorizationRequestRepository.removeAuthorizationRequest(serverWebExchange)
|
||||
.switchIfEmpty(oauth2AuthorizationException(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE))
|
||||
.flatMap(authorizationRequest -> authenticationRequest(serverWebExchange, authorizationRequest));
|
||||
.flatMap((authorizationRequest) -> authenticationRequest(serverWebExchange, authorizationRequest));
|
||||
}
|
||||
|
||||
private <T> Mono<T> oauth2AuthorizationException(String errorCode) {
|
||||
@@ -84,14 +84,14 @@ public class ServerOAuth2AuthorizationCodeAuthenticationTokenConverter implement
|
||||
|
||||
private Mono<OAuth2AuthorizationCodeAuthenticationToken> authenticationRequest(ServerWebExchange exchange,
|
||||
OAuth2AuthorizationRequest authorizationRequest) {
|
||||
return Mono.just(authorizationRequest).map(OAuth2AuthorizationRequest::getAttributes).flatMap(attributes -> {
|
||||
return Mono.just(authorizationRequest).map(OAuth2AuthorizationRequest::getAttributes).flatMap((attributes) -> {
|
||||
String id = (String) attributes.get(OAuth2ParameterNames.REGISTRATION_ID);
|
||||
if (id == null) {
|
||||
return oauth2AuthorizationException(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE);
|
||||
}
|
||||
return this.clientRegistrationRepository.findByRegistrationId(id);
|
||||
}).switchIfEmpty(oauth2AuthorizationException(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE))
|
||||
.map(clientRegistration -> {
|
||||
.map((clientRegistration) -> {
|
||||
OAuth2AuthorizationResponse authorizationResponse = convertResponse(exchange);
|
||||
OAuth2AuthorizationCodeAuthenticationToken authenticationRequest = new OAuth2AuthorizationCodeAuthenticationToken(
|
||||
clientRegistration,
|
||||
|
||||
+6
-6
@@ -53,8 +53,8 @@ public final class WebSessionOAuth2ServerAuthorizationRequestRepository
|
||||
return Mono.empty();
|
||||
}
|
||||
return getStateToAuthorizationRequest(exchange)
|
||||
.filter(stateToAuthorizationRequest -> stateToAuthorizationRequest.containsKey(state))
|
||||
.map(stateToAuthorizationRequest -> stateToAuthorizationRequest.get(state));
|
||||
.filter((stateToAuthorizationRequest) -> stateToAuthorizationRequest.containsKey(state))
|
||||
.map((stateToAuthorizationRequest) -> stateToAuthorizationRequest.get(state));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -62,7 +62,7 @@ public final class WebSessionOAuth2ServerAuthorizationRequestRepository
|
||||
ServerWebExchange exchange) {
|
||||
Assert.notNull(authorizationRequest, "authorizationRequest cannot be null");
|
||||
return saveStateToAuthorizationRequest(exchange)
|
||||
.doOnNext(stateToAuthorizationRequest -> stateToAuthorizationRequest
|
||||
.doOnNext((stateToAuthorizationRequest) -> stateToAuthorizationRequest
|
||||
.put(authorizationRequest.getState(), authorizationRequest))
|
||||
.then();
|
||||
}
|
||||
@@ -116,13 +116,13 @@ public final class WebSessionOAuth2ServerAuthorizationRequestRepository
|
||||
Assert.notNull(exchange, "exchange cannot be null");
|
||||
|
||||
return getSessionAttributes(exchange).flatMap(
|
||||
sessionAttrs -> Mono.justOrEmpty(this.sessionAttrsMapStateToAuthorizationRequest(sessionAttrs)));
|
||||
(sessionAttrs) -> Mono.justOrEmpty(this.sessionAttrsMapStateToAuthorizationRequest(sessionAttrs)));
|
||||
}
|
||||
|
||||
private Mono<Map<String, OAuth2AuthorizationRequest>> saveStateToAuthorizationRequest(ServerWebExchange exchange) {
|
||||
Assert.notNull(exchange, "exchange cannot be null");
|
||||
|
||||
return getSessionAttributes(exchange).doOnNext(sessionAttrs -> {
|
||||
return getSessionAttributes(exchange).doOnNext((sessionAttrs) -> {
|
||||
Object stateToAuthzRequest = sessionAttrs.get(this.sessionAttributeName);
|
||||
|
||||
if (stateToAuthzRequest == null) {
|
||||
@@ -133,7 +133,7 @@ public final class WebSessionOAuth2ServerAuthorizationRequestRepository
|
||||
// it into session again
|
||||
// in case of redis or hazelcast session. #6215
|
||||
sessionAttrs.put(this.sessionAttributeName, stateToAuthzRequest);
|
||||
}).flatMap(sessionAttrs -> Mono.justOrEmpty(this.sessionAttrsMapStateToAuthorizationRequest(sessionAttrs)));
|
||||
}).flatMap((sessionAttrs) -> Mono.justOrEmpty(this.sessionAttrsMapStateToAuthorizationRequest(sessionAttrs)));
|
||||
}
|
||||
|
||||
private Map<String, OAuth2AuthorizationRequest> sessionAttrsMapStateToAuthorizationRequest(
|
||||
|
||||
+3
-3
@@ -51,7 +51,7 @@ public final class WebSessionServerOAuth2AuthorizedClientRepository implements S
|
||||
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
|
||||
Assert.notNull(exchange, "exchange cannot be null");
|
||||
return exchange.getSession().map(this::getAuthorizedClients)
|
||||
.flatMap(clients -> Mono.justOrEmpty((T) clients.get(clientRegistrationId)));
|
||||
.flatMap((clients) -> Mono.justOrEmpty((T) clients.get(clientRegistrationId)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -59,7 +59,7 @@ public final class WebSessionServerOAuth2AuthorizedClientRepository implements S
|
||||
ServerWebExchange exchange) {
|
||||
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
|
||||
Assert.notNull(exchange, "exchange cannot be null");
|
||||
return exchange.getSession().doOnSuccess(session -> {
|
||||
return exchange.getSession().doOnSuccess((session) -> {
|
||||
Map<String, OAuth2AuthorizedClient> authorizedClients = getAuthorizedClients(session);
|
||||
authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient);
|
||||
session.getAttributes().put(this.sessionAttributeName, authorizedClients);
|
||||
@@ -71,7 +71,7 @@ public final class WebSessionServerOAuth2AuthorizedClientRepository implements S
|
||||
ServerWebExchange exchange) {
|
||||
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
|
||||
Assert.notNull(exchange, "exchange cannot be null");
|
||||
return exchange.getSession().doOnSuccess(session -> {
|
||||
return exchange.getSession().doOnSuccess((session) -> {
|
||||
Map<String, OAuth2AuthorizedClient> authorizedClients = getAuthorizedClients(session);
|
||||
authorizedClients.remove(clientRegistrationId);
|
||||
if (authorizedClients.isEmpty()) {
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ public class OAuth2AuthorizationContextTests {
|
||||
@Test
|
||||
public void withAuthorizedClientWhenAllValuesProvidedThenAllValuesAreSet() {
|
||||
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
|
||||
.withAuthorizedClient(this.authorizedClient).principal(this.principal).attributes(attributes -> {
|
||||
.withAuthorizedClient(this.authorizedClient).principal(this.principal).attributes((attributes) -> {
|
||||
attributes.put("attribute1", "value1");
|
||||
attributes.put("attribute2", "value2");
|
||||
}).build();
|
||||
|
||||
+2
-2
@@ -74,7 +74,7 @@ public class OAuth2AuthorizeRequestTests {
|
||||
public void withClientRegistrationIdWhenAllValuesProvidedThenAllValuesAreSet() {
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
|
||||
.attributes(attrs -> {
|
||||
.attributes((attrs) -> {
|
||||
attrs.put("name1", "value1");
|
||||
attrs.put("name2", "value2");
|
||||
}).build();
|
||||
@@ -88,7 +88,7 @@ public class OAuth2AuthorizeRequestTests {
|
||||
@Test
|
||||
public void withAuthorizedClientWhenAllValuesProvidedThenAllValuesAreSet() {
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).attributes(attrs -> {
|
||||
.principal(this.principal).attributes((attrs) -> {
|
||||
attrs.put("name1", "value1");
|
||||
attrs.put("name2", "value2");
|
||||
}).build();
|
||||
|
||||
+10
-6
@@ -101,7 +101,8 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
|
||||
@Test
|
||||
public void buildWhenRefreshTokenProviderThenProviderReauthorizes() {
|
||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.refreshToken(configurer -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.refreshToken(
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.build();
|
||||
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
|
||||
@@ -120,7 +121,7 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
|
||||
public void buildWhenClientCredentialsProviderThenProviderAuthorizes() {
|
||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.clientCredentials(
|
||||
configurer -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.build();
|
||||
|
||||
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
|
||||
@@ -135,7 +136,8 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
|
||||
@Test
|
||||
public void buildWhenPasswordProviderThenProviderAuthorizes() {
|
||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.password(configurer -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient)).build();
|
||||
.password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient))
|
||||
.build();
|
||||
|
||||
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
|
||||
.withClientRegistration(TestClientRegistrations.password().build()).principal(this.principal)
|
||||
@@ -151,10 +153,12 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
|
||||
public void buildWhenAllProvidersThenProvidersAuthorize() {
|
||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.authorizationCode()
|
||||
.refreshToken(configurer -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.refreshToken(
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.clientCredentials(
|
||||
configurer -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.password(configurer -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient)).build();
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient))
|
||||
.build();
|
||||
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
|
||||
|
||||
|
||||
+4
-4
@@ -167,7 +167,7 @@ public class OAuth2LoginAuthenticationProviderTests {
|
||||
|
||||
OAuth2User principal = mock(OAuth2User.class);
|
||||
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) invocation -> authorities);
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
|
||||
given(this.userService.loadUser(any())).willReturn(principal);
|
||||
|
||||
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
|
||||
@@ -190,13 +190,13 @@ public class OAuth2LoginAuthenticationProviderTests {
|
||||
|
||||
OAuth2User principal = mock(OAuth2User.class);
|
||||
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) invocation -> authorities);
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
|
||||
given(this.userService.loadUser(any())).willReturn(principal);
|
||||
|
||||
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
|
||||
@@ -213,7 +213,7 @@ public class OAuth2LoginAuthenticationProviderTests {
|
||||
|
||||
OAuth2User principal = mock(OAuth2User.class);
|
||||
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) invocation -> authorities);
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
|
||||
ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
|
||||
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
|
||||
|
||||
|
||||
+1
-1
@@ -197,7 +197,7 @@ 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())
|
||||
|
||||
+1
-1
@@ -190,7 +190,7 @@ public class WebClientReactiveAuthorizationCodeTokenResponseClientTests {
|
||||
|
||||
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block())
|
||||
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
|
||||
e -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client"))
|
||||
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client"))
|
||||
.hasMessageContaining("unauthorized_client");
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -149,7 +149,7 @@ public class WebClientReactiveClientCredentialsTokenResponseClientTests {
|
||||
|
||||
assertThatThrownBy(() -> this.client.getTokenResponse(request).block())
|
||||
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
|
||||
e -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
|
||||
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
|
||||
.hasMessageContaining("[invalid_token_response]")
|
||||
.hasMessageContaining("Empty OAuth 2.0 Access Token Response");
|
||||
|
||||
|
||||
+3
-3
@@ -149,7 +149,7 @@ public class WebClientReactivePasswordTokenResponseClientTests {
|
||||
|
||||
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
|
||||
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
|
||||
e -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
|
||||
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
|
||||
.hasMessageContaining("[invalid_token_response]")
|
||||
.hasMessageContaining("An error occurred parsing the Access Token response")
|
||||
.hasCauseInstanceOf(Throwable.class);
|
||||
@@ -185,7 +185,7 @@ public class WebClientReactivePasswordTokenResponseClientTests {
|
||||
|
||||
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
|
||||
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
|
||||
e -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client"))
|
||||
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client"))
|
||||
.hasMessageContaining("[unauthorized_client]");
|
||||
}
|
||||
|
||||
@@ -198,7 +198,7 @@ public class WebClientReactivePasswordTokenResponseClientTests {
|
||||
|
||||
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
|
||||
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
|
||||
e -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
|
||||
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
|
||||
.hasMessageContaining("[invalid_token_response]")
|
||||
.hasMessageContaining("Empty OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
+2
-2
@@ -189,7 +189,7 @@ public class WebClientReactiveRefreshTokenTokenResponseClientTests {
|
||||
|
||||
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
|
||||
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
|
||||
e -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client"))
|
||||
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client"))
|
||||
.hasMessageContaining("[unauthorized_client]");
|
||||
}
|
||||
|
||||
@@ -202,7 +202,7 @@ public class WebClientReactiveRefreshTokenTokenResponseClientTests {
|
||||
|
||||
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
|
||||
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
|
||||
e -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
|
||||
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
|
||||
.hasMessageContaining("[invalid_token_response]")
|
||||
.hasMessageContaining("Empty OAuth 2.0 Access Token Response");
|
||||
}
|
||||
|
||||
+1
-1
@@ -267,7 +267,7 @@ public class OAuth2AuthenticationTokenMixinTests {
|
||||
private static String asJson(List<SimpleGrantedAuthority> simpleAuthorities) {
|
||||
// @formatter:off
|
||||
return simpleAuthorities.stream()
|
||||
.map(authority -> "{\n" +
|
||||
.map((authority) -> "{\n" +
|
||||
" \"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\",\n" +
|
||||
" \"authority\": \"" + authority.getAuthority() + "\"\n" +
|
||||
" }")
|
||||
|
||||
+3
-3
@@ -139,14 +139,14 @@ public class OAuth2AuthorizationRequestMixinTests {
|
||||
}
|
||||
String additionalParameters = "\"@class\": \"java.util.Collections$UnmodifiableMap\"";
|
||||
if (!CollectionUtils.isEmpty(authorizationRequest.getAdditionalParameters())) {
|
||||
additionalParameters += "," + authorizationRequest.getAdditionalParameters().keySet().stream()
|
||||
.map(key -> "\"" + key + "\": \"" + authorizationRequest.getAdditionalParameters().get(key) + "\"")
|
||||
additionalParameters += "," + authorizationRequest.getAdditionalParameters().keySet().stream().map(
|
||||
(key) -> "\"" + key + "\": \"" + authorizationRequest.getAdditionalParameters().get(key) + "\"")
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
String attributes = "\"@class\": \"java.util.Collections$UnmodifiableMap\"";
|
||||
if (!CollectionUtils.isEmpty(authorizationRequest.getAttributes())) {
|
||||
attributes += "," + authorizationRequest.getAttributes().keySet().stream()
|
||||
.map(key -> "\"" + key + "\": \"" + authorizationRequest.getAttributes().get(key) + "\"")
|
||||
.map((key) -> "\"" + key + "\": \"" + authorizationRequest.getAttributes().get(key) + "\"")
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
// @formatter:off
|
||||
|
||||
+1
-1
@@ -215,7 +215,7 @@ public class OAuth2AuthorizedClientMixinTests {
|
||||
String configurationMetadata = "\"@class\": \"java.util.Collections$UnmodifiableMap\"";
|
||||
if (!CollectionUtils.isEmpty(providerDetails.getConfigurationMetadata())) {
|
||||
configurationMetadata += "," + providerDetails.getConfigurationMetadata().keySet().stream()
|
||||
.map(key -> "\"" + key + "\": \"" + providerDetails.getConfigurationMetadata().get(key) + "\"")
|
||||
.map((key) -> "\"" + key + "\": \"" + providerDetails.getConfigurationMetadata().get(key) + "\"")
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
// @formatter:off
|
||||
|
||||
+7
-7
@@ -232,7 +232,7 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
|
||||
|
||||
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
|
||||
given(jwtDecoder.decode(anyString())).willThrow(new JwtException("ID Token Validation Error"));
|
||||
this.authenticationProvider.setJwtDecoderFactory(registration -> jwtDecoder);
|
||||
this.authenticationProvider.setJwtDecoderFactory((registration) -> jwtDecoder);
|
||||
|
||||
this.authenticationProvider
|
||||
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
|
||||
@@ -267,7 +267,7 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
|
||||
|
||||
OidcUser principal = mock(OidcUser.class);
|
||||
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) invocation -> authorities);
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
|
||||
given(this.userService.loadUser(any())).willReturn(principal);
|
||||
|
||||
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider
|
||||
@@ -295,13 +295,13 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
|
||||
|
||||
OidcUser principal = mock(OidcUser.class);
|
||||
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) invocation -> authorities);
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
|
||||
given(this.userService.loadUser(any())).willReturn(principal);
|
||||
|
||||
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_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
|
||||
@@ -323,7 +323,7 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
|
||||
|
||||
OidcUser principal = mock(OidcUser.class);
|
||||
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) invocation -> authorities);
|
||||
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
|
||||
ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
|
||||
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
|
||||
|
||||
@@ -335,10 +335,10 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
|
||||
}
|
||||
|
||||
private void setUpIdToken(Map<String, Object> claims) {
|
||||
Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
|
||||
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
|
||||
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
|
||||
given(jwtDecoder.decode(anyString())).willReturn(idToken);
|
||||
this.authenticationProvider.setJwtDecoderFactory(registration -> jwtDecoder);
|
||||
this.authenticationProvider.setJwtDecoderFactory((registration) -> jwtDecoder);
|
||||
}
|
||||
|
||||
private OAuth2AccessTokenResponse accessTokenSuccessResponse() {
|
||||
|
||||
+14
-14
@@ -174,7 +174,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
|
||||
given(this.jwtDecoder.decode(any())).willThrow(new JwtException("ID Token Validation Error"));
|
||||
this.manager.setJwtDecoderFactory(c -> this.jwtDecoder);
|
||||
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
|
||||
|
||||
assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block())
|
||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||
@@ -195,11 +195,11 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
|
||||
claims.put(IdTokenClaimNames.SUB, "sub");
|
||||
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
|
||||
claims.put(IdTokenClaimNames.NONCE, "invalid-nonce-hash");
|
||||
Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
|
||||
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
|
||||
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
|
||||
this.manager.setJwtDecoderFactory(c -> this.jwtDecoder);
|
||||
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
|
||||
|
||||
assertThatThrownBy(() -> this.manager.authenticate(authorizationCodeAuthentication).block())
|
||||
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("[invalid_nonce]");
|
||||
@@ -220,12 +220,12 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
|
||||
claims.put(IdTokenClaimNames.SUB, "rob");
|
||||
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
|
||||
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
|
||||
Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
|
||||
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
|
||||
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
given(this.userService.loadUser(any())).willReturn(Mono.empty());
|
||||
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
|
||||
this.manager.setJwtDecoderFactory(c -> this.jwtDecoder);
|
||||
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
|
||||
assertThat(this.manager.authenticate(authorizationCodeAuthentication).block()).isNull();
|
||||
}
|
||||
|
||||
@@ -243,13 +243,13 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
|
||||
claims.put(IdTokenClaimNames.SUB, "rob");
|
||||
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
|
||||
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
|
||||
Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
|
||||
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
|
||||
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
|
||||
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
|
||||
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
|
||||
this.manager.setJwtDecoderFactory(c -> this.jwtDecoder);
|
||||
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
|
||||
|
||||
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager
|
||||
.authenticate(authorizationCodeAuthentication).block();
|
||||
@@ -274,13 +274,13 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
|
||||
claims.put(IdTokenClaimNames.SUB, "rob");
|
||||
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
|
||||
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
|
||||
Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
|
||||
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
|
||||
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
|
||||
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
|
||||
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
|
||||
this.manager.setJwtDecoderFactory(c -> this.jwtDecoder);
|
||||
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
|
||||
|
||||
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager
|
||||
.authenticate(authorizationCodeAuthentication).block();
|
||||
@@ -309,14 +309,14 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
|
||||
claims.put(IdTokenClaimNames.SUB, "rob");
|
||||
claims.put(IdTokenClaimNames.AUD, Arrays.asList(clientRegistration.getClientId()));
|
||||
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
|
||||
Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
|
||||
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
|
||||
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
|
||||
ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
|
||||
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
|
||||
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
|
||||
this.manager.setJwtDecoderFactory(c -> this.jwtDecoder);
|
||||
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
|
||||
|
||||
this.manager.authenticate(authorizationCodeAuthentication).block();
|
||||
|
||||
@@ -339,7 +339,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
|
||||
claims.put(IdTokenClaimNames.SUB, "rob");
|
||||
claims.put(IdTokenClaimNames.AUD, Collections.singletonList(clientRegistration.getClientId()));
|
||||
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
|
||||
Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
|
||||
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
|
||||
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
|
||||
DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
|
||||
@@ -349,9 +349,9 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
|
||||
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
|
||||
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
|
||||
given(authoritiesMapper.mapAuthorities(anyCollection()))
|
||||
.willAnswer((Answer<List<GrantedAuthority>>) invocation -> mappedAuthorities);
|
||||
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
|
||||
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
|
||||
this.manager.setJwtDecoderFactory(c -> this.jwtDecoder);
|
||||
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
|
||||
this.manager.setAuthoritiesMapper(authoritiesMapper);
|
||||
|
||||
Authentication result = this.manager.authenticate(authorizationCodeAuthentication).block();
|
||||
|
||||
+3
-3
@@ -109,7 +109,7 @@ public class OidcIdTokenDecoderFactoryTests {
|
||||
|
||||
@Test
|
||||
public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> SignatureAlgorithm.ES256);
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> SignatureAlgorithm.ES256);
|
||||
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
|
||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
|
||||
@@ -119,7 +119,7 @@ public class OidcIdTokenDecoderFactoryTests {
|
||||
|
||||
@Test
|
||||
public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() {
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> MacAlgorithm.HS256);
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> MacAlgorithm.HS256);
|
||||
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build()))
|
||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
|
||||
@@ -129,7 +129,7 @@ public class OidcIdTokenDecoderFactoryTests {
|
||||
|
||||
@Test
|
||||
public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() {
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> null);
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> null);
|
||||
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build()))
|
||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
|
||||
|
||||
+19
-19
@@ -92,7 +92,7 @@ public class OidcIdTokenValidatorTests {
|
||||
public void validateWhenIssuerNullThenHasErrors() {
|
||||
this.claims.remove(IdTokenClaimNames.ISS);
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.ISS));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.ISS));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -104,7 +104,7 @@ public class OidcIdTokenValidatorTests {
|
||||
this.registration = this.registration.issuerUri("https://somethingelse.com");
|
||||
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.ISS));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.ISS));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -122,42 +122,42 @@ public class OidcIdTokenValidatorTests {
|
||||
public void validateWhenSubNullThenHasErrors() {
|
||||
this.claims.remove(IdTokenClaimNames.SUB);
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.SUB));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.SUB));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateWhenAudNullThenHasErrors() {
|
||||
this.claims.remove(IdTokenClaimNames.AUD);
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.AUD));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AUD));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateWhenIssuedAtNullThenHasErrors() {
|
||||
this.issuedAt = null;
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.IAT));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.IAT));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateWhenExpiresAtNullThenHasErrors() {
|
||||
this.expiresAt = null;
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.EXP));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.EXP));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateWhenAudMultipleAndAzpNullThenHasErrors() {
|
||||
this.claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id", "other"));
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.AZP));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AZP));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateWhenAzpNotClientIdThenHasErrors() {
|
||||
this.claims.put(IdTokenClaimNames.AZP, "other");
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.AZP));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AZP));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -172,14 +172,14 @@ public class OidcIdTokenValidatorTests {
|
||||
this.claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id-1", "client-id-2"));
|
||||
this.claims.put(IdTokenClaimNames.AZP, "other-client");
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.AZP));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AZP));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateWhenAudNotClientIdThenHasErrors() {
|
||||
this.claims.put(IdTokenClaimNames.AUD, Collections.singletonList("other-client"));
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.AUD));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AUD));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -196,7 +196,7 @@ public class OidcIdTokenValidatorTests {
|
||||
this.expiresAt = this.issuedAt.plus(Duration.ofSeconds(30));
|
||||
this.clockSkew = Duration.ofSeconds(0);
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.EXP));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.EXP));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -213,7 +213,7 @@ public class OidcIdTokenValidatorTests {
|
||||
this.expiresAt = this.issuedAt.plus(Duration.ofSeconds(60));
|
||||
this.clockSkew = Duration.ofMinutes(0);
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.IAT));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.IAT));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -222,7 +222,7 @@ public class OidcIdTokenValidatorTests {
|
||||
this.expiresAt = this.issuedAt.plus(Duration.ofSeconds(5));
|
||||
this.clockSkew = Duration.ofSeconds(0);
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.EXP));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.EXP));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -232,10 +232,10 @@ public class OidcIdTokenValidatorTests {
|
||||
this.issuedAt = null;
|
||||
this.expiresAt = null;
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.SUB))
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.AUD))
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.IAT))
|
||||
.allMatch(msg -> msg.contains(IdTokenClaimNames.EXP));
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.SUB))
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.AUD))
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.IAT))
|
||||
.allMatch((msg) -> msg.contains(IdTokenClaimNames.EXP));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -243,12 +243,12 @@ public class OidcIdTokenValidatorTests {
|
||||
this.claims.remove(IdTokenClaimNames.SUB);
|
||||
this.claims.remove(IdTokenClaimNames.AUD);
|
||||
assertThat(this.validateIdToken()).hasSize(1).extracting(OAuth2Error::getDescription)
|
||||
.allMatch(msg -> msg.equals("The ID Token contains invalid claims: {sub=null, aud=null}"));
|
||||
.allMatch((msg) -> msg.equals("The ID Token contains invalid claims: {sub=null, aud=null}"));
|
||||
}
|
||||
|
||||
private Collection<OAuth2Error> validateIdToken() {
|
||||
Jwt idToken = Jwt.withTokenValue("token").issuedAt(this.issuedAt).expiresAt(this.expiresAt)
|
||||
.headers(h -> h.putAll(this.headers)).claims(c -> c.putAll(this.claims)).build();
|
||||
.headers((h) -> h.putAll(this.headers)).claims((c) -> c.putAll(this.claims)).build();
|
||||
OidcIdTokenValidator validator = new OidcIdTokenValidator(this.registration.build());
|
||||
validator.setClockSkew(this.clockSkew);
|
||||
return validator.validate(idToken).getErrors();
|
||||
|
||||
+3
-3
@@ -109,7 +109,7 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
|
||||
|
||||
@Test
|
||||
public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> SignatureAlgorithm.ES256);
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> SignatureAlgorithm.ES256);
|
||||
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
|
||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
|
||||
@@ -119,7 +119,7 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
|
||||
|
||||
@Test
|
||||
public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() {
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> MacAlgorithm.HS256);
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> MacAlgorithm.HS256);
|
||||
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build()))
|
||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
|
||||
@@ -129,7 +129,7 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
|
||||
|
||||
@Test
|
||||
public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() {
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> null);
|
||||
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> null);
|
||||
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build()))
|
||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
|
||||
|
||||
+2
-2
@@ -98,7 +98,7 @@ public class DefaultReactiveOAuth2UserServiceTests {
|
||||
public void loadUserWhenUserInfoUriIsNullThenThrowOAuth2AuthenticationException() {
|
||||
this.clientRegistration.userInfoUri(null);
|
||||
|
||||
StepVerifier.create(this.userService.loadUser(oauth2UserRequest())).expectErrorSatisfies(t -> assertThat(t)
|
||||
StepVerifier.create(this.userService.loadUser(oauth2UserRequest())).expectErrorSatisfies((t) -> assertThat(t)
|
||||
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("missing_user_info_uri"))
|
||||
.verify();
|
||||
}
|
||||
@@ -107,7 +107,7 @@ public class DefaultReactiveOAuth2UserServiceTests {
|
||||
public void loadUserWhenUserNameAttributeNameIsNullThenThrowOAuth2AuthenticationException() {
|
||||
this.clientRegistration.userNameAttributeName(null);
|
||||
|
||||
StepVerifier.create(this.userService.loadUser(oauth2UserRequest())).expectErrorSatisfies(t -> assertThat(t)
|
||||
StepVerifier.create(this.userService.loadUser(oauth2UserRequest())).expectErrorSatisfies((t) -> assertThat(t)
|
||||
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("missing_user_name_attribute"))
|
||||
.verify();
|
||||
}
|
||||
|
||||
+8
-7
@@ -458,8 +458,8 @@ public class DefaultOAuth2AuthorizationRequestResolverTests {
|
||||
request.setServletPath(requestUri);
|
||||
|
||||
this.resolver.setAuthorizationRequestCustomizer(
|
||||
customizer -> customizer.additionalParameters(params -> params.remove(OidcParameterNames.NONCE))
|
||||
.attributes(attrs -> attrs.remove(OidcParameterNames.NONCE)));
|
||||
(customizer) -> customizer.additionalParameters((params) -> params.remove(OidcParameterNames.NONCE))
|
||||
.attributes((attrs) -> attrs.remove(OidcParameterNames.NONCE)));
|
||||
|
||||
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
|
||||
assertThat(authorizationRequest.getAdditionalParameters()).doesNotContainKey(OidcParameterNames.NONCE);
|
||||
@@ -478,10 +478,11 @@ public class DefaultOAuth2AuthorizationRequestResolverTests {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
|
||||
request.setServletPath(requestUri);
|
||||
|
||||
this.resolver.setAuthorizationRequestCustomizer(customizer -> customizer.authorizationRequestUri(uriBuilder -> {
|
||||
uriBuilder.queryParam("param1", "value1");
|
||||
return uriBuilder.build();
|
||||
}));
|
||||
this.resolver
|
||||
.setAuthorizationRequestCustomizer((customizer) -> customizer.authorizationRequestUri((uriBuilder) -> {
|
||||
uriBuilder.queryParam("param1", "value1");
|
||||
return uriBuilder.build();
|
||||
}));
|
||||
|
||||
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
|
||||
assertThat(authorizationRequest.getAuthorizationRequestUri())
|
||||
@@ -498,7 +499,7 @@ public class DefaultOAuth2AuthorizationRequestResolverTests {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
|
||||
request.setServletPath(requestUri);
|
||||
|
||||
this.resolver.setAuthorizationRequestCustomizer(customizer -> customizer.parameters(params -> {
|
||||
this.resolver.setAuthorizationRequestCustomizer((customizer) -> customizer.parameters((params) -> {
|
||||
params.put("appid", params.get("client_id"));
|
||||
params.remove("client_id");
|
||||
}));
|
||||
|
||||
+11
-11
@@ -194,7 +194,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() {
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId("invalid-registration-id").principal(this.principal).attributes(attrs -> {
|
||||
.withClientRegistrationId("invalid-registration-id").principal(this.principal).attributes((attrs) -> {
|
||||
attrs.put(HttpServletRequest.class.getName(), this.request);
|
||||
attrs.put(HttpServletResponse.class.getName(), this.response);
|
||||
}).build();
|
||||
@@ -211,7 +211,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
|
||||
.attributes(attrs -> {
|
||||
.attributes((attrs) -> {
|
||||
attrs.put(HttpServletRequest.class.getName(), this.request);
|
||||
attrs.put(HttpServletResponse.class.getName(), this.response);
|
||||
}).build();
|
||||
@@ -241,7 +241,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
|
||||
.attributes(attrs -> {
|
||||
.attributes((attrs) -> {
|
||||
attrs.put(HttpServletRequest.class.getName(), this.request);
|
||||
attrs.put(HttpServletResponse.class.getName(), this.response);
|
||||
}).build();
|
||||
@@ -278,7 +278,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
|
||||
.attributes(attrs -> {
|
||||
.attributes((attrs) -> {
|
||||
attrs.put(HttpServletRequest.class.getName(), this.request);
|
||||
attrs.put(HttpServletResponse.class.getName(), this.response);
|
||||
}).build();
|
||||
@@ -308,7 +308,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
.willReturn(this.authorizedClient);
|
||||
|
||||
// Set custom contextAttributesMapper
|
||||
this.authorizedClientManager.setContextAttributesMapper(authorizeRequest -> {
|
||||
this.authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
|
||||
Map<String, Object> contextAttributes = new HashMap<>();
|
||||
HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
|
||||
String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
|
||||
@@ -325,7 +325,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
|
||||
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
|
||||
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
|
||||
.attributes(attrs -> {
|
||||
.attributes((attrs) -> {
|
||||
attrs.put(HttpServletRequest.class.getName(), this.request);
|
||||
attrs.put(HttpServletResponse.class.getName(), this.response);
|
||||
}).build();
|
||||
@@ -344,7 +344,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
@Test
|
||||
public void reauthorizeWhenUnsupportedProviderThenNotReauthorized() {
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).attributes(attrs -> {
|
||||
.principal(this.principal).attributes((attrs) -> {
|
||||
attrs.put(HttpServletRequest.class.getName(), this.request);
|
||||
attrs.put(HttpServletResponse.class.getName(), this.response);
|
||||
}).build();
|
||||
@@ -374,7 +374,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
.willReturn(reauthorizedClient);
|
||||
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).attributes(attrs -> {
|
||||
.principal(this.principal).attributes((attrs) -> {
|
||||
attrs.put(HttpServletRequest.class.getName(), this.request);
|
||||
attrs.put(HttpServletResponse.class.getName(), this.response);
|
||||
}).build();
|
||||
@@ -410,7 +410,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
this.request.addParameter(OAuth2ParameterNames.SCOPE, "read write");
|
||||
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).attributes(attrs -> {
|
||||
.principal(this.principal).attributes((attrs) -> {
|
||||
attrs.put(HttpServletRequest.class.getName(), this.request);
|
||||
attrs.put(HttpServletResponse.class.getName(), this.response);
|
||||
}).build();
|
||||
@@ -434,7 +434,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
.willThrow(authorizationException);
|
||||
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).attributes(attrs -> {
|
||||
.principal(this.principal).attributes((attrs) -> {
|
||||
attrs.put(HttpServletRequest.class.getName(), this.request);
|
||||
attrs.put(HttpServletResponse.class.getName(), this.response);
|
||||
}).build();
|
||||
@@ -457,7 +457,7 @@ public class DefaultOAuth2AuthorizedClientManagerTests {
|
||||
.willThrow(authorizationException);
|
||||
|
||||
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
|
||||
.principal(this.principal).attributes(attrs -> {
|
||||
.principal(this.principal).attributes((attrs) -> {
|
||||
attrs.put(HttpServletRequest.class.getName(), this.request);
|
||||
attrs.put(HttpServletResponse.class.getName(), this.response);
|
||||
}).build();
|
||||
|
||||
+4
-4
@@ -498,8 +498,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests {
|
||||
.willReturn(Mono.just(this.authorizedClient));
|
||||
|
||||
// Set custom contextAttributesMapper capable of mapping the form parameters
|
||||
this.authorizedClientManager.setContextAttributesMapper(
|
||||
authorizeRequest -> currentServerWebExchange().flatMap(ServerWebExchange::getFormData).map(formData -> {
|
||||
this.authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> currentServerWebExchange()
|
||||
.flatMap(ServerWebExchange::getFormData).map((formData) -> {
|
||||
Map<String, Object> contextAttributes = new HashMap<>();
|
||||
String username = formData.getFirst(OAuth2ParameterNames.USERNAME);
|
||||
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
|
||||
@@ -605,8 +605,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests {
|
||||
}
|
||||
|
||||
private Mono<ServerWebExchange> currentServerWebExchange() {
|
||||
return Mono.subscriberContext().filter(c -> c.hasKey(ServerWebExchange.class))
|
||||
.map(c -> c.get(ServerWebExchange.class));
|
||||
return Mono.subscriberContext().filter((c) -> c.hasKey(ServerWebExchange.class))
|
||||
.map((c) -> c.get(ServerWebExchange.class));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -445,7 +445,7 @@ public class OAuth2AuthorizationCodeGrantFilterTests {
|
||||
request.setServletPath(requestUri);
|
||||
if (!CollectionUtils.isEmpty(parameters)) {
|
||||
parameters.forEach(request::addParameter);
|
||||
request.setQueryString(parameters.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue())
|
||||
request.setQueryString(parameters.entrySet().stream().map((e) -> e.getKey() + "=" + e.getValue())
|
||||
.collect(Collectors.joining("&")));
|
||||
}
|
||||
return request;
|
||||
@@ -465,7 +465,7 @@ public class OAuth2AuthorizationCodeGrantFilterTests {
|
||||
authorizationResponse.addParameter(OAuth2ParameterNames.STATE, "state");
|
||||
additionalParameters.forEach(authorizationResponse::addParameter);
|
||||
authorizationResponse.setQueryString(authorizationResponse.getParameterMap().entrySet().stream()
|
||||
.map(e -> e.getKey() + "=" + e.getValue()[0]).collect(Collectors.joining("&")));
|
||||
.map((e) -> e.getKey() + "=" + e.getValue()[0]).collect(Collectors.joining("&")));
|
||||
authorizationResponse.setSession(authorizationRequest.getSession());
|
||||
return authorizationResponse;
|
||||
}
|
||||
|
||||
+1
-1
@@ -303,7 +303,7 @@ public class OAuth2AuthorizedClientArgumentResolverTests {
|
||||
authorizedClientManager.setAuthorizedClientProvider(passwordAuthorizedClientProvider);
|
||||
|
||||
// Set custom contextAttributesMapper
|
||||
authorizedClientManager.setContextAttributesMapper(authorizeRequest -> {
|
||||
authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
|
||||
Map<String, Object> contextAttributes = new HashMap<>();
|
||||
HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
|
||||
String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
|
||||
|
||||
+2
-2
@@ -228,7 +228,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests {
|
||||
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
|
||||
.clientRegistrationId(clientRegistration1.getRegistrationId()))
|
||||
.retrieve().bodyToMono(String.class)
|
||||
.flatMap(response -> this.webClient.get().uri(this.serverUrl)
|
||||
.flatMap((response) -> this.webClient.get().uri(this.serverUrl)
|
||||
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
|
||||
.clientRegistrationId(clientRegistration2.getRegistrationId()))
|
||||
.retrieve().bodyToMono(String.class))
|
||||
@@ -281,7 +281,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests {
|
||||
|
||||
// first try should fail, and remove the cached authorized client
|
||||
assertThatCode(requestMono::block).isInstanceOfSatisfying(WebClientResponseException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
(e) -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
|
||||
assertThat(this.server.getRequestCount()).isEqualTo(1);
|
||||
|
||||
|
||||
+15
-13
@@ -162,10 +162,12 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
public void setup() {
|
||||
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
|
||||
.builder().authorizationCode()
|
||||
.refreshToken(configurer -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.refreshToken(
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.clientCredentials(
|
||||
configurer -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.password(configurer -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient)).build();
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient))
|
||||
.build();
|
||||
this.authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
|
||||
this.clientRegistrationRepository, this.authorizedClientRepository);
|
||||
this.authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
@@ -445,7 +447,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
|
||||
|
||||
assertThat(this.authorizationExceptionCaptor.getValue())
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, e -> {
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> {
|
||||
assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
|
||||
assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token");
|
||||
assertThat(e).hasNoCause();
|
||||
@@ -474,7 +476,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
WebClientResponseException exception = WebClientResponseException.create(HttpStatus.UNAUTHORIZED.value(),
|
||||
HttpStatus.UNAUTHORIZED.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8);
|
||||
|
||||
ExchangeFunction throwingExchangeFunction = r -> Mono.error(exception);
|
||||
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
|
||||
|
||||
assertThatCode(() -> this.function.filter(request, throwingExchangeFunction)
|
||||
.subscriberContext(serverWebExchange()).block()).isEqualTo(exception);
|
||||
@@ -485,7 +487,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
|
||||
|
||||
assertThat(this.authorizationExceptionCaptor.getValue())
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, e -> {
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> {
|
||||
assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
|
||||
assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token");
|
||||
assertThat(e).hasCause(exception);
|
||||
@@ -521,7 +523,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
|
||||
|
||||
assertThat(this.authorizationExceptionCaptor.getValue())
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, e -> {
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> {
|
||||
assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
|
||||
assertThat(e.getError().getErrorCode()).isEqualTo("insufficient_scope");
|
||||
assertThat(e).hasNoCause();
|
||||
@@ -550,7 +552,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
WebClientResponseException exception = WebClientResponseException.create(HttpStatus.FORBIDDEN.value(),
|
||||
HttpStatus.FORBIDDEN.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8);
|
||||
|
||||
ExchangeFunction throwingExchangeFunction = r -> Mono.error(exception);
|
||||
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
|
||||
|
||||
assertThatCode(() -> this.function.filter(request, throwingExchangeFunction)
|
||||
.subscriberContext(serverWebExchange()).block()).isEqualTo(exception);
|
||||
@@ -561,7 +563,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
|
||||
|
||||
assertThat(this.authorizationExceptionCaptor.getValue())
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, e -> {
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> {
|
||||
assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
|
||||
assertThat(e.getError().getErrorCode()).isEqualTo("insufficient_scope");
|
||||
assertThat(e).hasCause(exception);
|
||||
@@ -603,7 +605,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
|
||||
|
||||
assertThat(this.authorizationExceptionCaptor.getValue())
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, e -> {
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> {
|
||||
assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
|
||||
assertThat(e.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
|
||||
assertThat(e.getError().getDescription())
|
||||
@@ -635,7 +637,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(
|
||||
new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, null, null));
|
||||
|
||||
ExchangeFunction throwingExchangeFunction = r -> Mono.error(exception);
|
||||
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
|
||||
|
||||
assertThatCode(() -> this.function.filter(request, throwingExchangeFunction)
|
||||
.subscriberContext(serverWebExchange()).block()).isEqualTo(exception);
|
||||
@@ -684,9 +686,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
eq(authentication), any())).willReturn(Mono.empty());
|
||||
|
||||
// Set custom contextAttributesMapper capable of mapping the form parameters
|
||||
this.authorizedClientManager.setContextAttributesMapper(authorizeRequest -> {
|
||||
this.authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
|
||||
ServerWebExchange serverWebExchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
|
||||
return Mono.just(serverWebExchange).flatMap(ServerWebExchange::getFormData).map(formData -> {
|
||||
return Mono.just(serverWebExchange).flatMap(ServerWebExchange::getFormData).map((formData) -> {
|
||||
Map<String, Object> contextAttributes = new HashMap<>();
|
||||
String username = formData.getFirst(OAuth2ParameterNames.USERNAME);
|
||||
String password = formData.getFirst(OAuth2ParameterNames.PASSWORD);
|
||||
|
||||
+1
-1
@@ -244,7 +244,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests {
|
||||
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
|
||||
.clientRegistrationId(clientRegistration1.getRegistrationId()))
|
||||
.retrieve().bodyToMono(String.class)
|
||||
.flatMap(response -> this.webClient.get().uri(this.serverUrl)
|
||||
.flatMap((response) -> this.webClient.get().uri(this.serverUrl)
|
||||
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
|
||||
.clientRegistrationId(clientRegistration2.getRegistrationId()))
|
||||
.retrieve().bodyToMono(String.class))
|
||||
|
||||
+16
-13
@@ -182,10 +182,12 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
this.authentication = new TestingAuthenticationToken("test", "this");
|
||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
|
||||
.authorizationCode()
|
||||
.refreshToken(configurer -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.refreshToken(
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
|
||||
.clientCredentials(
|
||||
configurer -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.password(configurer -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient)).build();
|
||||
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
|
||||
.password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient))
|
||||
.build();
|
||||
this.authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository,
|
||||
this.authorizedClientRepository);
|
||||
this.authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
|
||||
@@ -506,7 +508,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
.willReturn(registration);
|
||||
|
||||
// Set custom contextAttributesMapper
|
||||
this.authorizedClientManager.setContextAttributesMapper(authorizeRequest -> {
|
||||
this.authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
|
||||
Map<String, Object> contextAttributes = new HashMap<>();
|
||||
HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
|
||||
String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
|
||||
@@ -658,15 +660,16 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
|
||||
// Default request attributes set
|
||||
final ClientRequest request1 = ClientRequest.create(HttpMethod.GET, URI.create("https://example1.com"))
|
||||
.attributes(attrs -> attrs.putAll(getDefaultRequestAttributes())).build();
|
||||
.attributes((attrs) -> attrs.putAll(getDefaultRequestAttributes())).build();
|
||||
|
||||
// Default request attributes NOT set
|
||||
final ClientRequest request2 = ClientRequest.create(HttpMethod.GET, URI.create("https://example2.com")).build();
|
||||
|
||||
Context context = context(servletRequest, servletResponse, authentication);
|
||||
|
||||
this.function.filter(request1, this.exchange).flatMap(response -> this.function.filter(request2, this.exchange))
|
||||
.subscriberContext(context).block();
|
||||
this.function.filter(request1, this.exchange)
|
||||
.flatMap((response) -> this.function.filter(request2, this.exchange)).subscriberContext(context)
|
||||
.block();
|
||||
|
||||
List<ClientRequest> requests = this.exchange.getRequests();
|
||||
assertThat(requests).hasSize(2);
|
||||
@@ -716,7 +719,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
|
||||
|
||||
assertThat(this.authorizationExceptionCaptor.getValue())
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, e -> {
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> {
|
||||
assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
|
||||
assertThat(e.getError().getErrorCode()).isEqualTo(expectedErrorCode);
|
||||
assertThat(e).hasNoCause();
|
||||
@@ -756,7 +759,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
|
||||
|
||||
assertThat(this.authorizationExceptionCaptor.getValue())
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, e -> {
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> {
|
||||
assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
|
||||
assertThat(e.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
|
||||
assertThat(e.getError().getDescription())
|
||||
@@ -799,7 +802,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
|
||||
WebClientResponseException exception = WebClientResponseException.create(httpStatus.value(),
|
||||
httpStatus.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8);
|
||||
ExchangeFunction throwingExchangeFunction = r -> Mono.error(exception);
|
||||
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
|
||||
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
|
||||
|
||||
assertThatCode(() -> this.function.filter(request, throwingExchangeFunction).block()).isEqualTo(exception);
|
||||
@@ -808,7 +811,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
|
||||
|
||||
assertThat(this.authorizationExceptionCaptor.getValue())
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, e -> {
|
||||
.isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> {
|
||||
assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
|
||||
assertThat(e.getError().getErrorCode()).isEqualTo(expectedErrorCode);
|
||||
assertThat(e).hasCause(exception);
|
||||
@@ -835,7 +838,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
|
||||
OAuth2AuthorizationException authorizationException = new OAuth2AuthorizationException(
|
||||
new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN));
|
||||
ExchangeFunction throwingExchangeFunction = r -> Mono.error(authorizationException);
|
||||
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(authorizationException);
|
||||
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
|
||||
|
||||
assertThatCode(() -> this.function.filter(request, throwingExchangeFunction).block())
|
||||
@@ -845,7 +848,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
|
||||
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
|
||||
|
||||
assertThat(this.authorizationExceptionCaptor.getValue())
|
||||
.isInstanceOfSatisfying(OAuth2AuthorizationException.class, e -> {
|
||||
.isInstanceOfSatisfying(OAuth2AuthorizationException.class, (e) -> {
|
||||
assertThat(e.getError().getErrorCode()).isEqualTo(authorizationException.getError().getErrorCode());
|
||||
assertThat(e).hasNoCause();
|
||||
assertThat(e).hasMessageContaining(OAuth2ErrorCodes.INVALID_TOKEN);
|
||||
|
||||
+8
-7
@@ -146,8 +146,8 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests {
|
||||
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
|
||||
|
||||
this.resolver.setAuthorizationRequestCustomizer(
|
||||
customizer -> customizer.additionalParameters(params -> params.remove(OidcParameterNames.NONCE))
|
||||
.attributes(attrs -> attrs.remove(OidcParameterNames.NONCE)));
|
||||
(customizer) -> customizer.additionalParameters((params) -> params.remove(OidcParameterNames.NONCE))
|
||||
.attributes((attrs) -> attrs.remove(OidcParameterNames.NONCE)));
|
||||
|
||||
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
|
||||
|
||||
@@ -164,10 +164,11 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(any()))
|
||||
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
|
||||
|
||||
this.resolver.setAuthorizationRequestCustomizer(customizer -> customizer.authorizationRequestUri(uriBuilder -> {
|
||||
uriBuilder.queryParam("param1", "value1");
|
||||
return uriBuilder.build();
|
||||
}));
|
||||
this.resolver
|
||||
.setAuthorizationRequestCustomizer((customizer) -> customizer.authorizationRequestUri((uriBuilder) -> {
|
||||
uriBuilder.queryParam("param1", "value1");
|
||||
return uriBuilder.build();
|
||||
}));
|
||||
|
||||
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
|
||||
|
||||
@@ -182,7 +183,7 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests {
|
||||
given(this.clientRegistrationRepository.findByRegistrationId(any()))
|
||||
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
|
||||
|
||||
this.resolver.setAuthorizationRequestCustomizer(customizer -> customizer.parameters(params -> {
|
||||
this.resolver.setAuthorizationRequestCustomizer((customizer) -> customizer.parameters((params) -> {
|
||||
params.put("appid", params.get("client_id"));
|
||||
params.remove("client_id");
|
||||
}));
|
||||
|
||||
+9
-9
@@ -119,7 +119,7 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests {
|
||||
@Test
|
||||
public void filterWhenNotMatchThenAuthenticationManagerNotCalled() {
|
||||
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain(e -> e.getResponse().setComplete(),
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
|
||||
Collections.emptyList());
|
||||
|
||||
this.filter.filter(exchange, chain).block();
|
||||
@@ -146,7 +146,7 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests {
|
||||
|
||||
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
|
||||
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain(e -> e.getResponse().setComplete(),
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
|
||||
Collections.emptyList());
|
||||
|
||||
this.filter.filter(exchange, chain).block();
|
||||
@@ -178,7 +178,7 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests {
|
||||
|
||||
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
|
||||
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain(e -> e.getResponse().setComplete(),
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
|
||||
Collections.emptyList());
|
||||
|
||||
this.filter.filter(exchange, chain).block();
|
||||
@@ -216,7 +216,7 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests {
|
||||
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(
|
||||
createAuthorizationRequest(requestUri, parametersNotMatch));
|
||||
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain(e -> e.getResponse().setComplete(),
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
|
||||
Collections.emptyList());
|
||||
|
||||
this.filter.filter(exchange, chain).block();
|
||||
@@ -260,7 +260,7 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests {
|
||||
|
||||
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
|
||||
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain(e -> e.getResponse().setComplete(),
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
|
||||
Collections.emptyList());
|
||||
|
||||
ServerRequestCache requestCache = mock(ServerRequestCache.class);
|
||||
@@ -291,12 +291,12 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests {
|
||||
|
||||
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
|
||||
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain(e -> e.getResponse().setComplete(),
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
|
||||
Collections.emptyList());
|
||||
|
||||
assertThatThrownBy(() -> this.filter.filter(exchange, chain).block())
|
||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError()).extracting("errorCode")
|
||||
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()).extracting("errorCode")
|
||||
.isEqualTo("client_registration_not_found");
|
||||
verifyNoInteractions(this.authenticationManager);
|
||||
}
|
||||
@@ -320,12 +320,12 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests {
|
||||
|
||||
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
|
||||
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain(e -> e.getResponse().setComplete(),
|
||||
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
|
||||
Collections.emptyList());
|
||||
|
||||
assertThatThrownBy(() -> this.filter.filter(exchange, chain).block())
|
||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError()).extracting("errorCode")
|
||||
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()).extracting("errorCode")
|
||||
.isEqualTo("authorization_error");
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -69,7 +69,7 @@ public class OAuth2AuthorizationRequestRedirectWebFilterTests {
|
||||
public void setup() {
|
||||
this.filter = new OAuth2AuthorizationRequestRedirectWebFilter(this.clientRepository);
|
||||
this.filter.setAuthorizationRequestRepository(this.authzRequestRepository);
|
||||
FilteringWebHandler webHandler = new FilteringWebHandler(e -> e.getResponse().setComplete(),
|
||||
FilteringWebHandler webHandler = new FilteringWebHandler((e) -> e.getResponse().setComplete(),
|
||||
Arrays.asList(this.filter));
|
||||
|
||||
this.client = WebTestClient.bindToWebHandler(webHandler).build();
|
||||
@@ -125,7 +125,7 @@ public class OAuth2AuthorizationRequestRedirectWebFilterTests {
|
||||
@Test
|
||||
public void filterWhenExceptionThenRedirected() {
|
||||
FilteringWebHandler webHandler = new FilteringWebHandler(
|
||||
e -> Mono.error(new ClientAuthorizationRequiredException(this.registration.getRegistrationId())),
|
||||
(e) -> Mono.error(new ClientAuthorizationRequiredException(this.registration.getRegistrationId())),
|
||||
Arrays.asList(this.filter));
|
||||
this.client = WebTestClient.bindToWebHandler(webHandler).build();
|
||||
FluxExchangeResult<String> result = this.client.get().uri("https://example.com/foo").exchange().expectStatus()
|
||||
@@ -137,7 +137,7 @@ public class OAuth2AuthorizationRequestRedirectWebFilterTests {
|
||||
this.filter.setRequestCache(this.requestCache);
|
||||
given(this.requestCache.saveRequest(any())).willReturn(Mono.empty());
|
||||
FilteringWebHandler webHandler = new FilteringWebHandler(
|
||||
e -> Mono.error(new ClientAuthorizationRequiredException(this.registration.getRegistrationId())),
|
||||
(e) -> Mono.error(new ClientAuthorizationRequiredException(this.registration.getRegistrationId())),
|
||||
Arrays.asList(this.filter));
|
||||
this.client = WebTestClient.bindToWebHandler(webHandler).build();
|
||||
this.client.get().uri("https://example.com/foo").exchange().expectStatus().is3xxRedirection()
|
||||
|
||||
+4
-4
@@ -75,7 +75,7 @@ public class WebSessionOAuth2ServerAuthorizationRequestRepositoryTests {
|
||||
@Test
|
||||
public void loadAuthorizationRequestWhenSessionAndNoRequestThenEmpty() {
|
||||
Mono<OAuth2AuthorizationRequest> setAttrThenLoad = this.exchange.getSession().map(WebSession::getAttributes)
|
||||
.doOnNext(attrs -> attrs.put("foo", "bar"))
|
||||
.doOnNext((attrs) -> attrs.put("foo", "bar"))
|
||||
.then(this.repository.loadAuthorizationRequest(this.exchange));
|
||||
|
||||
StepVerifier.create(setAttrThenLoad).verifyComplete();
|
||||
@@ -109,7 +109,7 @@ public class WebSessionOAuth2ServerAuthorizationRequestRepositoryTests {
|
||||
.authorizationUri("https://example.com/oauth2/authorize").clientId("client-id")
|
||||
.redirectUri("http://localhost/client-1").state(oldState).build();
|
||||
|
||||
WebSessionManager sessionManager = e -> this.exchange.getSession();
|
||||
WebSessionManager sessionManager = (e) -> this.exchange.getSession();
|
||||
|
||||
this.exchange = new DefaultServerWebExchange(this.exchange.getRequest(), new MockServerHttpResponse(),
|
||||
sessionManager, ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver());
|
||||
@@ -192,7 +192,7 @@ public class WebSessionOAuth2ServerAuthorizationRequestRepositoryTests {
|
||||
.authorizationUri("https://example.com/oauth2/authorize").clientId("client-id")
|
||||
.redirectUri("http://localhost/client-1").state(oldState).build();
|
||||
|
||||
WebSessionManager sessionManager = e -> this.exchange.getSession();
|
||||
WebSessionManager sessionManager = (e) -> this.exchange.getSession();
|
||||
|
||||
this.exchange = new DefaultServerWebExchange(this.exchange.getRequest(), new MockServerHttpResponse(),
|
||||
sessionManager, ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver());
|
||||
@@ -226,7 +226,7 @@ public class WebSessionOAuth2ServerAuthorizationRequestRepositoryTests {
|
||||
Map<String, Object> sessionAttrs = spy(new HashMap<>());
|
||||
WebSession session = mock(WebSession.class);
|
||||
given(session.getAttributes()).willReturn(sessionAttrs);
|
||||
WebSessionManager sessionManager = e -> Mono.just(session);
|
||||
WebSessionManager sessionManager = (e) -> Mono.just(session);
|
||||
|
||||
this.exchange = new DefaultServerWebExchange(this.exchange.getRequest(), new MockServerHttpResponse(),
|
||||
sessionManager, ServerCodecConfigurer.create(), new AcceptHeaderLocaleContextResolver());
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ public class OAuth2LoginAuthenticationWebFilterTests {
|
||||
this.filter = new OAuth2LoginAuthenticationWebFilter(this.authenticationManager,
|
||||
this.authorizedClientRepository);
|
||||
this.webFilterExchange = new WebFilterExchange(MockServerWebExchange.from(MockServerHttpRequest.get("/")),
|
||||
new DefaultWebFilterChain(exchange -> exchange.getResponse().setComplete()));
|
||||
new DefaultWebFilterChain((exchange) -> exchange.getResponse().setComplete()));
|
||||
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -245,14 +245,14 @@ public final class OAuth2AuthorizationRequest implements Serializable {
|
||||
|
||||
private Map<String, Object> additionalParameters = new LinkedHashMap<>();
|
||||
|
||||
private Consumer<Map<String, Object>> parametersConsumer = params -> {
|
||||
private Consumer<Map<String, Object>> parametersConsumer = (params) -> {
|
||||
};
|
||||
|
||||
private Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
|
||||
private String authorizationRequestUri;
|
||||
|
||||
private Function<UriBuilder, URI> authorizationRequestUriFunction = builder -> builder.build();
|
||||
private Function<UriBuilder, URI> authorizationRequestUriFunction = (builder) -> builder.build();
|
||||
|
||||
private final DefaultUriBuilderFactory uriBuilderFactory;
|
||||
|
||||
|
||||
+1
-1
@@ -80,7 +80,7 @@ public class OAuth2AccessTokenResponseHttpMessageConverter
|
||||
Map<String, Object> tokenResponseParameters = (Map<String, Object>) this.jsonMessageConverter
|
||||
.read(PARAMETERIZED_RESPONSE_TYPE.getType(), null, inputMessage);
|
||||
return this.tokenResponseConverter.convert(tokenResponseParameters.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, entry -> String.valueOf(entry.getValue()))));
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> String.valueOf(entry.getValue()))));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new HttpMessageNotReadableException(
|
||||
|
||||
+1
-1
@@ -79,7 +79,7 @@ public class OAuth2ErrorHttpMessageConverter extends AbstractHttpMessageConverte
|
||||
Map<String, Object> errorParameters = (Map<String, Object>) this.jsonMessageConverter
|
||||
.read(PARAMETERIZED_RESPONSE_TYPE.getType(), null, inputMessage);
|
||||
return this.errorConverter.convert(errorParameters.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, entry -> String.valueOf(entry.getValue()))));
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> String.valueOf(entry.getValue()))));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new HttpMessageNotReadableException(
|
||||
|
||||
+1
-1
@@ -62,7 +62,7 @@ class OAuth2AccessTokenResponseBodyExtractor
|
||||
};
|
||||
BodyExtractor<Mono<Map<String, Object>>, ReactiveHttpInputMessage> delegate = BodyExtractors.toMono(type);
|
||||
return delegate.extract(inputMessage, context)
|
||||
.onErrorMap(e -> new OAuth2AuthorizationException(
|
||||
.onErrorMap((e) -> new OAuth2AuthorizationException(
|
||||
invalidTokenResponse("An error occurred parsing the Access Token response: " + e.getMessage()),
|
||||
e))
|
||||
.switchIfEmpty(Mono.error(() -> new OAuth2AuthorizationException(
|
||||
|
||||
+2
-1
@@ -84,7 +84,8 @@ public class ClaimTypeConverterTests {
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -165,7 +165,7 @@ public class OAuth2AuthorizationRequestTests {
|
||||
public void buildWhenAuthorizationRequestUriFunctionSetThenOverridesDefault() {
|
||||
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
|
||||
.authorizationUri(AUTHORIZATION_URI).clientId(CLIENT_ID).redirectUri(REDIRECT_URI).scopes(SCOPES)
|
||||
.state(STATE).authorizationRequestUri(uriBuilder -> URI.create(AUTHORIZATION_URI)).build();
|
||||
.state(STATE).authorizationRequestUri((uriBuilder) -> URI.create(AUTHORIZATION_URI)).build();
|
||||
assertThat(authorizationRequest.getAuthorizationRequestUri()).isEqualTo(AUTHORIZATION_URI);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -97,7 +97,7 @@ public class OidcIdTokenBuilderTests {
|
||||
public void claimsWhenRemovingAClaimThenIsNotPresent() {
|
||||
OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token").claim("needs", "a claim");
|
||||
|
||||
OidcIdToken idToken = idTokenBuilder.subject("sub").claims(claims -> claims.remove(IdTokenClaimNames.SUB))
|
||||
OidcIdToken idToken = idTokenBuilder.subject("sub").claims((claims) -> claims.remove(IdTokenClaimNames.SUB))
|
||||
.build();
|
||||
assertThat(idToken.getSubject()).isNull();
|
||||
}
|
||||
@@ -108,7 +108,7 @@ public class OidcIdTokenBuilderTests {
|
||||
|
||||
String name = new String("name");
|
||||
String value = new String("value");
|
||||
OidcIdToken idToken = idTokenBuilder.claims(claims -> claims.put(name, value)).build();
|
||||
OidcIdToken idToken = idTokenBuilder.claims((claims) -> claims.put(name, value)).build();
|
||||
|
||||
assertThat(idToken.getClaims()).hasSize(1);
|
||||
assertThat(idToken.getClaims().get(name)).isSameAs(value);
|
||||
|
||||
+2
-2
@@ -59,7 +59,7 @@ public class OidcUserInfoBuilderTests {
|
||||
public void claimsWhenRemovingAClaimThenIsNotPresent() {
|
||||
OidcUserInfo.Builder userInfoBuilder = OidcUserInfo.builder().claim("needs", "a claim");
|
||||
|
||||
OidcUserInfo userInfo = userInfoBuilder.subject("sub").claims(claims -> claims.remove(IdTokenClaimNames.SUB))
|
||||
OidcUserInfo userInfo = userInfoBuilder.subject("sub").claims((claims) -> claims.remove(IdTokenClaimNames.SUB))
|
||||
.build();
|
||||
assertThat(userInfo.getSubject()).isNull();
|
||||
}
|
||||
@@ -70,7 +70,7 @@ public class OidcUserInfoBuilderTests {
|
||||
|
||||
String name = new String("name");
|
||||
String value = new String("value");
|
||||
OidcUserInfo userInfo = userInfoBuilder.claims(claims -> claims.put(name, value)).build();
|
||||
OidcUserInfo userInfo = userInfoBuilder.claims((claims) -> claims.put(name, value)).build();
|
||||
|
||||
assertThat(userInfo.getClaims()).hasSize(1);
|
||||
assertThat(userInfo.getClaims().get(name)).isSameAs(value);
|
||||
|
||||
+1
-1
@@ -112,7 +112,7 @@ public final class MappedJwtClaimSetConverter implements Converter<Map<String, O
|
||||
}
|
||||
|
||||
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
|
||||
return source -> CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
|
||||
return (source) -> CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
|
||||
}
|
||||
|
||||
private static Instant convertInstant(Object source) {
|
||||
|
||||
+1
-1
@@ -149,7 +149,7 @@ public final class NimbusJwtDecoder implements JwtDecoder {
|
||||
Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
|
||||
Map<String, Object> claims = this.claimSetConverter.convert(jwtClaimsSet.getClaims());
|
||||
|
||||
return Jwt.withTokenValue(token).headers(h -> h.putAll(headers)).claims(c -> c.putAll(claims)).build();
|
||||
return Jwt.withTokenValue(token).headers((h) -> h.putAll(headers)).claims((c) -> c.putAll(claims)).build();
|
||||
}
|
||||
catch (RemoteKeySourceException ex) {
|
||||
if (ex.getCause() instanceof ParseException) {
|
||||
|
||||
+14
-13
@@ -159,9 +159,10 @@ public final class NimbusReactiveJwtDecoder implements ReactiveJwtDecoder {
|
||||
|
||||
private Mono<Jwt> decode(JWT parsedToken) {
|
||||
try {
|
||||
return this.jwtProcessor.convert(parsedToken).map(set -> createJwt(parsedToken, set)).map(this::validateJwt)
|
||||
.onErrorMap(e -> !(e instanceof IllegalStateException) && !(e instanceof JwtException),
|
||||
e -> new JwtException("An error occurred while attempting to decode the Jwt: ", e));
|
||||
return this.jwtProcessor.convert(parsedToken).map((set) -> createJwt(parsedToken, set))
|
||||
.map(this::validateJwt)
|
||||
.onErrorMap((e) -> !(e instanceof IllegalStateException) && !(e instanceof JwtException),
|
||||
(e) -> new JwtException("An error occurred while attempting to decode the Jwt: ", e));
|
||||
}
|
||||
catch (JwtException ex) {
|
||||
throw ex;
|
||||
@@ -176,8 +177,8 @@ public final class NimbusReactiveJwtDecoder implements ReactiveJwtDecoder {
|
||||
Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
|
||||
Map<String, Object> claims = this.claimSetConverter.convert(jwtClaimsSet.getClaims());
|
||||
|
||||
return Jwt.withTokenValue(parsedJwt.getParsedString()).headers(h -> h.putAll(headers))
|
||||
.claims(c -> c.putAll(claims)).build();
|
||||
return Jwt.withTokenValue(parsedJwt.getParsedString()).headers((h) -> h.putAll(headers))
|
||||
.claims((c) -> c.putAll(claims)).build();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new BadJwtException("An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex);
|
||||
@@ -376,10 +377,10 @@ public final class NimbusReactiveJwtDecoder implements ReactiveJwtDecoder {
|
||||
source.setWebClient(this.webClient);
|
||||
|
||||
Function<JWSAlgorithm, Boolean> expectedJwsAlgorithms = getExpectedJwsAlgorithms(jwsKeySelector);
|
||||
return jwt -> {
|
||||
return (jwt) -> {
|
||||
JWKSelector selector = createSelector(expectedJwsAlgorithms, jwt.getHeader());
|
||||
return source.get(selector).onErrorMap(e -> new IllegalStateException("Could not obtain the keys", e))
|
||||
.map(jwkList -> createClaimsSet(jwtProcessor, jwt, new JWKSecurityContext(jwkList)));
|
||||
return source.get(selector).onErrorMap((e) -> new IllegalStateException("Could not obtain the keys", e))
|
||||
.map((jwkList) -> createClaimsSet(jwtProcessor, jwt, new JWKSecurityContext(jwkList)));
|
||||
};
|
||||
}
|
||||
|
||||
@@ -478,7 +479,7 @@ public final class NimbusReactiveJwtDecoder implements ReactiveJwtDecoder {
|
||||
|
||||
this.jwtProcessorCustomizer.accept(jwtProcessor);
|
||||
|
||||
return jwt -> Mono.just(createClaimsSet(jwtProcessor, jwt, null));
|
||||
return (jwt) -> Mono.just(createClaimsSet(jwtProcessor, jwt, null));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -556,7 +557,7 @@ public final class NimbusReactiveJwtDecoder implements ReactiveJwtDecoder {
|
||||
|
||||
this.jwtProcessorCustomizer.accept(jwtProcessor);
|
||||
|
||||
return jwt -> Mono.just(createClaimsSet(jwtProcessor, jwt, null));
|
||||
return (jwt) -> Mono.just(createClaimsSet(jwtProcessor, jwt, null));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -628,11 +629,11 @@ public final class NimbusReactiveJwtDecoder implements ReactiveJwtDecoder {
|
||||
|
||||
this.jwtProcessorCustomizer.accept(jwtProcessor);
|
||||
|
||||
return jwt -> {
|
||||
return (jwt) -> {
|
||||
if (jwt instanceof SignedJWT) {
|
||||
return this.jwkSource.apply((SignedJWT) jwt)
|
||||
.onErrorMap(e -> new IllegalStateException("Could not obtain the keys", e)).collectList()
|
||||
.map(jwks -> createClaimsSet(jwtProcessor, jwt, new JWKSecurityContext(jwks)));
|
||||
.onErrorMap((e) -> new IllegalStateException("Could not obtain the keys", e)).collectList()
|
||||
.map((jwks) -> createClaimsSet(jwtProcessor, jwt, new JWKSecurityContext(jwks)));
|
||||
}
|
||||
throw new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());
|
||||
};
|
||||
|
||||
+3
-3
@@ -55,8 +55,8 @@ class ReactiveRemoteJWKSource implements ReactiveJWKSource {
|
||||
@Override
|
||||
public Mono<List<JWK>> get(JWKSelector jwkSelector) {
|
||||
return this.cachedJWKSet.get().switchIfEmpty(Mono.defer(() -> getJWKSet()))
|
||||
.flatMap(jwkSet -> get(jwkSelector, jwkSet))
|
||||
.switchIfEmpty(Mono.defer(() -> getJWKSet().map(jwkSet -> jwkSelector.select(jwkSet))));
|
||||
.flatMap((jwkSet) -> get(jwkSelector, jwkSet))
|
||||
.switchIfEmpty(Mono.defer(() -> getJWKSet().map((jwkSet) -> jwkSelector.select(jwkSet))));
|
||||
}
|
||||
|
||||
private Mono<List<JWK>> get(JWKSelector jwkSelector, JWKSet jwkSet) {
|
||||
@@ -96,7 +96,7 @@ class ReactiveRemoteJWKSource implements ReactiveJWKSource {
|
||||
*/
|
||||
private Mono<JWKSet> getJWKSet() {
|
||||
return this.webClient.get().uri(this.jwkSetURL).retrieve().bodyToMono(String.class).map(this::parse)
|
||||
.doOnNext(jwkSet -> this.cachedJWKSet.set(Mono.just(jwkSet))).cache();
|
||||
.doOnNext((jwkSet) -> this.cachedJWKSet.set(Mono.just(jwkSet))).cache();
|
||||
}
|
||||
|
||||
private JWKSet parse(String body) {
|
||||
|
||||
+4
-4
@@ -105,7 +105,7 @@ public class JwtBuilderTests {
|
||||
public void claimsWhenRemovingAClaimThenIsNotPresent() {
|
||||
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").claim("needs", "a claim").header("needs", "a header");
|
||||
|
||||
Jwt jwt = jwtBuilder.subject("sub").claims(claims -> claims.remove(JwtClaimNames.SUB)).build();
|
||||
Jwt jwt = jwtBuilder.subject("sub").claims((claims) -> claims.remove(JwtClaimNames.SUB)).build();
|
||||
assertThat(jwt.getSubject()).isNull();
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ public class JwtBuilderTests {
|
||||
|
||||
String name = new String("name");
|
||||
String value = new String("value");
|
||||
Jwt jwt = jwtBuilder.claims(claims -> claims.put(name, value)).build();
|
||||
Jwt jwt = jwtBuilder.claims((claims) -> claims.put(name, value)).build();
|
||||
|
||||
assertThat(jwt.getClaims()).hasSize(1);
|
||||
assertThat(jwt.getClaims().get(name)).isSameAs(value);
|
||||
@@ -125,7 +125,7 @@ public class JwtBuilderTests {
|
||||
public void headersWhenRemovingAClaimThenIsNotPresent() {
|
||||
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").claim("needs", "a claim").header("needs", "a header");
|
||||
|
||||
Jwt jwt = jwtBuilder.header("alg", "none").headers(headers -> headers.remove("alg")).build();
|
||||
Jwt jwt = jwtBuilder.header("alg", "none").headers((headers) -> headers.remove("alg")).build();
|
||||
assertThat(jwt.getHeaders().get("alg")).isNull();
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ public class JwtBuilderTests {
|
||||
|
||||
String name = new String("name");
|
||||
String value = new String("value");
|
||||
Jwt jwt = jwtBuilder.headers(headers -> headers.put(name, value)).build();
|
||||
Jwt jwt = jwtBuilder.headers((headers) -> headers.put(name, value)).build();
|
||||
|
||||
assertThat(jwt.getHeaders()).hasSize(1);
|
||||
assertThat(jwt.getHeaders().get(name)).isSameAs(value);
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
*/
|
||||
public class JwtClaimValidatorTests {
|
||||
|
||||
private static final Predicate<String> test = claim -> claim.equals("http://test");
|
||||
private static final Predicate<String> test = (claim) -> claim.equals("http://test");
|
||||
|
||||
private final JwtClaimValidator<String> validator = new JwtClaimValidator<>(JwtClaimNames.ISS, test);
|
||||
|
||||
|
||||
+2
-2
@@ -129,7 +129,7 @@ public class JwtTimestampValidatorTests {
|
||||
|
||||
@Test
|
||||
public void validateWhenNeitherExpiryNorNotBeforeIsSpecifiedThenReturnsSuccessfulResult() {
|
||||
Jwt jwt = TestJwts.jwt().claims(c -> c.remove(JwtClaimNames.EXP)).build();
|
||||
Jwt jwt = TestJwts.jwt().claims((c) -> c.remove(JwtClaimNames.EXP)).build();
|
||||
|
||||
JwtTimestampValidator jwtValidator = new JwtTimestampValidator();
|
||||
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
|
||||
@@ -137,7 +137,7 @@ public class JwtTimestampValidatorTests {
|
||||
|
||||
@Test
|
||||
public void validateWhenNotBeforeIsValidAndExpiryIsNotSpecifiedThenReturnsSuccessfulResult() {
|
||||
Jwt jwt = TestJwts.jwt().claims(c -> c.remove(JwtClaimNames.EXP)).notBefore(Instant.MIN).build();
|
||||
Jwt jwt = TestJwts.jwt().claims((c) -> c.remove(JwtClaimNames.EXP)).notBefore(Instant.MIN).build();
|
||||
|
||||
JwtTimestampValidator jwtValidator = new JwtTimestampValidator();
|
||||
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
|
||||
|
||||
+1
-1
@@ -104,7 +104,7 @@ public class NimbusJwtDecoderJwkSupportTests {
|
||||
public void decodeWhenExpClaimNullThenDoesNotThrowException() {
|
||||
NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(JWK_SET_URL);
|
||||
jwtDecoder.setRestOperations(mockJwkSetResponse(JWK_SET));
|
||||
jwtDecoder.setClaimSetConverter(map -> {
|
||||
jwtDecoder.setClaimSetConverter((map) -> {
|
||||
Map<String, Object> claims = new HashMap<>(map);
|
||||
claims.remove(JwtClaimNames.EXP);
|
||||
return claims;
|
||||
|
||||
+3
-3
@@ -360,7 +360,7 @@ public class NimbusJwtDecoderTests {
|
||||
NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(publicKey)
|
||||
.signatureAlgorithm(SignatureAlgorithm.RS256)
|
||||
.jwtProcessorCustomizer(
|
||||
p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
(p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
.build();
|
||||
assertThat(decoder.decode(signedJwt.serialize()).containsClaim(JwtClaimNames.EXP)).isNotNull();
|
||||
}
|
||||
@@ -429,7 +429,7 @@ public class NimbusJwtDecoderTests {
|
||||
SignedJWT signedJwt = signedJwt(secretKey, header, claimsSet);
|
||||
NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS256)
|
||||
.jwtProcessorCustomizer(
|
||||
p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
(p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
.build();
|
||||
assertThat(decoder.decode(signedJwt.serialize()).containsClaim(JwtClaimNames.EXP)).isNotNull();
|
||||
}
|
||||
@@ -541,7 +541,7 @@ public class NimbusJwtDecoderTests {
|
||||
.willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
|
||||
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations)
|
||||
.jwtProcessorCustomizer(
|
||||
p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
(p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
.build();
|
||||
assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(BadJwtException.class).hasMessageContaining(
|
||||
"An error occurred while attempting to decode the Jwt: Required JOSE header \"typ\" (type) parameter is missing");
|
||||
|
||||
+8
-9
@@ -308,7 +308,7 @@ public class NimbusReactiveJwtDecoderTests {
|
||||
WebClient webClient = mockJwkSetResponse(this.jwkSet);
|
||||
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).webClient(webClient)
|
||||
.jwtProcessorCustomizer(
|
||||
p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
(p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
.build();
|
||||
assertThatCode(() -> decoder.decode(this.messageReadToken).block()).isInstanceOf(BadJwtException.class)
|
||||
.hasRootCauseMessage("Required JOSE header \"typ\" (type) parameter is missing");
|
||||
@@ -357,7 +357,7 @@ public class NimbusReactiveJwtDecoderTests {
|
||||
public void withPublicKeyWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws Exception {
|
||||
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withPublicKey(key())
|
||||
.jwtProcessorCustomizer(
|
||||
p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
(p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
.build();
|
||||
|
||||
AssertionsForClassTypes.assertThatCode(() -> decoder.decode(this.rsa256).block())
|
||||
@@ -372,16 +372,15 @@ public class NimbusReactiveJwtDecoderTests {
|
||||
|
||||
@Test
|
||||
public void withJwkSourceWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() {
|
||||
assertThatCode(
|
||||
() -> NimbusReactiveJwtDecoder.withJwkSource(jwt -> Flux.empty()).jwtProcessorCustomizer(null).build())
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
assertThatCode(() -> NimbusReactiveJwtDecoder.withJwkSource((jwt) -> Flux.empty()).jwtProcessorCustomizer(null)
|
||||
.build()).isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("jwtProcessorCustomizer cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decodeWhenCustomJwkSourceResolutionThenDecodes() {
|
||||
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder
|
||||
.withJwkSource(jwt -> Flux.fromIterable(parseJWKSet(this.jwkSet).getKeys())).build();
|
||||
.withJwkSource((jwt) -> Flux.fromIterable(parseJWKSet(this.jwkSet).getKeys())).build();
|
||||
|
||||
assertThat(decoder.decode(this.messageReadToken).block()).extracting(Jwt::getExpiresAt).isNotNull();
|
||||
}
|
||||
@@ -389,9 +388,9 @@ public class NimbusReactiveJwtDecoderTests {
|
||||
// gh-8730
|
||||
@Test
|
||||
public void withJwkSourceWhenUsingCustomTypeHeaderThenRefuseOmittedType() {
|
||||
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSource(jwt -> Flux.empty())
|
||||
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSource((jwt) -> Flux.empty())
|
||||
.jwtProcessorCustomizer(
|
||||
p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
(p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
.build();
|
||||
|
||||
assertThatCode(() -> decoder.decode(this.messageReadToken).block()).isInstanceOf(BadJwtException.class)
|
||||
@@ -437,7 +436,7 @@ public class NimbusReactiveJwtDecoderTests {
|
||||
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
|
||||
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withSecretKey(secretKey)
|
||||
.jwtProcessorCustomizer(
|
||||
p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
(p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS"))))
|
||||
.build();
|
||||
assertThatCode(() -> decoder.decode(this.messageReadToken).block()).isInstanceOf(BadJwtException.class)
|
||||
.hasRootCauseMessage("Required JOSE header \"typ\" (type) parameter is missing");
|
||||
|
||||
+4
-4
@@ -89,22 +89,22 @@ public final class BearerTokenError extends OAuth2Error {
|
||||
}
|
||||
|
||||
private static boolean isDescriptionValid(String description) {
|
||||
return description == null || description.chars().allMatch(c -> withinTheRangeOf(c, 0x20, 0x21)
|
||||
return description == null || description.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21)
|
||||
|| withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
|
||||
}
|
||||
|
||||
private static boolean isErrorCodeValid(String errorCode) {
|
||||
return errorCode.chars().allMatch(c -> withinTheRangeOf(c, 0x20, 0x21) || withinTheRangeOf(c, 0x23, 0x5B)
|
||||
return errorCode.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21) || withinTheRangeOf(c, 0x23, 0x5B)
|
||||
|| withinTheRangeOf(c, 0x5D, 0x7E));
|
||||
}
|
||||
|
||||
private static boolean isErrorUriValid(String errorUri) {
|
||||
return errorUri == null || errorUri.chars()
|
||||
.allMatch(c -> c == 0x21 || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
|
||||
.allMatch((c) -> c == 0x21 || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
|
||||
}
|
||||
|
||||
private static boolean isScopeValid(String scope) {
|
||||
return scope == null || scope.chars().allMatch(c -> withinTheRangeOf(c, 0x20, 0x21)
|
||||
return scope == null || scope.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21)
|
||||
|| withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -162,7 +162,7 @@ public final class JwtIssuerAuthenticationManagerResolver implements Authenticat
|
||||
@Override
|
||||
public AuthenticationManager resolve(String issuer) {
|
||||
if (this.trustedIssuer.test(issuer)) {
|
||||
return this.authenticationManagers.computeIfAbsent(issuer, k -> {
|
||||
return this.authenticationManagers.computeIfAbsent(issuer, (k) -> {
|
||||
JwtDecoder jwtDecoder = JwtDecoders.fromIssuerLocation(issuer);
|
||||
return new JwtAuthenticationProvider(jwtDecoder)::authenticate;
|
||||
});
|
||||
|
||||
+4
-4
@@ -101,7 +101,7 @@ public final class JwtIssuerReactiveAuthenticationManagerResolver
|
||||
* authenticationManagers.put("https://issuerOne.example.org", managerOne);
|
||||
* authenticationManagers.put("https://issuerTwo.example.org", managerTwo);
|
||||
* JwtIssuerReactiveAuthenticationManagerResolver resolver = new JwtIssuerReactiveAuthenticationManagerResolver
|
||||
* (issuer -> Mono.justOrEmpty(authenticationManagers.get(issuer));
|
||||
* ((issuer) -> Mono.justOrEmpty(authenticationManagers.get(issuer));
|
||||
* </pre>
|
||||
*
|
||||
* The keys in the {@link Map} are the trusted issuers.
|
||||
@@ -124,7 +124,7 @@ public final class JwtIssuerReactiveAuthenticationManagerResolver
|
||||
@Override
|
||||
public Mono<ReactiveAuthenticationManager> resolve(ServerWebExchange exchange) {
|
||||
return this.issuerConverter.convert(exchange)
|
||||
.flatMap(issuer -> this.issuerAuthenticationManagerResolver.resolve(issuer)
|
||||
.flatMap((issuer) -> this.issuerAuthenticationManagerResolver.resolve(issuer)
|
||||
.switchIfEmpty(Mono.error(() -> new InvalidBearerTokenException("Invalid issuer " + issuer))));
|
||||
}
|
||||
|
||||
@@ -134,7 +134,7 @@ public final class JwtIssuerReactiveAuthenticationManagerResolver
|
||||
|
||||
@Override
|
||||
public Mono<String> convert(@NonNull ServerWebExchange exchange) {
|
||||
return this.converter.convert(exchange).map(convertedToken -> {
|
||||
return this.converter.convert(exchange).map((convertedToken) -> {
|
||||
BearerTokenAuthenticationToken token = (BearerTokenAuthenticationToken) convertedToken;
|
||||
try {
|
||||
String issuer = JWTParser.parse(token.getToken()).getJWTClaimsSet().getIssuer();
|
||||
@@ -170,7 +170,7 @@ public final class JwtIssuerReactiveAuthenticationManagerResolver
|
||||
return Mono.empty();
|
||||
}
|
||||
return this.authenticationManagers.computeIfAbsent(issuer,
|
||||
k -> Mono.<ReactiveAuthenticationManager>fromCallable(
|
||||
(k) -> Mono.<ReactiveAuthenticationManager>fromCallable(
|
||||
() -> new JwtReactiveAuthenticationManager(ReactiveJwtDecoders.fromIssuerLocation(k)))
|
||||
.subscribeOn(Schedulers.boundedElastic()).cache());
|
||||
}
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ public final class JwtReactiveAuthenticationManager implements ReactiveAuthentic
|
||||
|
||||
@Override
|
||||
public Mono<Authentication> authenticate(Authentication authentication) {
|
||||
return Mono.justOrEmpty(authentication).filter(a -> a instanceof BearerTokenAuthenticationToken)
|
||||
return Mono.justOrEmpty(authentication).filter((a) -> a instanceof BearerTokenAuthenticationToken)
|
||||
.cast(BearerTokenAuthenticationToken.class).map(BearerTokenAuthenticationToken::getToken)
|
||||
.flatMap(this.jwtDecoder::decode).flatMap(this.jwtAuthenticationConverter::convert)
|
||||
.cast(Authentication.class).onErrorMap(JwtException.class, this::onError);
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ public class OpaqueTokenReactiveAuthenticationManager implements ReactiveAuthent
|
||||
}
|
||||
|
||||
private Mono<BearerTokenAuthentication> authenticate(String token) {
|
||||
return this.introspector.introspect(token).map(principal -> {
|
||||
return this.introspector.introspect(token).map((principal) -> {
|
||||
Instant iat = principal.getAttribute(OAuth2IntrospectionClaimNames.ISSUED_AT);
|
||||
Instant exp = principal.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT);
|
||||
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ public final class ReactiveJwtAuthenticationConverter implements Converter<Jwt,
|
||||
@Override
|
||||
public Mono<AbstractAuthenticationToken> convert(Jwt jwt) {
|
||||
return this.jwtGrantedAuthoritiesConverter.convert(jwt).collectList()
|
||||
.map(authorities -> new JwtAuthenticationToken(jwt, authorities));
|
||||
.map((authorities) -> new JwtAuthenticationToken(jwt, authorities));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ public class NimbusOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
|
||||
}
|
||||
|
||||
private Converter<String, RequestEntity<?>> defaultRequestEntityConverter(URI introspectionUri) {
|
||||
return token -> {
|
||||
return (token) -> {
|
||||
HttpHeaders headers = requestHeaders();
|
||||
MultiValueMap<String, String> body = requestBody(token);
|
||||
return new RequestEntity<>(body, headers, HttpMethod.POST, introspectionUri);
|
||||
|
||||
+4
-4
@@ -73,7 +73,7 @@ public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueToke
|
||||
Assert.notNull(clientSecret, "clientSecret cannot be null");
|
||||
|
||||
this.introspectionUri = URI.create(introspectionUri);
|
||||
this.webClient = WebClient.builder().defaultHeaders(h -> h.setBasicAuth(clientId, clientSecret)).build();
|
||||
this.webClient = WebClient.builder().defaultHeaders((h) -> h.setBasicAuth(clientId, clientSecret)).build();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -97,8 +97,8 @@ public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueToke
|
||||
public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
|
||||
return Mono.just(token).flatMap(this::makeRequest).flatMap(this::adaptToNimbusResponse)
|
||||
.map(this::parseNimbusResponse).map(this::castToNimbusSuccess)
|
||||
.doOnNext(response -> validate(token, response)).map(this::convertClaimsSet)
|
||||
.onErrorMap(e -> !(e instanceof OAuth2IntrospectionException), this::onError);
|
||||
.doOnNext((response) -> validate(token, response)).map(this::convertClaimsSet)
|
||||
.onErrorMap((e) -> !(e instanceof OAuth2IntrospectionException), this::onError);
|
||||
}
|
||||
|
||||
private Mono<ClientResponse> makeRequest(String token) {
|
||||
@@ -115,7 +115,7 @@ public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueToke
|
||||
.then(Mono.error(new OAuth2IntrospectionException(
|
||||
"Introspection endpoint responded with " + response.getStatusCode())));
|
||||
}
|
||||
return responseEntity.bodyToMono(String.class).doOnNext(response::setContent).map(body -> response);
|
||||
return responseEntity.bodyToMono(String.class).doOnNext(response::setContent).map((body) -> response);
|
||||
}
|
||||
|
||||
private TokenIntrospectionResponse parseNimbusResponse(HTTPResponse response) {
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@ public final class BearerTokenAuthenticationFilter extends OncePerRequestFilter
|
||||
*/
|
||||
public BearerTokenAuthenticationFilter(AuthenticationManager authenticationManager) {
|
||||
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
|
||||
this.authenticationManagerResolver = request -> authenticationManager;
|
||||
this.authenticationManagerResolver = (request) -> authenticationManager;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+2
-2
@@ -63,8 +63,8 @@ public class BearerTokenServerAccessDeniedHandler implements ServerAccessDeniedH
|
||||
}
|
||||
|
||||
return exchange.getPrincipal().filter(AbstractOAuth2TokenAuthenticationToken.class::isInstance)
|
||||
.map(token -> errorMessageParameters(parameters)).switchIfEmpty(Mono.just(parameters))
|
||||
.flatMap(params -> respond(exchange, params));
|
||||
.map((token) -> errorMessageParameters(parameters)).switchIfEmpty(Mono.just(parameters))
|
||||
.flatMap((params) -> respond(exchange, params));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+3
-3
@@ -56,12 +56,12 @@ public final class ServerBearerExchangeFilterFunction implements ExchangeFilterF
|
||||
*/
|
||||
@Override
|
||||
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
|
||||
return oauth2Token().map(token -> bearer(request, token)).defaultIfEmpty(request).flatMap(next::exchange);
|
||||
return oauth2Token().map((token) -> bearer(request, token)).defaultIfEmpty(request).flatMap(next::exchange);
|
||||
}
|
||||
|
||||
private Mono<AbstractOAuth2Token> oauth2Token() {
|
||||
return currentAuthentication()
|
||||
.filter(authentication -> authentication.getCredentials() instanceof AbstractOAuth2Token)
|
||||
.filter((authentication) -> authentication.getCredentials() instanceof AbstractOAuth2Token)
|
||||
.map(Authentication::getCredentials).cast(AbstractOAuth2Token.class);
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ public final class ServerBearerExchangeFilterFunction implements ExchangeFilterF
|
||||
}
|
||||
|
||||
private ClientRequest bearer(ClientRequest request, AbstractOAuth2Token token) {
|
||||
return ClientRequest.from(request).headers(headers -> headers.setBearerAuth(token.getTokenValue())).build();
|
||||
return ClientRequest.from(request).headers((headers) -> headers.setBearerAuth(token.getTokenValue())).build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+3
-3
@@ -67,12 +67,12 @@ public final class ServletBearerExchangeFilterFunction implements ExchangeFilter
|
||||
*/
|
||||
@Override
|
||||
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
|
||||
return oauth2Token().map(token -> bearer(request, token)).defaultIfEmpty(request).flatMap(next::exchange);
|
||||
return oauth2Token().map((token) -> bearer(request, token)).defaultIfEmpty(request).flatMap(next::exchange);
|
||||
}
|
||||
|
||||
private Mono<AbstractOAuth2Token> oauth2Token() {
|
||||
return Mono.subscriberContext().flatMap(this::currentAuthentication)
|
||||
.filter(authentication -> authentication.getCredentials() instanceof AbstractOAuth2Token)
|
||||
.filter((authentication) -> authentication.getCredentials() instanceof AbstractOAuth2Token)
|
||||
.map(Authentication::getCredentials).cast(AbstractOAuth2Token.class);
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ public final class ServletBearerExchangeFilterFunction implements ExchangeFilter
|
||||
}
|
||||
|
||||
private ClientRequest bearer(ClientRequest request, AbstractOAuth2Token token) {
|
||||
return ClientRequest.from(request).headers(headers -> headers.setBearerAuth(token.getTokenValue())).build();
|
||||
return ClientRequest.from(request).headers((headers) -> headers.setBearerAuth(token.getTokenValue())).build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@ public class ServerBearerTokenAuthenticationConverter implements ServerAuthentic
|
||||
|
||||
@Override
|
||||
public Mono<Authentication> convert(ServerWebExchange exchange) {
|
||||
return Mono.fromCallable(() -> token(exchange.getRequest())).map(token -> {
|
||||
return Mono.fromCallable(() -> token(exchange.getRequest())).map((token) -> {
|
||||
if (token.isEmpty()) {
|
||||
BearerTokenError error = invalidTokenError();
|
||||
throw new OAuth2AuthenticationException(error);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user