Revert "Support resolving issuer from current request"

This reverts commit 666d569b48.
This commit is contained in:
Joe Grandja
2021-11-29 01:49:26 -05:00
parent c418306fd9
commit 830f55e538
34 changed files with 150 additions and 468 deletions

View File

@@ -216,17 +216,9 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
@Override @Override
public void configure(B builder) { public void configure(B builder) {
ProviderSettings providerSettings = OAuth2ConfigurerUtils.getProviderSettings(builder);
// IMPORTANT:
// This filter must be registered first as it resolves the current issuer identifier and
// sets it as a request attribute under WebAttributes.ISSUER, which may be used by upstream components.
OAuth2AuthorizationServerMetadataEndpointFilter authorizationServerMetadataEndpointFilter =
new OAuth2AuthorizationServerMetadataEndpointFilter(providerSettings);
builder.addFilterBefore(postProcess(authorizationServerMetadataEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class);
this.configurers.values().forEach(configurer -> configurer.configure(builder)); this.configurers.values().forEach(configurer -> configurer.configure(builder));
ProviderSettings providerSettings = OAuth2ConfigurerUtils.getProviderSettings(builder);
AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class); AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class);
OAuth2TokenIntrospectionEndpointFilter tokenIntrospectionEndpointFilter = OAuth2TokenIntrospectionEndpointFilter tokenIntrospectionEndpointFilter =
@@ -246,6 +238,12 @@ public final class OAuth2AuthorizationServerConfigurer<B extends HttpSecurityBui
OAuth2ConfigurerUtils.getJwkSource(builder), OAuth2ConfigurerUtils.getJwkSource(builder),
providerSettings.getJwkSetEndpoint()); providerSettings.getJwkSetEndpoint());
builder.addFilterBefore(postProcess(jwkSetEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class); builder.addFilterBefore(postProcess(jwkSetEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class);
if (providerSettings.getIssuer() != null) {
OAuth2AuthorizationServerMetadataEndpointFilter authorizationServerMetadataEndpointFilter =
new OAuth2AuthorizationServerMetadataEndpointFilter(providerSettings);
builder.addFilterBefore(postProcess(authorizationServerMetadataEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class);
}
} }
private Map<Class<? extends AbstractOAuth2Configurer>, AbstractOAuth2Configurer> createConfigurers() { private Map<Class<? extends AbstractOAuth2Configurer>, AbstractOAuth2Configurer> createConfigurers() {

View File

@@ -85,13 +85,16 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer {
} }
List<RequestMatcher> requestMatchers = new ArrayList<>(); List<RequestMatcher> requestMatchers = new ArrayList<>();
requestMatchers.add(new AntPathRequestMatcher( ProviderSettings providerSettings = OAuth2ConfigurerUtils.getProviderSettings(builder);
"/.well-known/openid-configuration", HttpMethod.GET.name())); if (providerSettings.getIssuer() != null) {
requestMatchers.add(new AntPathRequestMatcher(
"/.well-known/openid-configuration", HttpMethod.GET.name()));
}
requestMatchers.add(this.userInfoEndpointConfigurer.getRequestMatcher()); requestMatchers.add(this.userInfoEndpointConfigurer.getRequestMatcher());
if (this.clientRegistrationEndpointConfigurer != null) { if (this.clientRegistrationEndpointConfigurer != null) {
requestMatchers.add(this.clientRegistrationEndpointConfigurer.getRequestMatcher()); requestMatchers.add(this.clientRegistrationEndpointConfigurer.getRequestMatcher());
} }
this.requestMatcher = new OrRequestMatcher(requestMatchers); this.requestMatcher = requestMatchers.size() > 1 ? new OrRequestMatcher(requestMatchers) : requestMatchers.get(0);
} }
@Override @Override
@@ -102,9 +105,11 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer {
} }
ProviderSettings providerSettings = OAuth2ConfigurerUtils.getProviderSettings(builder); ProviderSettings providerSettings = OAuth2ConfigurerUtils.getProviderSettings(builder);
OidcProviderConfigurationEndpointFilter oidcProviderConfigurationEndpointFilter = if (providerSettings.getIssuer() != null) {
new OidcProviderConfigurationEndpointFilter(providerSettings); OidcProviderConfigurationEndpointFilter oidcProviderConfigurationEndpointFilter =
builder.addFilterBefore(postProcess(oidcProviderConfigurationEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class); new OidcProviderConfigurationEndpointFilter(providerSettings);
builder.addFilterBefore(postProcess(oidcProviderConfigurationEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class);
}
} }
@Override @Override

View File

@@ -26,6 +26,7 @@ import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
@@ -86,6 +87,7 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
private final JwtEncoder jwtEncoder; private final JwtEncoder jwtEncoder;
private OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = (context) -> {}; private OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = (context) -> {};
private Supplier<String> refreshTokenGenerator = DEFAULT_REFRESH_TOKEN_GENERATOR::generateKey; private Supplier<String> refreshTokenGenerator = DEFAULT_REFRESH_TOKEN_GENERATOR::generateKey;
private ProviderSettings providerSettings;
/** /**
* Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the provided parameters. * Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the provided parameters.
@@ -122,8 +124,9 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
this.refreshTokenGenerator = refreshTokenGenerator; this.refreshTokenGenerator = refreshTokenGenerator;
} }
@Deprecated @Autowired(required = false)
protected void setProviderSettings(ProviderSettings providerSettings) { protected void setProviderSettings(ProviderSettings providerSettings) {
this.providerSettings = providerSettings;
} }
@Override @Override
@@ -164,7 +167,7 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT); throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
} }
String issuer = authorizationCodeAuthentication.getIssuer(); String issuer = this.providerSettings != null ? this.providerSettings.getIssuer() : null;
Set<String> authorizedScopes = authorization.getAttribute( Set<String> authorizedScopes = authorization.getAttribute(
OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME); OAuth2Authorization.AUTHORIZED_SCOPE_ATTRIBUTE_NAME);

View File

@@ -43,9 +43,7 @@ public class OAuth2AuthorizationCodeAuthenticationToken extends OAuth2Authorizat
* @param clientPrincipal the authenticated client principal * @param clientPrincipal the authenticated client principal
* @param redirectUri the redirect uri * @param redirectUri the redirect uri
* @param additionalParameters the additional parameters * @param additionalParameters the additional parameters
* @deprecated Use {@link #OAuth2AuthorizationCodeAuthenticationToken(String, String, Authentication, String, Map)} instead
*/ */
@Deprecated
public OAuth2AuthorizationCodeAuthenticationToken(String code, Authentication clientPrincipal, public OAuth2AuthorizationCodeAuthenticationToken(String code, Authentication clientPrincipal,
@Nullable String redirectUri, @Nullable Map<String, Object> additionalParameters) { @Nullable String redirectUri, @Nullable Map<String, Object> additionalParameters) {
super(AuthorizationGrantType.AUTHORIZATION_CODE, clientPrincipal, additionalParameters); super(AuthorizationGrantType.AUTHORIZATION_CODE, clientPrincipal, additionalParameters);
@@ -54,24 +52,6 @@ public class OAuth2AuthorizationCodeAuthenticationToken extends OAuth2Authorizat
this.redirectUri = redirectUri; this.redirectUri = redirectUri;
} }
/**
* Constructs an {@code OAuth2AuthorizationCodeAuthenticationToken} using the provided parameters.
*
* @param issuer the issuer identifier
* @param code the authorization code
* @param clientPrincipal the authenticated client principal
* @param redirectUri the redirect uri
* @param additionalParameters the additional parameters
* @since 0.2.1
*/
public OAuth2AuthorizationCodeAuthenticationToken(String issuer, String code, Authentication clientPrincipal,
@Nullable String redirectUri, @Nullable Map<String, Object> additionalParameters) {
super(AuthorizationGrantType.AUTHORIZATION_CODE, issuer, clientPrincipal, additionalParameters);
Assert.hasText(code, "code cannot be empty");
this.code = code;
this.redirectUri = redirectUri;
}
/** /**
* Returns the authorization code. * Returns the authorization code.
* *

View File

@@ -39,7 +39,6 @@ import org.springframework.util.Assert;
public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthenticationToken { public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = Version.SERIAL_VERSION_UID; private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
private final AuthorizationGrantType authorizationGrantType; private final AuthorizationGrantType authorizationGrantType;
private final String issuer;
private final Authentication clientPrincipal; private final Authentication clientPrincipal;
private final Map<String, Object> additionalParameters; private final Map<String, Object> additionalParameters;
@@ -49,40 +48,13 @@ public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthent
* @param authorizationGrantType the authorization grant type * @param authorizationGrantType the authorization grant type
* @param clientPrincipal the authenticated client principal * @param clientPrincipal the authenticated client principal
* @param additionalParameters the additional parameters * @param additionalParameters the additional parameters
* @deprecated Use {@link #OAuth2AuthorizationGrantAuthenticationToken(AuthorizationGrantType, String, Authentication, Map)} instead
*/ */
@Deprecated
protected OAuth2AuthorizationGrantAuthenticationToken(AuthorizationGrantType authorizationGrantType, protected OAuth2AuthorizationGrantAuthenticationToken(AuthorizationGrantType authorizationGrantType,
Authentication clientPrincipal, @Nullable Map<String, Object> additionalParameters) { Authentication clientPrincipal, @Nullable Map<String, Object> additionalParameters) {
super(Collections.emptyList()); super(Collections.emptyList());
Assert.notNull(authorizationGrantType, "authorizationGrantType cannot be null"); Assert.notNull(authorizationGrantType, "authorizationGrantType cannot be null");
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null"); Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
this.authorizationGrantType = authorizationGrantType; this.authorizationGrantType = authorizationGrantType;
this.issuer = null;
this.clientPrincipal = clientPrincipal;
this.additionalParameters = Collections.unmodifiableMap(
additionalParameters != null ?
new HashMap<>(additionalParameters) :
Collections.emptyMap());
}
/**
* Sub-class constructor.
*
* @param authorizationGrantType the authorization grant type
* @param issuer the issuer identifier
* @param clientPrincipal the authenticated client principal
* @param additionalParameters the additional parameters
* @since 0.2.1
*/
protected OAuth2AuthorizationGrantAuthenticationToken(AuthorizationGrantType authorizationGrantType,
String issuer, Authentication clientPrincipal, @Nullable Map<String, Object> additionalParameters) {
super(Collections.emptyList());
Assert.notNull(authorizationGrantType, "authorizationGrantType cannot be null");
Assert.hasText(issuer, "issuer cannot be empty");
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
this.authorizationGrantType = authorizationGrantType;
this.issuer = issuer;
this.clientPrincipal = clientPrincipal; this.clientPrincipal = clientPrincipal;
this.additionalParameters = Collections.unmodifiableMap( this.additionalParameters = Collections.unmodifiableMap(
additionalParameters != null ? additionalParameters != null ?
@@ -99,16 +71,6 @@ public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthent
return this.authorizationGrantType; return this.authorizationGrantType;
} }
/**
* Returns the issuer identifier.
*
* @return the issuer identifier
* @since 0.2.1
*/
public String getIssuer() {
return this.issuer;
}
@Override @Override
public Object getPrincipal() { public Object getPrincipal() {
return this.clientPrincipal; return this.clientPrincipal;

View File

@@ -19,6 +19,7 @@ import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
@@ -61,6 +62,7 @@ public final class OAuth2ClientCredentialsAuthenticationProvider implements Auth
private final OAuth2AuthorizationService authorizationService; private final OAuth2AuthorizationService authorizationService;
private final JwtEncoder jwtEncoder; private final JwtEncoder jwtEncoder;
private OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = (context) -> {}; private OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = (context) -> {};
private ProviderSettings providerSettings;
/** /**
* Constructs an {@code OAuth2ClientCredentialsAuthenticationProvider} using the provided parameters. * Constructs an {@code OAuth2ClientCredentialsAuthenticationProvider} using the provided parameters.
@@ -88,8 +90,9 @@ public final class OAuth2ClientCredentialsAuthenticationProvider implements Auth
this.jwtCustomizer = jwtCustomizer; this.jwtCustomizer = jwtCustomizer;
} }
@Deprecated @Autowired(required = false)
protected void setProviderSettings(ProviderSettings providerSettings) { protected void setProviderSettings(ProviderSettings providerSettings) {
this.providerSettings = providerSettings;
} }
@Override @Override
@@ -115,7 +118,7 @@ public final class OAuth2ClientCredentialsAuthenticationProvider implements Auth
authorizedScopes = new LinkedHashSet<>(clientCredentialsAuthentication.getScopes()); authorizedScopes = new LinkedHashSet<>(clientCredentialsAuthentication.getScopes());
} }
String issuer = clientCredentialsAuthentication.getIssuer(); String issuer = this.providerSettings != null ? this.providerSettings.getIssuer() : null;
JoseHeader.Builder headersBuilder = JwtUtils.headers(); JoseHeader.Builder headersBuilder = JwtUtils.headers();
JwtClaimsSet.Builder claimsBuilder = JwtUtils.accessTokenClaims( JwtClaimsSet.Builder claimsBuilder = JwtUtils.accessTokenClaims(

View File

@@ -41,9 +41,7 @@ public class OAuth2ClientCredentialsAuthenticationToken extends OAuth2Authorizat
* @param clientPrincipal the authenticated client principal * @param clientPrincipal the authenticated client principal
* @param scopes the requested scope(s) * @param scopes the requested scope(s)
* @param additionalParameters the additional parameters * @param additionalParameters the additional parameters
* @deprecated Use {@link #OAuth2ClientCredentialsAuthenticationToken(String, Authentication, Set, Map)} instead
*/ */
@Deprecated
public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal, public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal,
@Nullable Set<String> scopes, @Nullable Map<String, Object> additionalParameters) { @Nullable Set<String> scopes, @Nullable Map<String, Object> additionalParameters) {
super(AuthorizationGrantType.CLIENT_CREDENTIALS, clientPrincipal, additionalParameters); super(AuthorizationGrantType.CLIENT_CREDENTIALS, clientPrincipal, additionalParameters);
@@ -51,22 +49,6 @@ public class OAuth2ClientCredentialsAuthenticationToken extends OAuth2Authorizat
scopes != null ? new HashSet<>(scopes) : Collections.emptySet()); scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
} }
/**
* Constructs an {@code OAuth2ClientCredentialsAuthenticationToken} using the provided parameters.
*
* @param issuer the issuer identifier
* @param clientPrincipal the authenticated client principal
* @param scopes the requested scope(s)
* @param additionalParameters the additional parameters
* @since 0.2.1
*/
public OAuth2ClientCredentialsAuthenticationToken(String issuer, Authentication clientPrincipal,
@Nullable Set<String> scopes, @Nullable Map<String, Object> additionalParameters) {
super(AuthorizationGrantType.CLIENT_CREDENTIALS, issuer, clientPrincipal, additionalParameters);
this.scopes = Collections.unmodifiableSet(
scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
}
/** /**
* Returns the requested scope(s). * Returns the requested scope(s).
* *

View File

@@ -26,6 +26,7 @@ import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
@@ -79,6 +80,7 @@ public final class OAuth2RefreshTokenAuthenticationProvider implements Authentic
private final JwtEncoder jwtEncoder; private final JwtEncoder jwtEncoder;
private OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = (context) -> {}; private OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = (context) -> {};
private Supplier<String> refreshTokenGenerator = DEFAULT_REFRESH_TOKEN_GENERATOR::generateKey; private Supplier<String> refreshTokenGenerator = DEFAULT_REFRESH_TOKEN_GENERATOR::generateKey;
private ProviderSettings providerSettings;
/** /**
* Constructs an {@code OAuth2RefreshTokenAuthenticationProvider} using the provided parameters. * Constructs an {@code OAuth2RefreshTokenAuthenticationProvider} using the provided parameters.
@@ -116,8 +118,9 @@ public final class OAuth2RefreshTokenAuthenticationProvider implements Authentic
this.refreshTokenGenerator = refreshTokenGenerator; this.refreshTokenGenerator = refreshTokenGenerator;
} }
@Deprecated @Autowired(required = false)
protected void setProviderSettings(ProviderSettings providerSettings) { protected void setProviderSettings(ProviderSettings providerSettings) {
this.providerSettings = providerSettings;
} }
@Override @Override
@@ -163,7 +166,7 @@ public final class OAuth2RefreshTokenAuthenticationProvider implements Authentic
scopes = authorizedScopes; scopes = authorizedScopes;
} }
String issuer = refreshTokenAuthentication.getIssuer(); String issuer = this.providerSettings != null ? this.providerSettings.getIssuer() : null;
JoseHeader.Builder headersBuilder = JwtUtils.headers(); JoseHeader.Builder headersBuilder = JwtUtils.headers();
JwtClaimsSet.Builder claimsBuilder = JwtUtils.accessTokenClaims( JwtClaimsSet.Builder claimsBuilder = JwtUtils.accessTokenClaims(

View File

@@ -44,9 +44,7 @@ public class OAuth2RefreshTokenAuthenticationToken extends OAuth2AuthorizationGr
* @param clientPrincipal the authenticated client principal * @param clientPrincipal the authenticated client principal
* @param scopes the requested scope(s) * @param scopes the requested scope(s)
* @param additionalParameters the additional parameters * @param additionalParameters the additional parameters
* @deprecated Use {@link #OAuth2RefreshTokenAuthenticationToken(String, String, Authentication, Set, Map)} instead
*/ */
@Deprecated
public OAuth2RefreshTokenAuthenticationToken(String refreshToken, Authentication clientPrincipal, public OAuth2RefreshTokenAuthenticationToken(String refreshToken, Authentication clientPrincipal,
@Nullable Set<String> scopes, @Nullable Map<String, Object> additionalParameters) { @Nullable Set<String> scopes, @Nullable Map<String, Object> additionalParameters) {
super(AuthorizationGrantType.REFRESH_TOKEN, clientPrincipal, additionalParameters); super(AuthorizationGrantType.REFRESH_TOKEN, clientPrincipal, additionalParameters);
@@ -56,25 +54,6 @@ public class OAuth2RefreshTokenAuthenticationToken extends OAuth2AuthorizationGr
scopes != null ? new HashSet<>(scopes) : Collections.emptySet()); scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
} }
/**
* Constructs an {@code OAuth2RefreshTokenAuthenticationToken} using the provided parameters.
*
* @param issuer the issuer identifier
* @param refreshToken the refresh token
* @param clientPrincipal the authenticated client principal
* @param scopes the requested scope(s)
* @param additionalParameters the additional parameters
* @since 0.2.1
*/
public OAuth2RefreshTokenAuthenticationToken(String issuer, String refreshToken, Authentication clientPrincipal,
@Nullable Set<String> scopes, @Nullable Map<String, Object> additionalParameters) {
super(AuthorizationGrantType.REFRESH_TOKEN, issuer, clientPrincipal, additionalParameters);
Assert.hasText(refreshToken, "refreshToken cannot be empty");
this.refreshToken = refreshToken;
this.scopes = Collections.unmodifiableSet(
scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
}
/** /**
* Returns the refresh token. * Returns the refresh token.
* *

View File

@@ -178,11 +178,9 @@ public final class OidcClientRegistrationAuthenticationProvider implements Authe
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT); throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
} }
OidcClientRegistration clientRegistration = buildRegistration( OidcClientRegistration clientRegistration = buildRegistration(registeredClient).build();
registeredClient, clientRegistrationAuthentication.getIssuer())
.build();
return new OidcClientRegistrationAuthenticationToken(clientRegistrationAuthentication.getIssuer(), return new OidcClientRegistrationAuthenticationToken(
(Authentication) clientRegistrationAuthentication.getPrincipal(), clientRegistration); (Authentication) clientRegistrationAuthentication.getPrincipal(), clientRegistration);
} }
@@ -200,8 +198,7 @@ public final class OidcClientRegistrationAuthenticationProvider implements Authe
RegisteredClient registeredClient = createClient(clientRegistrationAuthentication.getClientRegistration()); RegisteredClient registeredClient = createClient(clientRegistrationAuthentication.getClientRegistration());
this.registeredClientRepository.save(registeredClient); this.registeredClientRepository.save(registeredClient);
OAuth2Authorization registeredClientAuthorization = registerAccessToken( OAuth2Authorization registeredClientAuthorization = registerAccessToken(registeredClient);
registeredClient, clientRegistrationAuthentication.getIssuer());
// Invalidate the "initial" access token as it can only be used once // Invalidate the "initial" access token as it can only be used once
authorization = OidcAuthenticationProviderUtils.invalidate(authorization, authorizedAccessToken.getToken()); authorization = OidcAuthenticationProviderUtils.invalidate(authorization, authorizedAccessToken.getToken());
@@ -210,22 +207,21 @@ public final class OidcClientRegistrationAuthenticationProvider implements Authe
} }
this.authorizationService.save(authorization); this.authorizationService.save(authorization);
OidcClientRegistration clientRegistration = buildRegistration( OidcClientRegistration clientRegistration = buildRegistration(registeredClient)
registeredClient, clientRegistrationAuthentication.getIssuer())
.registrationAccessToken(registeredClientAuthorization.getAccessToken().getToken().getTokenValue()) .registrationAccessToken(registeredClientAuthorization.getAccessToken().getToken().getTokenValue())
.build(); .build();
return new OidcClientRegistrationAuthenticationToken(clientRegistrationAuthentication.getIssuer(), return new OidcClientRegistrationAuthenticationToken(
(Authentication) clientRegistrationAuthentication.getPrincipal(), clientRegistration); (Authentication) clientRegistrationAuthentication.getPrincipal(), clientRegistration);
} }
private OAuth2Authorization registerAccessToken(RegisteredClient registeredClient, String issuer) { private OAuth2Authorization registerAccessToken(RegisteredClient registeredClient) {
JoseHeader headers = JwtUtils.headers().build(); JoseHeader headers = JwtUtils.headers().build();
Set<String> authorizedScopes = Collections.singleton(DEFAULT_CLIENT_CONFIGURATION_AUTHORIZED_SCOPE); Set<String> authorizedScopes = Collections.singleton(DEFAULT_CLIENT_CONFIGURATION_AUTHORIZED_SCOPE);
JwtClaimsSet claims = JwtUtils.accessTokenClaims( JwtClaimsSet claims = JwtUtils.accessTokenClaims(
registeredClient, issuer, registeredClient.getClientId(), authorizedScopes) registeredClient, this.providerSettings.getIssuer(), registeredClient.getClientId(), authorizedScopes)
.build(); .build();
Jwt registrationAccessToken = this.jwtEncoder.encode(headers, claims); Jwt registrationAccessToken = this.jwtEncoder.encode(headers, claims);
@@ -250,7 +246,7 @@ public final class OidcClientRegistrationAuthenticationProvider implements Authe
return registeredClientAuthorization; return registeredClientAuthorization;
} }
private OidcClientRegistration.Builder buildRegistration(RegisteredClient registeredClient, String issuer) { private OidcClientRegistration.Builder buildRegistration(RegisteredClient registeredClient) {
// @formatter:off // @formatter:off
OidcClientRegistration.Builder builder = OidcClientRegistration.builder() OidcClientRegistration.Builder builder = OidcClientRegistration.builder()
.clientId(registeredClient.getClientId()) .clientId(registeredClient.getClientId())
@@ -274,7 +270,7 @@ public final class OidcClientRegistrationAuthenticationProvider implements Authe
scopes.addAll(registeredClient.getScopes())); scopes.addAll(registeredClient.getScopes()));
} }
String registrationClientUri = UriComponentsBuilder.fromUriString(issuer) String registrationClientUri = UriComponentsBuilder.fromUriString(this.providerSettings.getIssuer())
.path(this.providerSettings.getOidcClientRegistrationEndpoint()) .path(this.providerSettings.getOidcClientRegistrationEndpoint())
.queryParam(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()) .queryParam(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId())
.toUriString(); .toUriString();

View File

@@ -36,7 +36,6 @@ import org.springframework.util.Assert;
*/ */
public class OidcClientRegistrationAuthenticationToken extends AbstractAuthenticationToken { public class OidcClientRegistrationAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = Version.SERIAL_VERSION_UID; private static final long serialVersionUID = Version.SERIAL_VERSION_UID;
private final String issuer;
private final Authentication principal; private final Authentication principal;
private final OidcClientRegistration clientRegistration; private final OidcClientRegistration clientRegistration;
private final String clientId; private final String clientId;
@@ -46,14 +45,11 @@ public class OidcClientRegistrationAuthenticationToken extends AbstractAuthentic
* *
* @param principal the authenticated principal * @param principal the authenticated principal
* @param clientRegistration the client registration * @param clientRegistration the client registration
* @deprecated Use {@link #OidcClientRegistrationAuthenticationToken(String, Authentication, OidcClientRegistration)} instead
*/ */
@Deprecated
public OidcClientRegistrationAuthenticationToken(Authentication principal, OidcClientRegistration clientRegistration) { public OidcClientRegistrationAuthenticationToken(Authentication principal, OidcClientRegistration clientRegistration) {
super(Collections.emptyList()); super(Collections.emptyList());
Assert.notNull(principal, "principal cannot be null"); Assert.notNull(principal, "principal cannot be null");
Assert.notNull(clientRegistration, "clientRegistration cannot be null"); Assert.notNull(clientRegistration, "clientRegistration cannot be null");
this.issuer = null;
this.principal = principal; this.principal = principal;
this.clientRegistration = clientRegistration; this.clientRegistration = clientRegistration;
this.clientId = null; this.clientId = null;
@@ -63,53 +59,20 @@ public class OidcClientRegistrationAuthenticationToken extends AbstractAuthentic
/** /**
* Constructs an {@code OidcClientRegistrationAuthenticationToken} using the provided parameters. * Constructs an {@code OidcClientRegistrationAuthenticationToken} using the provided parameters.
* *
* @param issuer the issuer identifier
* @param principal the authenticated principal
* @param clientRegistration the client registration
* @since 0.2.1
*/
public OidcClientRegistrationAuthenticationToken(String issuer, Authentication principal, OidcClientRegistration clientRegistration) {
super(Collections.emptyList());
Assert.hasText(issuer, "issuer cannot be empty");
Assert.notNull(principal, "principal cannot be null");
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
this.issuer = issuer;
this.principal = principal;
this.clientRegistration = clientRegistration;
this.clientId = null;
setAuthenticated(principal.isAuthenticated());
}
/**
* Constructs an {@code OidcClientRegistrationAuthenticationToken} using the provided parameters.
*
* @param issuer the issuer identifier
* @param principal the authenticated principal * @param principal the authenticated principal
* @param clientId the client identifier * @param clientId the client identifier
* @since 0.2.1 * @since 0.2.1
*/ */
public OidcClientRegistrationAuthenticationToken(String issuer, Authentication principal, String clientId) { public OidcClientRegistrationAuthenticationToken(Authentication principal, String clientId) {
super(Collections.emptyList()); super(Collections.emptyList());
Assert.hasText(issuer, "issuer cannot be empty");
Assert.notNull(principal, "principal cannot be null"); Assert.notNull(principal, "principal cannot be null");
Assert.hasText(clientId, "clientId cannot be empty"); Assert.hasText(clientId, "clientId cannot be empty");
this.issuer = issuer;
this.principal = principal; this.principal = principal;
this.clientRegistration = null; this.clientRegistration = null;
this.clientId = clientId; this.clientId = clientId;
setAuthenticated(principal.isAuthenticated()); setAuthenticated(principal.isAuthenticated());
} }
/**
* Returns the issuer identifier.
*
* @return the issuer identifier
* @since 0.2.1
*/
public String getIssuer() {
return this.issuer;
}
@Override @Override
public Object getPrincipal() { public Object getPrincipal() {
return this.principal; return this.principal;

View File

@@ -38,7 +38,6 @@ import org.springframework.security.oauth2.core.http.converter.OAuth2ErrorHttpMe
import org.springframework.security.oauth2.core.oidc.OidcClientRegistration; import org.springframework.security.oauth2.core.oidc.OidcClientRegistration;
import org.springframework.security.oauth2.core.oidc.http.converter.OidcClientRegistrationHttpMessageConverter; import org.springframework.security.oauth2.core.oidc.http.converter.OidcClientRegistrationHttpMessageConverter;
import org.springframework.security.oauth2.server.authorization.oidc.authentication.OidcClientRegistrationAuthenticationToken; import org.springframework.security.oauth2.server.authorization.oidc.authentication.OidcClientRegistrationAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.web.WebAttributes;
import org.springframework.security.web.util.matcher.AndRequestMatcher; import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher;
@@ -149,10 +148,7 @@ public final class OidcClientRegistrationEndpointFilter extends OncePerRequestFi
if ("POST".equals(request.getMethod())) { if ("POST".equals(request.getMethod())) {
OidcClientRegistration clientRegistration = this.clientRegistrationHttpMessageConverter.read( OidcClientRegistration clientRegistration = this.clientRegistrationHttpMessageConverter.read(
OidcClientRegistration.class, new ServletServerHttpRequest(request)); OidcClientRegistration.class, new ServletServerHttpRequest(request));
return new OidcClientRegistrationAuthenticationToken(principal, clientRegistration);
String issuer = (String) request.getAttribute(WebAttributes.ISSUER);
return new OidcClientRegistrationAuthenticationToken(issuer, principal, clientRegistration);
} }
// client_id (REQUIRED) // client_id (REQUIRED)
@@ -162,9 +158,7 @@ public final class OidcClientRegistrationEndpointFilter extends OncePerRequestFi
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST);
} }
String issuer = (String) request.getAttribute(WebAttributes.ISSUER); return new OidcClientRegistrationAuthenticationToken(principal, clientId);
return new OidcClientRegistrationAuthenticationToken(issuer, principal, clientId);
} }
private void sendClientRegistrationResponse(HttpServletResponse response, HttpStatus httpStatus, OidcClientRegistration clientRegistration) throws IOException { private void sendClientRegistrationResponse(HttpServletResponse response, HttpStatus httpStatus, OidcClientRegistration clientRegistration) throws IOException {

View File

@@ -15,13 +15,6 @@
*/ */
package org.springframework.security.oauth2.server.authorization.oidc.web; package org.springframework.security.oauth2.server.authorization.oidc.web;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.http.server.ServletServerHttpResponse;
@@ -33,13 +26,18 @@ import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.http.converter.OidcProviderConfigurationHttpMessageConverter; import org.springframework.security.oauth2.core.oidc.http.converter.OidcProviderConfigurationHttpMessageConverter;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm; import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings; import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.web.WebAttributes;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/** /**
* A {@code Filter} that processes OpenID Provider Configuration Requests. * A {@code Filter} that processes OpenID Provider Configuration Requests.
* *
@@ -78,15 +76,13 @@ public final class OidcProviderConfigurationEndpointFilter extends OncePerReques
return; return;
} }
String issuer = (String) request.getAttribute(WebAttributes.ISSUER);
OidcProviderConfiguration providerConfiguration = OidcProviderConfiguration.builder() OidcProviderConfiguration providerConfiguration = OidcProviderConfiguration.builder()
.issuer(issuer) .issuer(this.providerSettings.getIssuer())
.authorizationEndpoint(asUrl(issuer, this.providerSettings.getAuthorizationEndpoint())) .authorizationEndpoint(asUrl(this.providerSettings.getIssuer(), this.providerSettings.getAuthorizationEndpoint()))
.tokenEndpoint(asUrl(issuer, this.providerSettings.getTokenEndpoint())) .tokenEndpoint(asUrl(this.providerSettings.getIssuer(), this.providerSettings.getTokenEndpoint()))
.tokenEndpointAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue()) .tokenEndpointAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue())
.tokenEndpointAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST.getValue()) .tokenEndpointAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST.getValue())
.jwkSetUrl(asUrl(issuer, this.providerSettings.getJwkSetEndpoint())) .jwkSetUrl(asUrl(this.providerSettings.getIssuer(), this.providerSettings.getJwkSetEndpoint()))
.responseType(OAuth2AuthorizationResponseType.CODE.getValue()) .responseType(OAuth2AuthorizationResponseType.CODE.getValue())
.grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()) .grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue())
.grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue())
@@ -104,5 +100,4 @@ public final class OidcProviderConfigurationEndpointFilter extends OncePerReques
private static String asUrl(String issuer, String endpoint) { private static String asUrl(String issuer, String endpoint) {
return UriComponentsBuilder.fromUriString(issuer).path(endpoint).build().toUriString(); return UriComponentsBuilder.fromUriString(issuer).path(endpoint).build().toUriString();
} }
} }

View File

@@ -33,7 +33,6 @@ import org.springframework.security.oauth2.core.OAuth2AuthorizationServerMetadat
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponseType; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponseType;
import org.springframework.security.oauth2.core.http.converter.OAuth2AuthorizationServerMetadataHttpMessageConverter; import org.springframework.security.oauth2.core.http.converter.OAuth2AuthorizationServerMetadataHttpMessageConverter;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings; import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@@ -44,7 +43,6 @@ import org.springframework.web.util.UriComponentsBuilder;
* A {@code Filter} that processes OAuth 2.0 Authorization Server Metadata Requests. * A {@code Filter} that processes OAuth 2.0 Authorization Server Metadata Requests.
* *
* @author Daniel Garnier-Moiroux * @author Daniel Garnier-Moiroux
* @author Joe Grandja
* @since 0.1.1 * @since 0.1.1
* @see OAuth2AuthorizationServerMetadata * @see OAuth2AuthorizationServerMetadata
* @see ProviderSettings * @see ProviderSettings
@@ -74,32 +72,24 @@ public final class OAuth2AuthorizationServerMetadataEndpointFilter extends OnceP
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException { throws ServletException, IOException {
// Resolve the current issuer identifier
String issuer = this.providerSettings.getIssuer();
if (issuer == null) {
issuer = resolveIssuer(request);
}
// Set the current issuer identifier as a request attribute (for use by upstream components)
request.setAttribute(WebAttributes.ISSUER, issuer);
if (!this.requestMatcher.matches(request)) { if (!this.requestMatcher.matches(request)) {
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
return; return;
} }
OAuth2AuthorizationServerMetadata authorizationServerMetadata = OAuth2AuthorizationServerMetadata.builder() OAuth2AuthorizationServerMetadata authorizationServerMetadata = OAuth2AuthorizationServerMetadata.builder()
.issuer(issuer) .issuer(this.providerSettings.getIssuer())
.authorizationEndpoint(asUrl(issuer, this.providerSettings.getAuthorizationEndpoint())) .authorizationEndpoint(asUrl(this.providerSettings.getIssuer(), this.providerSettings.getAuthorizationEndpoint()))
.tokenEndpoint(asUrl(issuer, this.providerSettings.getTokenEndpoint())) .tokenEndpoint(asUrl(this.providerSettings.getIssuer(), this.providerSettings.getTokenEndpoint()))
.tokenEndpointAuthenticationMethods(clientAuthenticationMethods()) .tokenEndpointAuthenticationMethods(clientAuthenticationMethods())
.jwkSetUrl(asUrl(issuer, this.providerSettings.getJwkSetEndpoint())) .jwkSetUrl(asUrl(this.providerSettings.getIssuer(), this.providerSettings.getJwkSetEndpoint()))
.responseType(OAuth2AuthorizationResponseType.CODE.getValue()) .responseType(OAuth2AuthorizationResponseType.CODE.getValue())
.grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()) .grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue())
.grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue())
.grantType(AuthorizationGrantType.REFRESH_TOKEN.getValue()) .grantType(AuthorizationGrantType.REFRESH_TOKEN.getValue())
.tokenRevocationEndpoint(asUrl(issuer, this.providerSettings.getTokenRevocationEndpoint())) .tokenRevocationEndpoint(asUrl(this.providerSettings.getIssuer(), this.providerSettings.getTokenRevocationEndpoint()))
.tokenRevocationEndpointAuthenticationMethods(clientAuthenticationMethods()) .tokenRevocationEndpointAuthenticationMethods(clientAuthenticationMethods())
.tokenIntrospectionEndpoint(asUrl(issuer, this.providerSettings.getTokenIntrospectionEndpoint())) .tokenIntrospectionEndpoint(asUrl(this.providerSettings.getIssuer(), this.providerSettings.getTokenIntrospectionEndpoint()))
.tokenIntrospectionEndpointAuthenticationMethods(clientAuthenticationMethods()) .tokenIntrospectionEndpointAuthenticationMethods(clientAuthenticationMethods())
.codeChallengeMethod("plain") .codeChallengeMethod("plain")
.codeChallengeMethod("S256") .codeChallengeMethod("S256")
@@ -110,17 +100,6 @@ public final class OAuth2AuthorizationServerMetadataEndpointFilter extends OnceP
authorizationServerMetadata, MediaType.APPLICATION_JSON, httpResponse); authorizationServerMetadata, MediaType.APPLICATION_JSON, httpResponse);
} }
private static String resolveIssuer(HttpServletRequest request) {
// @formatter:off
return UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
.replacePath(request.getContextPath())
.replaceQuery(null)
.fragment(null)
.build()
.toUriString();
// @formatter:on
}
private static Consumer<List<String>> clientAuthenticationMethods() { private static Consumer<List<String>> clientAuthenticationMethods() {
return (authenticationMethods) -> { return (authenticationMethods) -> {
authenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue()); authenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue());

View File

@@ -1,37 +0,0 @@
/*
* Copyright 2020-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.server.authorization.web;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
/**
* Well-known attribute names which are used to store information in request or session scope.
*
* @author Joe Grandja
* @since 0.2.1
*/
public final class WebAttributes {
private WebAttributes() {
}
/**
* The {@link javax.servlet.http.HttpServletRequest#getAttribute(String) request attribute} name that holds the current issuer identifier.
* The issuer identifier is resolved from {@link ProviderSettings#getIssuer()} or dynamically from the current {@link javax.servlet.http.HttpServletRequest}.
*/
public static final String ISSUER = WebAttributes.class.getName().concat(".ISSUER");
}

View File

@@ -28,7 +28,6 @@ import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationToken; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter; import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter;
import org.springframework.security.oauth2.server.authorization.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationConverter; import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -89,10 +88,8 @@ public final class OAuth2AuthorizationCodeAuthenticationConverter implements Aut
} }
}); });
String issuer = (String) request.getAttribute(WebAttributes.ISSUER);
return new OAuth2AuthorizationCodeAuthenticationToken( return new OAuth2AuthorizationCodeAuthenticationToken(
issuer, code, clientPrincipal, redirectUri, additionalParameters); code, clientPrincipal, redirectUri, additionalParameters);
} }
} }

View File

@@ -31,7 +31,6 @@ import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationToken; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter; import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter;
import org.springframework.security.oauth2.server.authorization.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationConverter; import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -84,10 +83,7 @@ public final class OAuth2ClientCredentialsAuthenticationConverter implements Aut
} }
}); });
String issuer = (String) request.getAttribute(WebAttributes.ISSUER);
return new OAuth2ClientCredentialsAuthenticationToken( return new OAuth2ClientCredentialsAuthenticationToken(
issuer, clientPrincipal, requestedScopes, additionalParameters); clientPrincipal, requestedScopes, additionalParameters);
} }
} }

View File

@@ -31,7 +31,6 @@ import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2RefreshTokenAuthenticationToken; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2RefreshTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter; import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter;
import org.springframework.security.oauth2.server.authorization.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationConverter; import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -95,10 +94,7 @@ public final class OAuth2RefreshTokenAuthenticationConverter implements Authenti
} }
}); });
String issuer = (String) request.getAttribute(WebAttributes.ISSUER);
return new OAuth2RefreshTokenAuthenticationToken( return new OAuth2RefreshTokenAuthenticationToken(
issuer, refreshToken, clientPrincipal, requestedScopes, additionalParameters); refreshToken, clientPrincipal, requestedScopes, additionalParameters);
} }
} }

View File

@@ -213,11 +213,10 @@ public class OAuth2ClientCredentialsGrantTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
this.registeredClientRepository.save(registeredClient); this.registeredClientRepository.save(registeredClient);
String issuer = "https://example.com/issuer1";
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication = OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication =
new OAuth2ClientCredentialsAuthenticationToken(issuer, clientPrincipal, null, null); new OAuth2ClientCredentialsAuthenticationToken(clientPrincipal, null, null);
when(authenticationConverter.convert(any())).thenReturn(clientCredentialsAuthentication); when(authenticationConverter.convert(any())).thenReturn(clientCredentialsAuthentication);
OAuth2AccessToken accessToken = new OAuth2AccessToken( OAuth2AccessToken accessToken = new OAuth2AccessToken(

View File

@@ -88,10 +88,9 @@ public class JwtEncodingContextTests {
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute( OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest.class.getName());
String issuer = "https://provider.com";
OAuth2AuthorizationCodeAuthenticationToken authorizationGrant = OAuth2AuthorizationCodeAuthenticationToken authorizationGrant =
new OAuth2AuthorizationCodeAuthenticationToken( new OAuth2AuthorizationCodeAuthenticationToken(
issuer, "code", clientPrincipal, authorizationRequest.getRedirectUri(), null); "code", clientPrincipal, authorizationRequest.getRedirectUri(), null);
JwtEncodingContext context = JwtEncodingContext.with(headers, claims) JwtEncodingContext context = JwtEncodingContext.with(headers, claims)
.registeredClient(registeredClient) .registeredClient(registeredClient)

View File

@@ -34,7 +34,6 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthorizationCode;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2TokenType; import org.springframework.security.oauth2.core.OAuth2TokenType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
@@ -49,6 +48,7 @@ import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder; import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.server.authorization.JwtEncodingContext; import org.springframework.security.oauth2.server.authorization.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.core.OAuth2AuthorizationCode;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenCustomizer; import org.springframework.security.oauth2.server.authorization.OAuth2TokenCustomizer;
import org.springframework.security.oauth2.server.authorization.TestOAuth2Authorizations; import org.springframework.security.oauth2.server.authorization.TestOAuth2Authorizations;
@@ -74,7 +74,6 @@ import static org.mockito.Mockito.when;
* @author Daniel Garnier-Moiroux * @author Daniel Garnier-Moiroux
*/ */
public class OAuth2AuthorizationCodeAuthenticationProviderTests { public class OAuth2AuthorizationCodeAuthenticationProviderTests {
private static final String ISSUER = "https://example.com/issuer1";
private static final String AUTHORIZATION_CODE = "code"; private static final String AUTHORIZATION_CODE = "code";
private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.CODE); private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.CODE);
private OAuth2AuthorizationService authorizationService; private OAuth2AuthorizationService authorizationService;
@@ -131,7 +130,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
TestingAuthenticationToken clientPrincipal = new TestingAuthenticationToken( TestingAuthenticationToken clientPrincipal = new TestingAuthenticationToken(
registeredClient.getClientId(), registeredClient.getClientSecret()); registeredClient.getClientId(), registeredClient.getClientSecret());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, null, null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) .extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
@@ -145,7 +144,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null); registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null);
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, null, null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) .extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
@@ -159,7 +158,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, null, null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) .extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
@@ -177,7 +176,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, null, null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) .extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
@@ -204,7 +203,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute( OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest.class.getName());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri() + "-invalid", null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri() + "-invalid", null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) .extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
@@ -228,7 +227,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute( OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest.class.getName());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -254,7 +253,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute( OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest.class.getName());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -275,7 +274,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute( OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest.class.getName());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt()); when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt());
@@ -331,7 +330,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute( OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest.class.getName());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt()); when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt());
@@ -405,7 +404,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute( OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest.class.getName());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt()); when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt());
@@ -468,7 +467,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute( OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest.class.getName());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
Instant accessTokenIssuedAt = Instant.now(); Instant accessTokenIssuedAt = Instant.now();
Instant accessTokenExpiresAt = accessTokenIssuedAt.plus(accessTokenTTL); Instant accessTokenExpiresAt = accessTokenIssuedAt.plus(accessTokenTTL);
@@ -507,7 +506,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute( OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest.class.getName());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt()); when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt());
@@ -540,7 +539,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute( OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationRequest.class.getName());
OAuth2AuthorizationCodeAuthenticationToken authentication = OAuth2AuthorizationCodeAuthenticationToken authentication =
new OAuth2AuthorizationCodeAuthenticationToken(ISSUER, AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); new OAuth2AuthorizationCodeAuthenticationToken(AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication); (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication);

View File

@@ -35,7 +35,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
* @author Daniel Garnier-Moiroux * @author Daniel Garnier-Moiroux
*/ */
public class OAuth2AuthorizationCodeAuthenticationTokenTests { public class OAuth2AuthorizationCodeAuthenticationTokenTests {
private String issuer = "https://example.com/issuer1";
private String code = "code"; private String code = "code";
private RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); private RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
private OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( private OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
@@ -43,23 +42,16 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests {
private String redirectUri = "redirectUri"; private String redirectUri = "redirectUri";
private Map<String, Object> additionalParameters = Collections.singletonMap("param1", "value1"); private Map<String, Object> additionalParameters = Collections.singletonMap("param1", "value1");
@Test
public void constructorWhenIssuerNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.code, this.clientPrincipal, this.redirectUri, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("issuer cannot be empty");
}
@Test @Test
public void constructorWhenCodeNullThenThrowIllegalArgumentException() { public void constructorWhenCodeNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.issuer, null, this.clientPrincipal, this.redirectUri, null)) assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.clientPrincipal, this.redirectUri, null))
.isInstanceOf(IllegalArgumentException.class) .isInstanceOf(IllegalArgumentException.class)
.hasMessage("code cannot be empty"); .hasMessage("code cannot be empty");
} }
@Test @Test
public void constructorWhenClientPrincipalNullThenThrowIllegalArgumentException() { public void constructorWhenClientPrincipalNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.issuer, this.code, null, this.redirectUri, null)) assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.code, null, this.redirectUri, null))
.isInstanceOf(IllegalArgumentException.class) .isInstanceOf(IllegalArgumentException.class)
.hasMessage("clientPrincipal cannot be null"); .hasMessage("clientPrincipal cannot be null");
} }
@@ -67,9 +59,8 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests {
@Test @Test
public void constructorWhenClientPrincipalProvidedThenCreated() { public void constructorWhenClientPrincipalProvidedThenCreated() {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
this.issuer, this.code, this.clientPrincipal, this.redirectUri, this.additionalParameters); this.code, this.clientPrincipal, this.redirectUri, this.additionalParameters);
assertThat(authentication.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE); assertThat(authentication.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
assertThat(authentication.getIssuer()).isEqualTo(this.issuer);
assertThat(authentication.getPrincipal()).isEqualTo(this.clientPrincipal); assertThat(authentication.getPrincipal()).isEqualTo(this.clientPrincipal);
assertThat(authentication.getCredentials().toString()).isEmpty(); assertThat(authentication.getCredentials().toString()).isEmpty();
assertThat(authentication.getCode()).isEqualTo(this.code); assertThat(authentication.getCode()).isEqualTo(this.code);
@@ -80,7 +71,7 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests {
@Test @Test
public void getAdditionalParametersWhenUpdateThenThrowUnsupportedOperationException() { public void getAdditionalParametersWhenUpdateThenThrowUnsupportedOperationException() {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
this.issuer, this.code, this.clientPrincipal, this.redirectUri, this.additionalParameters); this.code, this.clientPrincipal, this.redirectUri, this.additionalParameters);
assertThatThrownBy(() -> authentication.getAdditionalParameters().put("another_key", 1)) assertThatThrownBy(() -> authentication.getAdditionalParameters().put("another_key", 1))
.isInstanceOf(UnsupportedOperationException.class); .isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> authentication.getAdditionalParameters().remove("some_key")) assertThatThrownBy(() -> authentication.getAdditionalParameters().remove("some_key"))

View File

@@ -36,12 +36,12 @@ import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JoseHeaderNames; import org.springframework.security.oauth2.jwt.JoseHeaderNames;
import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtEncoder; import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.server.authorization.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenCustomizer;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients; import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients;
import org.springframework.security.oauth2.server.authorization.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenCustomizer;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -105,12 +105,11 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientPrincipalNotOAuth2ClientAuthenticationTokenThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientPrincipalNotOAuth2ClientAuthenticationTokenThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
TestingAuthenticationToken clientPrincipal = new TestingAuthenticationToken( TestingAuthenticationToken clientPrincipal = new TestingAuthenticationToken(
registeredClient.getClientId(), registeredClient.getClientSecret()); registeredClient.getClientId(), registeredClient.getClientSecret());
OAuth2ClientCredentialsAuthenticationToken authentication = OAuth2ClientCredentialsAuthenticationToken authentication =
new OAuth2ClientCredentialsAuthenticationToken(issuer, clientPrincipal, null, null); new OAuth2ClientCredentialsAuthenticationToken(clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -121,12 +120,11 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientPrincipalNotAuthenticatedThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientPrincipalNotAuthenticatedThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null); registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null);
OAuth2ClientCredentialsAuthenticationToken authentication = OAuth2ClientCredentialsAuthenticationToken authentication =
new OAuth2ClientCredentialsAuthenticationToken(issuer, clientPrincipal, null, null); new OAuth2ClientCredentialsAuthenticationToken(clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -137,14 +135,13 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientNotAuthorizedToRequestTokenThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientNotAuthorizedToRequestTokenThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2() RegisteredClient registeredClient = TestRegisteredClients.registeredClient2()
.authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.CLIENT_CREDENTIALS)) .authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.CLIENT_CREDENTIALS))
.build(); .build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2ClientCredentialsAuthenticationToken authentication = OAuth2ClientCredentialsAuthenticationToken authentication =
new OAuth2ClientCredentialsAuthenticationToken(issuer, clientPrincipal, null, null); new OAuth2ClientCredentialsAuthenticationToken(clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -155,12 +152,11 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
@Test @Test
public void authenticateWhenInvalidScopeThenThrowOAuth2AuthenticationException() { public void authenticateWhenInvalidScopeThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken( OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
issuer, clientPrincipal, Collections.singleton("invalid-scope"), null); clientPrincipal, Collections.singleton("invalid-scope"), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -171,13 +167,12 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
@Test @Test
public void authenticateWhenScopeRequestedThenAccessTokenContainsScope() { public void authenticateWhenScopeRequestedThenAccessTokenContainsScope() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
Set<String> requestedScope = Collections.singleton("scope1"); Set<String> requestedScope = Collections.singleton("scope1");
OAuth2ClientCredentialsAuthenticationToken authentication = OAuth2ClientCredentialsAuthenticationToken authentication =
new OAuth2ClientCredentialsAuthenticationToken(issuer, clientPrincipal, requestedScope, null); new OAuth2ClientCredentialsAuthenticationToken(clientPrincipal, requestedScope, null);
when(this.jwtEncoder.encode(any(), any())) when(this.jwtEncoder.encode(any(), any()))
.thenReturn(createJwt(Collections.singleton("mapped-scoped"))); .thenReturn(createJwt(Collections.singleton("mapped-scoped")));
@@ -189,12 +184,11 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
@Test @Test
public void authenticateWhenValidAuthenticationThenReturnAccessToken() { public void authenticateWhenValidAuthenticationThenReturnAccessToken() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2ClientCredentialsAuthenticationToken authentication = OAuth2ClientCredentialsAuthenticationToken authentication =
new OAuth2ClientCredentialsAuthenticationToken(issuer, clientPrincipal, null, null); new OAuth2ClientCredentialsAuthenticationToken(clientPrincipal, null, null);
when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt(registeredClient.getScopes())); when(this.jwtEncoder.encode(any(), any())).thenReturn(createJwt(registeredClient.getScopes()));

View File

@@ -35,23 +35,15 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
* @author Alexey Nesterov * @author Alexey Nesterov
*/ */
public class OAuth2ClientCredentialsAuthenticationTokenTests { public class OAuth2ClientCredentialsAuthenticationTokenTests {
private String issuer = "https://example.com/issuer1";
private final RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); private final RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
private final OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( private final OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
this.registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, this.registeredClient.getClientSecret()); this.registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, this.registeredClient.getClientSecret());
private Set<String> scopes = Collections.singleton("scope1"); private Set<String> scopes = Collections.singleton("scope1");
private Map<String, Object> additionalParameters = Collections.singletonMap("param1", "value1"); private Map<String, Object> additionalParameters = Collections.singletonMap("param1", "value1");
@Test
public void constructorWhenIssuerNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2ClientCredentialsAuthenticationToken(null, this.clientPrincipal, this.scopes, this.additionalParameters))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("issuer cannot be empty");
}
@Test @Test
public void constructorWhenClientPrincipalNullThenThrowIllegalArgumentException() { public void constructorWhenClientPrincipalNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2ClientCredentialsAuthenticationToken(this.issuer, null, this.scopes, this.additionalParameters)) assertThatThrownBy(() -> new OAuth2ClientCredentialsAuthenticationToken(null, this.scopes, this.additionalParameters))
.isInstanceOf(IllegalArgumentException.class) .isInstanceOf(IllegalArgumentException.class)
.hasMessage("clientPrincipal cannot be null"); .hasMessage("clientPrincipal cannot be null");
} }
@@ -59,10 +51,9 @@ public class OAuth2ClientCredentialsAuthenticationTokenTests {
@Test @Test
public void constructorWhenClientPrincipalProvidedThenCreated() { public void constructorWhenClientPrincipalProvidedThenCreated() {
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken( OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
this.issuer, this.clientPrincipal, this.scopes, this.additionalParameters); this.clientPrincipal, this.scopes, this.additionalParameters);
assertThat(authentication.getGrantType()).isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS); assertThat(authentication.getGrantType()).isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS);
assertThat(authentication.getIssuer()).isEqualTo(this.issuer);
assertThat(authentication.getPrincipal()).isEqualTo(this.clientPrincipal); assertThat(authentication.getPrincipal()).isEqualTo(this.clientPrincipal);
assertThat(authentication.getCredentials().toString()).isEmpty(); assertThat(authentication.getCredentials().toString()).isEmpty();
assertThat(authentication.getScopes()).isEqualTo(this.scopes); assertThat(authentication.getScopes()).isEqualTo(this.scopes);
@@ -74,10 +65,9 @@ public class OAuth2ClientCredentialsAuthenticationTokenTests {
Set<String> expectedScopes = Collections.singleton("test-scope"); Set<String> expectedScopes = Collections.singleton("test-scope");
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken( OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
this.issuer, this.clientPrincipal, expectedScopes, this.additionalParameters); this.clientPrincipal, expectedScopes, this.additionalParameters);
assertThat(authentication.getGrantType()).isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS); assertThat(authentication.getGrantType()).isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS);
assertThat(authentication.getIssuer()).isEqualTo(this.issuer);
assertThat(authentication.getPrincipal()).isEqualTo(this.clientPrincipal); assertThat(authentication.getPrincipal()).isEqualTo(this.clientPrincipal);
assertThat(authentication.getCredentials().toString()).isEmpty(); assertThat(authentication.getCredentials().toString()).isEmpty();
assertThat(authentication.getScopes()).isEqualTo(expectedScopes); assertThat(authentication.getScopes()).isEqualTo(expectedScopes);

View File

@@ -132,7 +132,6 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenValidRefreshTokenThenReturnAccessToken() { public void authenticateWhenValidRefreshTokenThenReturnAccessToken() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken( when(this.authorizationService.findByToken(
@@ -143,7 +142,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null);
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication); (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication);
@@ -177,7 +176,6 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenValidRefreshTokenThenReturnIdToken() { public void authenticateWhenValidRefreshTokenThenReturnIdToken() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken( when(this.authorizationService.findByToken(
@@ -188,7 +186,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null);
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication); (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication);
@@ -245,7 +243,6 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenReuseRefreshTokensFalseThenReturnNewRefreshToken() { public void authenticateWhenReuseRefreshTokensFalseThenReturnNewRefreshToken() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient() RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.tokenSettings(TokenSettings.builder().reuseRefreshTokens(false).build()) .tokenSettings(TokenSettings.builder().reuseRefreshTokens(false).build())
.build(); .build();
@@ -258,7 +255,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null);
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication); (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication);
@@ -273,7 +270,6 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenRequestedScopesAuthorizedThenAccessTokenIncludesScopes() { public void authenticateWhenRequestedScopesAuthorizedThenAccessTokenIncludesScopes() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient() RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.scope("scope2") .scope("scope2")
.scope("scope3") .scope("scope3")
@@ -290,7 +286,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
Set<String> requestedScopes = new HashSet<>(authorizedScopes); Set<String> requestedScopes = new HashSet<>(authorizedScopes);
requestedScopes.remove("scope1"); requestedScopes.remove("scope1");
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, requestedScopes, null); authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, requestedScopes, null);
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication); (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication);
@@ -300,7 +296,6 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenCustomRefreshTokenGeneratorThenUsed() { public void authenticateWhenCustomRefreshTokenGeneratorThenUsed() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient() RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.tokenSettings(TokenSettings.builder().reuseRefreshTokens(false).build()) .tokenSettings(TokenSettings.builder().reuseRefreshTokens(false).build())
.build(); .build();
@@ -322,7 +317,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null);
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication); (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider.authenticate(authentication);
@@ -333,7 +328,6 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenRequestedScopesNotAuthorizedThenThrowOAuth2AuthenticationException() { public void authenticateWhenRequestedScopesNotAuthorizedThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken( when(this.authorizationService.findByToken(
@@ -347,7 +341,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
Set<String> requestedScopes = new HashSet<>(authorizedScopes); Set<String> requestedScopes = new HashSet<>(authorizedScopes);
requestedScopes.add("unauthorized"); requestedScopes.add("unauthorized");
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, requestedScopes, null); authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, requestedScopes, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -358,12 +352,11 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenInvalidRefreshTokenThenThrowOAuth2AuthenticationException() { public void authenticateWhenInvalidRefreshTokenThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, "invalid", clientPrincipal, null, null); "invalid", clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -374,12 +367,11 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientPrincipalNotOAuth2ClientAuthenticationTokenThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientPrincipalNotOAuth2ClientAuthenticationTokenThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
TestingAuthenticationToken clientPrincipal = new TestingAuthenticationToken( TestingAuthenticationToken clientPrincipal = new TestingAuthenticationToken(
registeredClient.getClientId(), registeredClient.getClientSecret()); registeredClient.getClientId(), registeredClient.getClientSecret());
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, "refresh-token", clientPrincipal, null, null); "refresh-token", clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -390,12 +382,11 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientPrincipalNotAuthenticatedThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientPrincipalNotAuthenticatedThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null); registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null);
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, "refresh-token", clientPrincipal, null, null); "refresh-token", clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -406,7 +397,6 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenRefreshTokenIssuedToAnotherClientThenThrowOAuth2AuthenticationException() { public void authenticateWhenRefreshTokenIssuedToAnotherClientThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken( when(this.authorizationService.findByToken(
@@ -418,7 +408,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient2, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient2.getClientSecret()); registeredClient2, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient2.getClientSecret());
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -429,7 +419,6 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientNotAuthorizedToRefreshTokenThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientNotAuthorizedToRefreshTokenThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient() RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.REFRESH_TOKEN)) .authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.REFRESH_TOKEN))
.build(); .build();
@@ -442,7 +431,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -453,7 +442,6 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenExpiredRefreshTokenThenThrowOAuth2AuthenticationException() { public void authenticateWhenExpiredRefreshTokenThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
OAuth2RefreshToken expiredRefreshToken = new OAuth2RefreshToken( OAuth2RefreshToken expiredRefreshToken = new OAuth2RefreshToken(
@@ -467,7 +455,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -478,7 +466,6 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
@Test @Test
public void authenticateWhenRevokedRefreshTokenThenThrowOAuth2AuthenticationException() { public void authenticateWhenRevokedRefreshTokenThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken( OAuth2RefreshToken refreshToken = new OAuth2RefreshToken(
"refresh-token", Instant.now().minusSeconds(120), Instant.now().plusSeconds(1000)); "refresh-token", Instant.now().minusSeconds(120), Instant.now().plusSeconds(1000));
@@ -493,7 +480,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
issuer, authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)

View File

@@ -36,33 +36,25 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
* @since 0.0.3 * @since 0.0.3
*/ */
public class OAuth2RefreshTokenAuthenticationTokenTests { public class OAuth2RefreshTokenAuthenticationTokenTests {
private String issuer = "https://example.com/issuer1";
private RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); private RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
private OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( private OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(
this.registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, this.registeredClient.getClientSecret()); this.registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, this.registeredClient.getClientSecret());
private Set<String> scopes = Collections.singleton("scope1"); private Set<String> scopes = Collections.singleton("scope1");
private Map<String, Object> additionalParameters = Collections.singletonMap("param1", "value1"); private Map<String, Object> additionalParameters = Collections.singletonMap("param1", "value1");
@Test
public void constructorWhenIssuerNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2RefreshTokenAuthenticationToken(null, "refresh-token", this.clientPrincipal, this.scopes, this.additionalParameters))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("issuer cannot be empty");
}
@Test @Test
public void constructorWhenRefreshTokenNullOrEmptyThenThrowIllegalArgumentException() { public void constructorWhenRefreshTokenNullOrEmptyThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2RefreshTokenAuthenticationToken(this.issuer, null, this.clientPrincipal, this.scopes, this.additionalParameters)) assertThatThrownBy(() -> new OAuth2RefreshTokenAuthenticationToken(null, this.clientPrincipal, this.scopes, this.additionalParameters))
.isInstanceOf(IllegalArgumentException.class) .isInstanceOf(IllegalArgumentException.class)
.hasMessage("refreshToken cannot be empty"); .hasMessage("refreshToken cannot be empty");
assertThatThrownBy(() -> new OAuth2RefreshTokenAuthenticationToken(this.issuer, "", this.clientPrincipal, this.scopes, this.additionalParameters)) assertThatThrownBy(() -> new OAuth2RefreshTokenAuthenticationToken("", this.clientPrincipal, this.scopes, this.additionalParameters))
.isInstanceOf(IllegalArgumentException.class) .isInstanceOf(IllegalArgumentException.class)
.hasMessage("refreshToken cannot be empty"); .hasMessage("refreshToken cannot be empty");
} }
@Test @Test
public void constructorWhenClientPrincipalNullThenThrowIllegalArgumentException() { public void constructorWhenClientPrincipalNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2RefreshTokenAuthenticationToken(this.issuer, "refresh-token", null, this.scopes, this.additionalParameters)) assertThatThrownBy(() -> new OAuth2RefreshTokenAuthenticationToken("refresh-token", null, this.scopes, this.additionalParameters))
.isInstanceOf(IllegalArgumentException.class) .isInstanceOf(IllegalArgumentException.class)
.hasMessage("clientPrincipal cannot be null"); .hasMessage("clientPrincipal cannot be null");
} }
@@ -70,9 +62,8 @@ public class OAuth2RefreshTokenAuthenticationTokenTests {
@Test @Test
public void constructorWhenScopesProvidedThenCreated() { public void constructorWhenScopesProvidedThenCreated() {
OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken(
this.issuer, "refresh-token", this.clientPrincipal, this.scopes, this.additionalParameters); "refresh-token", this.clientPrincipal, this.scopes, this.additionalParameters);
assertThat(authentication.getGrantType()).isEqualTo(AuthorizationGrantType.REFRESH_TOKEN); assertThat(authentication.getGrantType()).isEqualTo(AuthorizationGrantType.REFRESH_TOKEN);
assertThat(authentication.getIssuer()).isEqualTo(this.issuer);
assertThat(authentication.getRefreshToken()).isEqualTo("refresh-token"); assertThat(authentication.getRefreshToken()).isEqualTo("refresh-token");
assertThat(authentication.getPrincipal()).isEqualTo(this.clientPrincipal); assertThat(authentication.getPrincipal()).isEqualTo(this.clientPrincipal);
assertThat(authentication.getCredentials().toString()).isEmpty(); assertThat(authentication.getCredentials().toString()).isEmpty();

View File

@@ -83,7 +83,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
this.registeredClientRepository = mock(RegisteredClientRepository.class); this.registeredClientRepository = mock(RegisteredClientRepository.class);
this.authorizationService = mock(OAuth2AuthorizationService.class); this.authorizationService = mock(OAuth2AuthorizationService.class);
this.jwtEncoder = mock(JwtEncoder.class); this.jwtEncoder = mock(JwtEncoder.class);
this.providerSettings = ProviderSettings.builder().build(); this.providerSettings = ProviderSettings.builder().issuer("https://auth-server:9000").build();
this.authenticationProvider = new OidcClientRegistrationAuthenticationProvider( this.authenticationProvider = new OidcClientRegistrationAuthenticationProvider(
this.registeredClientRepository, this.authorizationService, this.jwtEncoder); this.registeredClientRepository, this.authorizationService, this.jwtEncoder);
this.authenticationProvider.setProviderSettings(this.providerSettings); this.authenticationProvider.setProviderSettings(this.providerSettings);
@@ -117,14 +117,13 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenPrincipalNotOAuth2TokenAuthenticationTokenThenThrowOAuth2AuthenticationException() { public void authenticateWhenPrincipalNotOAuth2TokenAuthenticationTokenThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
TestingAuthenticationToken principal = new TestingAuthenticationToken("principal", "credentials"); TestingAuthenticationToken principal = new TestingAuthenticationToken("principal", "credentials");
OidcClientRegistration clientRegistration = OidcClientRegistration.builder() OidcClientRegistration clientRegistration = OidcClientRegistration.builder()
.redirectUri("https://client.example.com") .redirectUri("https://client.example.com")
.build(); .build();
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, clientRegistration); principal, clientRegistration);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -134,14 +133,13 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenPrincipalNotAuthenticatedThenThrowOAuth2AuthenticationException() { public void authenticateWhenPrincipalNotAuthenticatedThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
JwtAuthenticationToken principal = new JwtAuthenticationToken(createJwtClientRegistration()); JwtAuthenticationToken principal = new JwtAuthenticationToken(createJwtClientRegistration());
OidcClientRegistration clientRegistration = OidcClientRegistration.builder() OidcClientRegistration clientRegistration = OidcClientRegistration.builder()
.redirectUri("https://client.example.com") .redirectUri("https://client.example.com")
.build(); .build();
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, clientRegistration); principal, clientRegistration);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -151,7 +149,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenAccessTokenNotFoundThenThrowOAuth2AuthenticationException() { public void authenticateWhenAccessTokenNotFoundThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwtClientRegistration(); Jwt jwt = createJwtClientRegistration();
JwtAuthenticationToken principal = new JwtAuthenticationToken( JwtAuthenticationToken principal = new JwtAuthenticationToken(
jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create"));
@@ -160,7 +157,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
.build(); .build();
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, clientRegistration); principal, clientRegistration);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -172,7 +169,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenAccessTokenNotActiveThenThrowOAuth2AuthenticationException() { public void authenticateWhenAccessTokenNotActiveThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwtClientRegistration(); Jwt jwt = createJwtClientRegistration();
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -192,7 +188,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
.build(); .build();
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, clientRegistration); principal, clientRegistration);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -204,7 +200,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientRegistrationRequestAndAccessTokenNotAuthorizedThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientRegistrationRequestAndAccessTokenNotAuthorizedThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwt(Collections.singleton("unauthorized.scope")); Jwt jwt = createJwt(Collections.singleton("unauthorized.scope"));
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -223,7 +218,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
.build(); .build();
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, clientRegistration); principal, clientRegistration);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -235,7 +230,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientRegistrationRequestAndAccessTokenContainsRequiredScopeAndAdditionalScopeThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientRegistrationRequestAndAccessTokenContainsRequiredScopeAndAdditionalScopeThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwt(new HashSet<>(Arrays.asList("client.create", "scope1"))); Jwt jwt = createJwt(new HashSet<>(Arrays.asList("client.create", "scope1")));
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -254,7 +248,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
.build(); .build();
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, clientRegistration); principal, clientRegistration);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -266,7 +260,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientRegistrationRequestAndInvalidRedirectUriThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientRegistrationRequestAndInvalidRedirectUriThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwtClientRegistration(); Jwt jwt = createJwtClientRegistration();
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -287,7 +280,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
// @formatter:on // @formatter:on
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, clientRegistration); principal, clientRegistration);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -299,7 +292,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientRegistrationRequestAndRedirectUriContainsFragmentThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientRegistrationRequestAndRedirectUriContainsFragmentThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwtClientRegistration(); Jwt jwt = createJwtClientRegistration();
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -320,7 +312,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
// @formatter:on // @formatter:on
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, clientRegistration); principal, clientRegistration);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -332,7 +324,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientRegistrationRequestAndValidAccessTokenThenReturnClientRegistration() { public void authenticateWhenClientRegistrationRequestAndValidAccessTokenThenReturnClientRegistration() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwtClientRegistration(); Jwt jwt = createJwtClientRegistration();
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -359,8 +350,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
// @formatter:on // @formatter:on
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, clientRegistration); principal, clientRegistration);
OidcClientRegistrationAuthenticationToken authenticationResult = OidcClientRegistrationAuthenticationToken authenticationResult =
(OidcClientRegistrationAuthenticationToken) this.authenticationProvider.authenticate(authentication); (OidcClientRegistrationAuthenticationToken) this.authenticationProvider.authenticate(authentication);
@@ -425,7 +415,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
assertThat(clientRegistrationResult.getIdTokenSignedResponseAlgorithm()) assertThat(clientRegistrationResult.getIdTokenSignedResponseAlgorithm())
.isEqualTo(registeredClientResult.getTokenSettings().getIdTokenSignatureAlgorithm().getName()); .isEqualTo(registeredClientResult.getTokenSettings().getIdTokenSignatureAlgorithm().getName());
String expectedRegistrationClientUrl = UriComponentsBuilder.fromUriString(issuer) String expectedRegistrationClientUrl = UriComponentsBuilder.fromUriString(this.providerSettings.getIssuer())
.path(this.providerSettings.getOidcClientRegistrationEndpoint()) .path(this.providerSettings.getOidcClientRegistrationEndpoint())
.queryParam(OAuth2ParameterNames.CLIENT_ID, registeredClientResult.getClientId()).toUriString(); .queryParam(OAuth2ParameterNames.CLIENT_ID, registeredClientResult.getClientId()).toUriString();
@@ -435,7 +425,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientConfigurationRequestAndAccessTokenNotAuthorizedThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientConfigurationRequestAndAccessTokenNotAuthorizedThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwt(Collections.singleton("unauthorized.scope")); Jwt jwt = createJwt(Collections.singleton("unauthorized.scope"));
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -451,7 +440,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
jwt, AuthorityUtils.createAuthorityList("SCOPE_unauthorized.scope")); jwt, AuthorityUtils.createAuthorityList("SCOPE_unauthorized.scope"));
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, registeredClient.getClientId()); principal, registeredClient.getClientId());
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -463,7 +452,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientConfigurationRequestAndAccessTokenContainsRequiredScopeAndAdditionalScopeThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientConfigurationRequestAndAccessTokenContainsRequiredScopeAndAdditionalScopeThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwt(new HashSet<>(Arrays.asList("client.read", "scope1"))); Jwt jwt = createJwt(new HashSet<>(Arrays.asList("client.read", "scope1")));
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -479,7 +467,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read", "SCOPE_scope1")); jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read", "SCOPE_scope1"));
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, registeredClient.getClientId()); principal, registeredClient.getClientId());
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -491,7 +479,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientConfigurationRequestAndRegisteredClientNotFoundThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientConfigurationRequestAndRegisteredClientNotFoundThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwtClientConfiguration(); Jwt jwt = createJwtClientConfiguration();
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -507,7 +494,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read"));
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, registeredClient.getClientId()); principal, registeredClient.getClientId());
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -521,7 +508,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientConfigurationRequestClientIdNotEqualToAuthorizedClientThenThrowOAuth2AuthenticationException() { public void authenticateWhenClientConfigurationRequestClientIdNotEqualToAuthorizedClientThenThrowOAuth2AuthenticationException() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwtClientConfiguration(); Jwt jwt = createJwtClientConfiguration();
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -541,7 +527,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read"));
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, registeredClient.getClientId()); principal, registeredClient.getClientId());
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class) .isInstanceOf(OAuth2AuthenticationException.class)
@@ -555,7 +541,6 @@ public class OidcClientRegistrationAuthenticationProviderTests {
@Test @Test
public void authenticateWhenClientConfigurationRequestAndValidAccessTokenThenReturnClientRegistration() { public void authenticateWhenClientConfigurationRequestAndValidAccessTokenThenReturnClientRegistration() {
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwtClientConfiguration(); Jwt jwt = createJwtClientConfiguration();
OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, OAuth2AccessToken jwtAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getTokenValue(), jwt.getIssuedAt(),
@@ -575,7 +560,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read"));
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
issuer, principal, registeredClient.getClientId()); principal, registeredClient.getClientId());
OidcClientRegistrationAuthenticationToken authenticationResult = OidcClientRegistrationAuthenticationToken authenticationResult =
(OidcClientRegistrationAuthenticationToken) this.authenticationProvider.authenticate(authentication); (OidcClientRegistrationAuthenticationToken) this.authenticationProvider.authenticate(authentication);
@@ -612,7 +597,7 @@ public class OidcClientRegistrationAuthenticationProviderTests {
assertThat(clientRegistrationResult.getIdTokenSignedResponseAlgorithm()) assertThat(clientRegistrationResult.getIdTokenSignedResponseAlgorithm())
.isEqualTo(registeredClient.getTokenSettings().getIdTokenSignatureAlgorithm().getName()); .isEqualTo(registeredClient.getTokenSettings().getIdTokenSignatureAlgorithm().getName());
String expectedRegistrationClientUrl = UriComponentsBuilder.fromUriString(issuer) String expectedRegistrationClientUrl = UriComponentsBuilder.fromUriString(this.providerSettings.getIssuer())
.path(this.providerSettings.getOidcClientRegistrationEndpoint()) .path(this.providerSettings.getOidcClientRegistrationEndpoint())
.queryParam(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()).toUriString(); .queryParam(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()).toUriString();

View File

@@ -29,52 +29,43 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* @author Joe Grandja * @author Joe Grandja
*/ */
public class OidcClientRegistrationAuthenticationTokenTests { public class OidcClientRegistrationAuthenticationTokenTests {
private String issuer = "https://example.com/issuer1";
private TestingAuthenticationToken principal = new TestingAuthenticationToken("principal", "credentials"); private TestingAuthenticationToken principal = new TestingAuthenticationToken("principal", "credentials");
private OidcClientRegistration clientRegistration = OidcClientRegistration.builder() private OidcClientRegistration clientRegistration = OidcClientRegistration.builder()
.redirectUri("https://client.example.com").build(); .redirectUri("https://client.example.com").build();
@Test
public void constructorWhenIssuerNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcClientRegistrationAuthenticationToken(null, this.principal, this.clientRegistration))
.withMessage("issuer cannot be empty");
}
@Test @Test
public void constructorWhenPrincipalNullThenThrowIllegalArgumentException() { public void constructorWhenPrincipalNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcClientRegistrationAuthenticationToken(this.issuer, null, this.clientRegistration)) .isThrownBy(() -> new OidcClientRegistrationAuthenticationToken(null, this.clientRegistration))
.withMessage("principal cannot be null"); .withMessage("principal cannot be null");
} }
@Test @Test
public void constructorWhenClientRegistrationNullThenThrowIllegalArgumentException() { public void constructorWhenClientRegistrationNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcClientRegistrationAuthenticationToken(this.issuer, this.principal, (OidcClientRegistration) null)) .isThrownBy(() -> new OidcClientRegistrationAuthenticationToken(this.principal, (OidcClientRegistration) null))
.withMessage("clientRegistration cannot be null"); .withMessage("clientRegistration cannot be null");
} }
@Test @Test
public void constructorWhenClientIdNullThenThrowIllegalArgumentException() { public void constructorWhenClientIdNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcClientRegistrationAuthenticationToken(this.issuer, this.principal, (String) null)) .isThrownBy(() -> new OidcClientRegistrationAuthenticationToken(this.principal, (String) null))
.withMessage("clientId cannot be empty"); .withMessage("clientId cannot be empty");
} }
@Test @Test
public void constructorWhenClientIdEmptyThenThrowIllegalArgumentException() { public void constructorWhenClientIdEmptyThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcClientRegistrationAuthenticationToken(this.issuer, this.principal, "")) .isThrownBy(() -> new OidcClientRegistrationAuthenticationToken(this.principal, ""))
.withMessage("clientId cannot be empty"); .withMessage("clientId cannot be empty");
} }
@Test @Test
public void constructorWhenOidcClientRegistrationProvidedThenCreated() { public void constructorWhenOidcClientRegistrationProvidedThenCreated() {
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
this.issuer, this.principal, this.clientRegistration); this.principal, this.clientRegistration);
assertThat(authentication.getIssuer()).isEqualTo(this.issuer);
assertThat(authentication.getPrincipal()).isEqualTo(this.principal); assertThat(authentication.getPrincipal()).isEqualTo(this.principal);
assertThat(authentication.getCredentials().toString()).isEmpty(); assertThat(authentication.getCredentials().toString()).isEmpty();
assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
@@ -85,9 +76,8 @@ public class OidcClientRegistrationAuthenticationTokenTests {
@Test @Test
public void constructorWhenClientIdProvidedThenCreated() { public void constructorWhenClientIdProvidedThenCreated() {
OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken( OidcClientRegistrationAuthenticationToken authentication = new OidcClientRegistrationAuthenticationToken(
this.issuer, this.principal, "client-1"); this.principal, "client-1");
assertThat(authentication.getIssuer()).isEqualTo(this.issuer);
assertThat(authentication.getPrincipal()).isEqualTo(this.principal); assertThat(authentication.getPrincipal()).isEqualTo(this.principal);
assertThat(authentication.getCredentials().toString()).isEmpty(); assertThat(authentication.getCredentials().toString()).isEmpty();
assertThat(authentication.getClientRegistration()).isNull(); assertThat(authentication.getClientRegistration()).isNull();

View File

@@ -53,7 +53,6 @@ import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.TestJoseHeaders; import org.springframework.security.oauth2.jwt.TestJoseHeaders;
import org.springframework.security.oauth2.jwt.TestJwtClaimsSets; import org.springframework.security.oauth2.jwt.TestJwtClaimsSets;
import org.springframework.security.oauth2.server.authorization.oidc.authentication.OidcClientRegistrationAuthenticationToken; import org.springframework.security.oauth2.server.authorization.oidc.authentication.OidcClientRegistrationAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.web.WebAttributes;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@@ -189,7 +188,6 @@ public class OidcClientRegistrationEndpointFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri); MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri);
request.setServletPath(requestUri); request.setServletPath(requestUri);
writeClientRegistrationRequest(request, clientRegistrationRequest); writeClientRegistrationRequest(request, clientRegistrationRequest);
request.setAttribute(WebAttributes.ISSUER, "https://example.com/issuer1");
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class); FilterChain filterChain = mock(FilterChain.class);
@@ -227,13 +225,12 @@ public class OidcClientRegistrationEndpointFilterTests {
.build(); .build();
// @formatter:on // @formatter:on
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwt("client.create"); Jwt jwt = createJwt("client.create");
JwtAuthenticationToken principal = new JwtAuthenticationToken( JwtAuthenticationToken principal = new JwtAuthenticationToken(
jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create"));
OidcClientRegistrationAuthenticationToken clientRegistrationAuthenticationResult = OidcClientRegistrationAuthenticationToken clientRegistrationAuthenticationResult =
new OidcClientRegistrationAuthenticationToken(issuer, principal, expectedClientRegistrationResponse); new OidcClientRegistrationAuthenticationToken(principal, expectedClientRegistrationResponse);
when(this.authenticationManager.authenticate(any())).thenReturn(clientRegistrationAuthenticationResult); when(this.authenticationManager.authenticate(any())).thenReturn(clientRegistrationAuthenticationResult);
@@ -245,7 +242,6 @@ public class OidcClientRegistrationEndpointFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri); MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri);
request.setServletPath(requestUri); request.setServletPath(requestUri);
writeClientRegistrationRequest(request, clientRegistrationRequest); writeClientRegistrationRequest(request, clientRegistrationRequest);
request.setAttribute(WebAttributes.ISSUER, issuer);
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class); FilterChain filterChain = mock(FilterChain.class);
@@ -374,7 +370,6 @@ public class OidcClientRegistrationEndpointFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri); request.setServletPath(requestUri);
request.setParameter(OAuth2ParameterNames.CLIENT_ID, "client1"); request.setParameter(OAuth2ParameterNames.CLIENT_ID, "client1");
request.setAttribute(WebAttributes.ISSUER, "https://example.com/issuer1");
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class); FilterChain filterChain = mock(FilterChain.class);
@@ -407,13 +402,12 @@ public class OidcClientRegistrationEndpointFilterTests {
.build(); .build();
// @formatter:on // @formatter:on
String issuer = "https://example.com/issuer1";
Jwt jwt = createJwt("client.read"); Jwt jwt = createJwt("client.read");
JwtAuthenticationToken principal = new JwtAuthenticationToken( JwtAuthenticationToken principal = new JwtAuthenticationToken(
jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read"));
OidcClientRegistrationAuthenticationToken clientConfigurationAuthenticationResult = OidcClientRegistrationAuthenticationToken clientConfigurationAuthenticationResult =
new OidcClientRegistrationAuthenticationToken(issuer, principal, expectedClientRegistrationResponse); new OidcClientRegistrationAuthenticationToken(principal, expectedClientRegistrationResponse);
when(this.authenticationManager.authenticate(any())).thenReturn(clientConfigurationAuthenticationResult); when(this.authenticationManager.authenticate(any())).thenReturn(clientConfigurationAuthenticationResult);
@@ -425,7 +419,6 @@ public class OidcClientRegistrationEndpointFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri); request.setServletPath(requestUri);
request.setParameter(OAuth2ParameterNames.CLIENT_ID, expectedClientRegistrationResponse.getClientId()); request.setParameter(OAuth2ParameterNames.CLIENT_ID, expectedClientRegistrationResponse.getClientId());
request.setAttribute(WebAttributes.ISSUER, issuer);
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class); FilterChain filterChain = mock(FilterChain.class);

View File

@@ -25,7 +25,6 @@ import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings; import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.oauth2.server.authorization.web.WebAttributes;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -99,7 +98,6 @@ public class OidcProviderConfigurationEndpointFilterTests {
String requestUri = DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI; String requestUri = DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI;
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri); request.setServletPath(requestUri);
request.setAttribute(WebAttributes.ISSUER, providerSettings.getIssuer());
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class); FilterChain filterChain = mock(FilterChain.class);
@@ -132,7 +130,6 @@ public class OidcProviderConfigurationEndpointFilterTests {
String requestUri = DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI; String requestUri = DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI;
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri); request.setServletPath(requestUri);
request.setAttribute(WebAttributes.ISSUER, providerSettings.getIssuer());
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class); FilterChain filterChain = mock(FilterChain.class);

View File

@@ -146,36 +146,4 @@ public class OAuth2AuthorizationServerMetadataEndpointFilterTests {
.withMessage("issuer must be a valid URL"); .withMessage("issuer must be a valid URL");
} }
@Test
public void doFilterWhenProviderSettingsWithIssuerNotSetThenIssuerResolvesFromRequest() throws Exception {
ProviderSettings providerSettings = ProviderSettings.builder().build();
OAuth2AuthorizationServerMetadataEndpointFilter filter =
new OAuth2AuthorizationServerMetadataEndpointFilter(providerSettings);
String requestUri = DEFAULT_OAUTH2_AUTHORIZATION_SERVER_METADATA_ENDPOINT_URI;
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
filter.doFilter(request, response, filterChain);
verifyNoInteractions(filterChain);
assertThat(response.getContentType()).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
String authorizationServerMetadataResponse = response.getContentAsString();
assertThat(authorizationServerMetadataResponse).contains("\"issuer\":\"http://localhost\"");
assertThat(authorizationServerMetadataResponse).contains("\"authorization_endpoint\":\"http://localhost/oauth2/authorize\"");
assertThat(authorizationServerMetadataResponse).contains("\"token_endpoint\":\"http://localhost/oauth2/token\"");
assertThat(authorizationServerMetadataResponse).contains("\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"client_secret_post\"]");
assertThat(authorizationServerMetadataResponse).contains("\"jwks_uri\":\"http://localhost/oauth2/jwks\"");
assertThat(authorizationServerMetadataResponse).contains("\"response_types_supported\":[\"code\"]");
assertThat(authorizationServerMetadataResponse).contains("\"grant_types_supported\":[\"authorization_code\",\"client_credentials\",\"refresh_token\"]");
assertThat(authorizationServerMetadataResponse).contains("\"revocation_endpoint\":\"http://localhost/oauth2/revoke\"");
assertThat(authorizationServerMetadataResponse).contains("\"revocation_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"client_secret_post\"]");
assertThat(authorizationServerMetadataResponse).contains("\"introspection_endpoint\":\"http://localhost/oauth2/introspect\"");
assertThat(authorizationServerMetadataResponse).contains("\"introspection_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"client_secret_post\"]");
assertThat(authorizationServerMetadataResponse).contains("\"code_challenge_methods_supported\":[\"plain\",\"S256\"]");
}
} }

View File

@@ -489,13 +489,12 @@ public class OAuth2TokenEndpointFilterTests {
@Test @Test
public void doFilterWhenCustomAuthenticationConverterThenUsed() throws Exception { public void doFilterWhenCustomAuthenticationConverterThenUsed() throws Exception {
String issuer = "https://example.com/issuer1";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
Authentication clientPrincipal = new OAuth2ClientAuthenticationToken( Authentication clientPrincipal = new OAuth2ClientAuthenticationToken(
registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication =
new OAuth2AuthorizationCodeAuthenticationToken(issuer, "code", clientPrincipal, null, null); new OAuth2AuthorizationCodeAuthenticationToken("code", clientPrincipal, null, null);
AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
when(authenticationConverter.convert(any())).thenReturn(authorizationCodeAuthentication); when(authenticationConverter.convert(any())).thenReturn(authorizationCodeAuthentication);
@@ -614,8 +613,6 @@ public class OAuth2TokenEndpointFilterTests {
request.addParameter(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()); request.addParameter(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId());
request.addParameter("custom-param-1", "custom-value-1"); request.addParameter("custom-param-1", "custom-value-1");
request.setAttribute(WebAttributes.ISSUER, "https://example.com/issuer1");
return request; return request;
} }
@@ -630,8 +627,6 @@ public class OAuth2TokenEndpointFilterTests {
StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " "));
request.addParameter("custom-param-1", "custom-value-1"); request.addParameter("custom-param-1", "custom-value-1");
request.setAttribute(WebAttributes.ISSUER, "https://example.com/issuer1");
return request; return request;
} }
@@ -647,8 +642,6 @@ public class OAuth2TokenEndpointFilterTests {
StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " "));
request.addParameter("custom-param-1", "custom-value-1"); request.addParameter("custom-param-1", "custom-value-1");
request.setAttribute(WebAttributes.ISSUER, "https://example.com/issuer1");
return request; return request;
} }
} }

View File

@@ -39,6 +39,7 @@ import org.springframework.security.oauth2.server.authorization.client.InMemoryR
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ClientSettings; import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
@@ -100,6 +101,11 @@ public class AuthorizationServerConfig {
return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet); return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
} }
@Bean
public ProviderSettings providerSettings() {
return ProviderSettings.builder().issuer("http://auth-server:9000").build();
}
@Bean @Bean
public OAuth2AuthorizationConsentService authorizationConsentService() { public OAuth2AuthorizationConsentService authorizationConsentService() {
// Will be used by the ConsentController // Will be used by the ConsentController

View File

@@ -45,6 +45,7 @@ import org.springframework.security.oauth2.server.authorization.client.JdbcRegis
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.ClientSettings; import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
/** /**
@@ -104,6 +105,11 @@ public class AuthorizationServerConfig {
return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet); return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet);
} }
@Bean
public ProviderSettings providerSettings() {
return ProviderSettings.builder().issuer("http://auth-server:9000").build();
}
@Bean @Bean
public EmbeddedDatabase embeddedDatabase() { public EmbeddedDatabase embeddedDatabase() {
// @formatter:off // @formatter:off