> codeChallengeMethodsConsumer) {
- acceptClaimValues(OAuth2AuthorizationServerMetadataClaimNames.CODE_CHALLENGE_METHODS_SUPPORTED, codeChallengeMethodsConsumer);
+ acceptClaimValues(OAuth2AuthorizationServerMetadataClaimNames.CODE_CHALLENGE_METHODS_SUPPORTED,
+ codeChallengeMethodsConsumer);
return getThis();
}
/**
- * Use this claim in the resulting {@link AbstractOAuth2AuthorizationServerMetadata}.
- *
+ * Use this claim in the resulting
+ * {@link AbstractOAuth2AuthorizationServerMetadata}.
* @param name the claim name
* @param value the claim value
* @return the {@link AbstractBuilder} for further configuration
@@ -338,7 +376,6 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata implements OAuth
/**
* Provides access to every {@link #claim(String, Object)} declared so far with
* the possibility to add, replace, or remove.
- *
* @param claimsConsumer a {@code Consumer} of the claims
* @return the {@link AbstractBuilder} for further configurations
*/
@@ -349,59 +386,105 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata implements OAuth
/**
* Creates the {@link AbstractOAuth2AuthorizationServerMetadata}.
- *
* @return the {@link AbstractOAuth2AuthorizationServerMetadata}
*/
public abstract T build();
protected void validate() {
- Assert.notNull(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.ISSUER), "issuer cannot be null");
- validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.ISSUER), "issuer must be a valid URL");
- Assert.notNull(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.AUTHORIZATION_ENDPOINT), "authorizationEndpoint cannot be null");
- validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.AUTHORIZATION_ENDPOINT), "authorizationEndpoint must be a valid URL");
+ Assert.notNull(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.ISSUER),
+ "issuer cannot be null");
+ validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.ISSUER),
+ "issuer must be a valid URL");
+ Assert.notNull(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.AUTHORIZATION_ENDPOINT),
+ "authorizationEndpoint cannot be null");
+ validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.AUTHORIZATION_ENDPOINT),
+ "authorizationEndpoint must be a valid URL");
if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.DEVICE_AUTHORIZATION_ENDPOINT) != null) {
- validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.DEVICE_AUTHORIZATION_ENDPOINT), "deviceAuthorizationEndpoint must be a valid URL");
+ validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.DEVICE_AUTHORIZATION_ENDPOINT),
+ "deviceAuthorizationEndpoint must be a valid URL");
}
- Assert.notNull(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.TOKEN_ENDPOINT), "tokenEndpoint cannot be null");
- validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.TOKEN_ENDPOINT), "tokenEndpoint must be a valid URL");
- if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED) != null) {
- Assert.isInstanceOf(List.class, getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED), "tokenEndpointAuthenticationMethods must be of type List");
- Assert.notEmpty((List>) getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED), "tokenEndpointAuthenticationMethods cannot be empty");
+ Assert.notNull(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.TOKEN_ENDPOINT),
+ "tokenEndpoint cannot be null");
+ validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.TOKEN_ENDPOINT),
+ "tokenEndpoint must be a valid URL");
+ if (getClaims()
+ .get(OAuth2AuthorizationServerMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED) != null) {
+ Assert.isInstanceOf(List.class,
+ getClaims()
+ .get(OAuth2AuthorizationServerMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED),
+ "tokenEndpointAuthenticationMethods must be of type List");
+ Assert.notEmpty(
+ (List>) getClaims()
+ .get(OAuth2AuthorizationServerMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED),
+ "tokenEndpointAuthenticationMethods cannot be empty");
}
if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.JWKS_URI) != null) {
- validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.JWKS_URI), "jwksUri must be a valid URL");
+ validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.JWKS_URI),
+ "jwksUri must be a valid URL");
}
if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.SCOPES_SUPPORTED) != null) {
- Assert.isInstanceOf(List.class, getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.SCOPES_SUPPORTED), "scopes must be of type List");
- Assert.notEmpty((List>) getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.SCOPES_SUPPORTED), "scopes cannot be empty");
+ Assert.isInstanceOf(List.class,
+ getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.SCOPES_SUPPORTED),
+ "scopes must be of type List");
+ Assert.notEmpty((List>) getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.SCOPES_SUPPORTED),
+ "scopes cannot be empty");
}
- Assert.notNull(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED), "responseTypes cannot be null");
- Assert.isInstanceOf(List.class, getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED), "responseTypes must be of type List");
- Assert.notEmpty((List>) getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED), "responseTypes cannot be empty");
+ Assert.notNull(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED),
+ "responseTypes cannot be null");
+ Assert.isInstanceOf(List.class,
+ getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED),
+ "responseTypes must be of type List");
+ Assert.notEmpty(
+ (List>) getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED),
+ "responseTypes cannot be empty");
if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.GRANT_TYPES_SUPPORTED) != null) {
- Assert.isInstanceOf(List.class, getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.GRANT_TYPES_SUPPORTED), "grantTypes must be of type List");
- Assert.notEmpty((List>) getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.GRANT_TYPES_SUPPORTED), "grantTypes cannot be empty");
+ Assert.isInstanceOf(List.class,
+ getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.GRANT_TYPES_SUPPORTED),
+ "grantTypes must be of type List");
+ Assert.notEmpty(
+ (List>) getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.GRANT_TYPES_SUPPORTED),
+ "grantTypes cannot be empty");
}
if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT) != null) {
- validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT), "tokenRevocationEndpoint must be a valid URL");
+ validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT),
+ "tokenRevocationEndpoint must be a valid URL");
}
- if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT_AUTH_METHODS_SUPPORTED) != null) {
- Assert.isInstanceOf(List.class, getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT_AUTH_METHODS_SUPPORTED), "tokenRevocationEndpointAuthenticationMethods must be of type List");
- Assert.notEmpty((List>) getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT_AUTH_METHODS_SUPPORTED), "tokenRevocationEndpointAuthenticationMethods cannot be empty");
+ if (getClaims()
+ .get(OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT_AUTH_METHODS_SUPPORTED) != null) {
+ Assert.isInstanceOf(List.class,
+ getClaims().get(
+ OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT_AUTH_METHODS_SUPPORTED),
+ "tokenRevocationEndpointAuthenticationMethods must be of type List");
+ Assert.notEmpty(
+ (List>) getClaims().get(
+ OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT_AUTH_METHODS_SUPPORTED),
+ "tokenRevocationEndpointAuthenticationMethods cannot be empty");
}
if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT) != null) {
- validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT), "tokenIntrospectionEndpoint must be a valid URL");
+ validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT),
+ "tokenIntrospectionEndpoint must be a valid URL");
}
- if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED) != null) {
- Assert.isInstanceOf(List.class, getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED), "tokenIntrospectionEndpointAuthenticationMethods must be of type List");
- Assert.notEmpty((List>) getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED), "tokenIntrospectionEndpointAuthenticationMethods cannot be empty");
+ if (getClaims().get(
+ OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED) != null) {
+ Assert.isInstanceOf(List.class, getClaims()
+ .get(OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED),
+ "tokenIntrospectionEndpointAuthenticationMethods must be of type List");
+ Assert.notEmpty((List>) getClaims()
+ .get(OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED),
+ "tokenIntrospectionEndpointAuthenticationMethods cannot be empty");
}
if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.REGISTRATION_ENDPOINT) != null) {
- validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.REGISTRATION_ENDPOINT), "clientRegistrationEndpoint must be a valid URL");
+ validateURL(getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.REGISTRATION_ENDPOINT),
+ "clientRegistrationEndpoint must be a valid URL");
}
if (getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.CODE_CHALLENGE_METHODS_SUPPORTED) != null) {
- Assert.isInstanceOf(List.class, getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.CODE_CHALLENGE_METHODS_SUPPORTED), "codeChallengeMethods must be of type List");
- Assert.notEmpty((List>) getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.CODE_CHALLENGE_METHODS_SUPPORTED), "codeChallengeMethods cannot be empty");
+ Assert.isInstanceOf(List.class,
+ getClaims().get(OAuth2AuthorizationServerMetadataClaimNames.CODE_CHALLENGE_METHODS_SUPPORTED),
+ "codeChallengeMethods must be of type List");
+ Assert.notEmpty(
+ (List>) getClaims()
+ .get(OAuth2AuthorizationServerMetadataClaimNames.CODE_CHALLENGE_METHODS_SUPPORTED),
+ "codeChallengeMethods cannot be empty");
}
}
@@ -429,10 +512,12 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata implements OAuth
try {
new URI(url.toString()).toURL();
- } catch (Exception ex) {
+ }
+ catch (Exception ex) {
throw new IllegalArgumentException(errorMessage, ex);
}
}
}
+
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java
index 42bfc034..a2b351b7 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java
@@ -26,7 +26,8 @@ import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
- * An {@link OAuth2AuthorizationConsentService} that stores {@link OAuth2AuthorizationConsent}'s in-memory.
+ * An {@link OAuth2AuthorizationConsentService} that stores
+ * {@link OAuth2AuthorizationConsent}'s in-memory.
*
*
* NOTE: This implementation should ONLY be used during development/testing.
@@ -36,6 +37,7 @@ import org.springframework.util.Assert;
* @see OAuth2AuthorizationConsentService
*/
public final class InMemoryOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {
+
private final Map authorizationConsents = new ConcurrentHashMap<>();
/**
@@ -46,8 +48,8 @@ public final class InMemoryOAuth2AuthorizationConsentService implements OAuth2Au
}
/**
- * Constructs an {@code InMemoryOAuth2AuthorizationConsentService} using the provided parameters.
- *
+ * Constructs an {@code InMemoryOAuth2AuthorizationConsentService} using the provided
+ * parameters.
* @param authorizationConsents the authorization consent(s)
*/
public InMemoryOAuth2AuthorizationConsentService(OAuth2AuthorizationConsent... authorizationConsents) {
@@ -55,8 +57,8 @@ public final class InMemoryOAuth2AuthorizationConsentService implements OAuth2Au
}
/**
- * Constructs an {@code InMemoryOAuth2AuthorizationConsentService} using the provided parameters.
- *
+ * Constructs an {@code InMemoryOAuth2AuthorizationConsentService} using the provided
+ * parameters.
* @param authorizationConsents the authorization consent(s)
*/
public InMemoryOAuth2AuthorizationConsentService(List authorizationConsents) {
@@ -66,8 +68,8 @@ public final class InMemoryOAuth2AuthorizationConsentService implements OAuth2Au
int id = getId(authorizationConsent);
Assert.isTrue(!this.authorizationConsents.containsKey(id),
"The authorizationConsent must be unique. Found duplicate, with registered client id: ["
- + authorizationConsent.getRegisteredClientId()
- + "] and principal name: [" + authorizationConsent.getPrincipalName() + "]");
+ + authorizationConsent.getRegisteredClientId() + "] and principal name: ["
+ + authorizationConsent.getPrincipalName() + "]");
this.authorizationConsents.put(id, authorizationConsent);
});
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationService.java
index 20dbb0bf..e69dad95 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationService.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationService.java
@@ -33,7 +33,8 @@ import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames
import org.springframework.util.Assert;
/**
- * An {@link OAuth2AuthorizationService} that stores {@link OAuth2Authorization}'s in-memory.
+ * An {@link OAuth2AuthorizationService} that stores {@link OAuth2Authorization}'s
+ * in-memory.
*
*
* NOTE: This implementation should ONLY be used during development/testing.
@@ -44,15 +45,17 @@ import org.springframework.util.Assert;
* @see OAuth2AuthorizationService
*/
public final class InMemoryOAuth2AuthorizationService implements OAuth2AuthorizationService {
+
private int maxInitializedAuthorizations = 100;
/*
- * Stores "initialized" (uncompleted) authorizations, where an access token has not yet been granted.
- * This state occurs with the authorization_code grant flow during the user consent step OR
- * when the code is returned in the authorization response but the access token request is not yet initiated.
+ * Stores "initialized" (uncompleted) authorizations, where an access token has not
+ * yet been granted. This state occurs with the authorization_code grant flow during
+ * the user consent step OR when the code is returned in the authorization response
+ * but the access token request is not yet initiated.
*/
- private Map initializedAuthorizations =
- Collections.synchronizedMap(new MaxSizeHashMap<>(this.maxInitializedAuthorizations));
+ private Map initializedAuthorizations = Collections
+ .synchronizedMap(new MaxSizeHashMap<>(this.maxInitializedAuthorizations));
/*
* Stores "completed" authorizations, where an access token has been granted.
@@ -64,7 +67,8 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
*/
InMemoryOAuth2AuthorizationService(int maxInitializedAuthorizations) {
this.maxInitializedAuthorizations = maxInitializedAuthorizations;
- this.initializedAuthorizations = Collections.synchronizedMap(new MaxSizeHashMap<>(this.maxInitializedAuthorizations));
+ this.initializedAuthorizations = Collections
+ .synchronizedMap(new MaxSizeHashMap<>(this.maxInitializedAuthorizations));
}
/**
@@ -75,8 +79,8 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
}
/**
- * Constructs an {@code InMemoryOAuth2AuthorizationService} using the provided parameters.
- *
+ * Constructs an {@code InMemoryOAuth2AuthorizationService} using the provided
+ * parameters.
* @param authorizations the authorization(s)
*/
public InMemoryOAuth2AuthorizationService(OAuth2Authorization... authorizations) {
@@ -84,8 +88,8 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
}
/**
- * Constructs an {@code InMemoryOAuth2AuthorizationService} using the provided parameters.
- *
+ * Constructs an {@code InMemoryOAuth2AuthorizationService} using the provided
+ * parameters.
* @param authorizations the authorization(s)
*/
public InMemoryOAuth2AuthorizationService(List authorizations) {
@@ -103,7 +107,8 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
Assert.notNull(authorization, "authorization cannot be null");
if (isComplete(authorization)) {
this.authorizations.put(authorization.getId(), authorization);
- } else {
+ }
+ else {
this.initializedAuthorizations.put(authorization.getId(), authorization);
}
}
@@ -113,7 +118,8 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
Assert.notNull(authorization, "authorization cannot be null");
if (isComplete(authorization)) {
this.authorizations.remove(authorization.getId(), authorization);
- } else {
+ }
+ else {
this.initializedAuthorizations.remove(authorization.getId(), authorization);
}
}
@@ -123,9 +129,7 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
public OAuth2Authorization findById(String id) {
Assert.hasText(id, "id cannot be empty");
OAuth2Authorization authorization = this.authorizations.get(id);
- return authorization != null ?
- authorization :
- this.initializedAuthorizations.get(id);
+ return authorization != null ? authorization : this.initializedAuthorizations.get(id);
}
@Nullable
@@ -149,7 +153,8 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
return authorization.getAccessToken() != null;
}
- private static boolean hasToken(OAuth2Authorization authorization, String token, @Nullable OAuth2TokenType tokenType) {
+ private static boolean hasToken(OAuth2Authorization authorization, String token,
+ @Nullable OAuth2TokenType tokenType) {
// @formatter:off
if (tokenType == null) {
return matchesState(authorization, token) ||
@@ -183,42 +188,38 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
}
private static boolean matchesAuthorizationCode(OAuth2Authorization authorization, String token) {
- OAuth2Authorization.Token authorizationCode =
- authorization.getToken(OAuth2AuthorizationCode.class);
+ OAuth2Authorization.Token authorizationCode = authorization
+ .getToken(OAuth2AuthorizationCode.class);
return authorizationCode != null && authorizationCode.getToken().getTokenValue().equals(token);
}
private static boolean matchesAccessToken(OAuth2Authorization authorization, String token) {
- OAuth2Authorization.Token accessToken =
- authorization.getToken(OAuth2AccessToken.class);
+ OAuth2Authorization.Token accessToken = authorization.getToken(OAuth2AccessToken.class);
return accessToken != null && accessToken.getToken().getTokenValue().equals(token);
}
private static boolean matchesRefreshToken(OAuth2Authorization authorization, String token) {
- OAuth2Authorization.Token refreshToken =
- authorization.getToken(OAuth2RefreshToken.class);
+ OAuth2Authorization.Token refreshToken = authorization.getToken(OAuth2RefreshToken.class);
return refreshToken != null && refreshToken.getToken().getTokenValue().equals(token);
}
private static boolean matchesIdToken(OAuth2Authorization authorization, String token) {
- OAuth2Authorization.Token idToken =
- authorization.getToken(OidcIdToken.class);
+ OAuth2Authorization.Token idToken = authorization.getToken(OidcIdToken.class);
return idToken != null && idToken.getToken().getTokenValue().equals(token);
}
private static boolean matchesDeviceCode(OAuth2Authorization authorization, String token) {
- OAuth2Authorization.Token deviceCode =
- authorization.getToken(OAuth2DeviceCode.class);
+ OAuth2Authorization.Token deviceCode = authorization.getToken(OAuth2DeviceCode.class);
return deviceCode != null && deviceCode.getToken().getTokenValue().equals(token);
}
private static boolean matchesUserCode(OAuth2Authorization authorization, String token) {
- OAuth2Authorization.Token userCode =
- authorization.getToken(OAuth2UserCode.class);
+ OAuth2Authorization.Token userCode = authorization.getToken(OAuth2UserCode.class);
return userCode != null && userCode.getToken().getTokenValue().equals(token);
}
private static final class MaxSizeHashMap extends LinkedHashMap {
+
private final int maxSize;
private MaxSizeHashMap(int maxSize) {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentService.java
index 24ca449e..a0313360 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentService.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentService.java
@@ -43,16 +43,18 @@ import org.springframework.util.StringUtils;
* {@link JdbcOperations} for {@link OAuth2AuthorizationConsent} persistence.
*
*
- * IMPORTANT: This {@code OAuth2AuthorizationConsentService} depends on the table definition
- * described in
- * "classpath:org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql" and
- * therefore MUST be defined in the database schema.
+ * IMPORTANT: This {@code OAuth2AuthorizationConsentService} depends on the table
+ * definition described in
+ * "classpath:org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql"
+ * and therefore MUST be defined in the database schema.
*
*
- * NOTE: This {@code OAuth2AuthorizationConsentService} is a simplified JDBC implementation that MAY be used in a production environment.
- * However, it does have limitations as it likely won't perform well in an environment requiring high throughput.
- * The expectation is that the consuming application will provide their own implementation of {@code OAuth2AuthorizationConsentService}
- * that meets the performance requirements for its deployment environment.
+ * NOTE: This {@code OAuth2AuthorizationConsentService} is a simplified JDBC
+ * implementation that MAY be used in a production environment. However, it does have
+ * limitations as it likely won't perform well in an environment requiring high
+ * throughput. The expectation is that the consuming application will provide their own
+ * implementation of {@code OAuth2AuthorizationConsentService} that meets the performance
+ * requirements for its deployment environment.
*
* @author Ovidiu Popa
* @since 0.1.2
@@ -93,13 +95,15 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio
private static final String REMOVE_AUTHORIZATION_CONSENT_SQL = "DELETE FROM " + TABLE_NAME + " WHERE " + PK_FILTER;
private final JdbcOperations jdbcOperations;
+
private RowMapper authorizationConsentRowMapper;
+
private Function> authorizationConsentParametersMapper;
/**
- * Constructs a {@code JdbcOAuth2AuthorizationConsentService} using the provided parameters.
- *
- * @param jdbcOperations the JDBC operations
+ * Constructs a {@code JdbcOAuth2AuthorizationConsentService} using the provided
+ * parameters.
+ * @param jdbcOperations the JDBC operations
* @param registeredClientRepository the registered client repository
*/
public JdbcOAuth2AuthorizationConsentService(JdbcOperations jdbcOperations,
@@ -114,11 +118,12 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio
@Override
public void save(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
- OAuth2AuthorizationConsent existingAuthorizationConsent = findById(
- authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName());
+ OAuth2AuthorizationConsent existingAuthorizationConsent = findById(authorizationConsent.getRegisteredClientId(),
+ authorizationConsent.getPrincipalName());
if (existingAuthorizationConsent == null) {
insertAuthorizationConsent(authorizationConsent);
- } else {
+ }
+ else {
updateAuthorizationConsent(authorizationConsent);
}
}
@@ -144,8 +149,7 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
SqlParameterValue[] parameters = new SqlParameterValue[] {
new SqlParameterValue(Types.VARCHAR, authorizationConsent.getRegisteredClientId()),
- new SqlParameterValue(Types.VARCHAR, authorizationConsent.getPrincipalName())
- };
+ new SqlParameterValue(Types.VARCHAR, authorizationConsent.getPrincipalName()) };
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters);
this.jdbcOperations.update(REMOVE_AUTHORIZATION_CONSENT_SQL, pss);
}
@@ -157,7 +161,7 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio
Assert.hasText(principalName, "principalName cannot be empty");
SqlParameterValue[] parameters = new SqlParameterValue[] {
new SqlParameterValue(Types.VARCHAR, registeredClientId),
- new SqlParameterValue(Types.VARCHAR, principalName)};
+ new SqlParameterValue(Types.VARCHAR, principalName) };
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters);
List result = this.jdbcOperations.query(LOAD_AUTHORIZATION_CONSENT_SQL, pss,
this.authorizationConsentRowMapper);
@@ -168,22 +172,21 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio
* Sets the {@link RowMapper} used for mapping the current row in
* {@code java.sql.ResultSet} to {@link OAuth2AuthorizationConsent}. The default is
* {@link OAuth2AuthorizationConsentRowMapper}.
- *
- * @param authorizationConsentRowMapper the {@link RowMapper} used for mapping the current
- * row in {@code ResultSet} to {@link OAuth2AuthorizationConsent}
+ * @param authorizationConsentRowMapper the {@link RowMapper} used for mapping the
+ * current row in {@code ResultSet} to {@link OAuth2AuthorizationConsent}
*/
- public final void setAuthorizationConsentRowMapper(RowMapper authorizationConsentRowMapper) {
+ public final void setAuthorizationConsentRowMapper(
+ RowMapper authorizationConsentRowMapper) {
Assert.notNull(authorizationConsentRowMapper, "authorizationConsentRowMapper cannot be null");
this.authorizationConsentRowMapper = authorizationConsentRowMapper;
}
/**
- * Sets the {@code Function} used for mapping {@link OAuth2AuthorizationConsent} to
- * a {@code List} of {@link SqlParameterValue}. The default is
+ * Sets the {@code Function} used for mapping {@link OAuth2AuthorizationConsent} to a
+ * {@code List} of {@link SqlParameterValue}. The default is
* {@link OAuth2AuthorizationConsentParametersMapper}.
- *
* @param authorizationConsentParametersMapper the {@code Function} used for mapping
- * {@link OAuth2AuthorizationConsent} to a {@code List} of {@link SqlParameterValue}
+ * {@link OAuth2AuthorizationConsent} to a {@code List} of {@link SqlParameterValue}
*/
public final void setAuthorizationConsentParametersMapper(
Function> authorizationConsentParametersMapper) {
@@ -204,10 +207,11 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio
}
/**
- * The default {@link RowMapper} that maps the current row in
- * {@code ResultSet} to {@link OAuth2AuthorizationConsent}.
+ * The default {@link RowMapper} that maps the current row in {@code ResultSet} to
+ * {@link OAuth2AuthorizationConsent}.
*/
public static class OAuth2AuthorizationConsentRowMapper implements RowMapper {
+
private final RegisteredClientRepository registeredClientRepository;
public OAuth2AuthorizationConsentRowMapper(RegisteredClientRepository registeredClientRepository) {
@@ -220,13 +224,14 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio
String registeredClientId = rs.getString("registered_client_id");
RegisteredClient registeredClient = this.registeredClientRepository.findById(registeredClientId);
if (registeredClient == null) {
- throw new DataRetrievalFailureException(
- "The RegisteredClient with id '" + registeredClientId + "' was not found in the RegisteredClientRepository.");
+ throw new DataRetrievalFailureException("The RegisteredClient with id '" + registeredClientId
+ + "' was not found in the RegisteredClientRepository.");
}
String principalName = rs.getString("principal_name");
- OAuth2AuthorizationConsent.Builder builder = OAuth2AuthorizationConsent.withId(registeredClientId, principalName);
+ OAuth2AuthorizationConsent.Builder builder = OAuth2AuthorizationConsent.withId(registeredClientId,
+ principalName);
String authorizationConsentAuthorities = rs.getString("authorities");
if (authorizationConsentAuthorities != null) {
for (String authority : StringUtils.commaDelimitedListToSet(authorizationConsentAuthorities)) {
@@ -246,7 +251,8 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio
* The default {@code Function} that maps {@link OAuth2AuthorizationConsent} to a
* {@code List} of {@link SqlParameterValue}.
*/
- public static class OAuth2AuthorizationConsentParametersMapper implements Function> {
+ public static class OAuth2AuthorizationConsentParametersMapper
+ implements Function> {
@Override
public List apply(OAuth2AuthorizationConsent authorizationConsent) {
@@ -258,7 +264,8 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio
for (GrantedAuthority authority : authorizationConsent.getAuthorities()) {
authorities.add(authority.getAuthority());
}
- parameters.add(new SqlParameterValue(Types.VARCHAR, StringUtils.collectionToDelimitedString(authorities, ",")));
+ parameters
+ .add(new SqlParameterValue(Types.VARCHAR, StringUtils.collectionToDelimitedString(authorities, ",")));
return parameters;
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java
index 96e08966..9bbbb912 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java
@@ -68,16 +68,18 @@ import org.springframework.util.StringUtils;
* {@link JdbcOperations} for {@link OAuth2Authorization} persistence.
*
*
- * IMPORTANT: This {@code OAuth2AuthorizationService} depends on the table definition
- * described in
- * "classpath:org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql" and
- * therefore MUST be defined in the database schema.
+ * IMPORTANT: This {@code OAuth2AuthorizationService} depends on the table
+ * definition described in
+ * "classpath:org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql"
+ * and therefore MUST be defined in the database schema.
*
*
- * NOTE: This {@code OAuth2AuthorizationService} is a simplified JDBC implementation that MAY be used in a production environment.
- * However, it does have limitations as it likely won't perform well in an environment requiring high throughput.
- * The expectation is that the consuming application will provide their own implementation of {@code OAuth2AuthorizationService}
- * that meets the performance requirements for its deployment environment.
+ * NOTE: This {@code OAuth2AuthorizationService} is a simplified JDBC
+ * implementation that MAY be used in a production environment. However, it does have
+ * limitations as it likely won't perform well in an environment requiring high
+ * throughput. The expectation is that the consuming application will provide their own
+ * implementation of {@code OAuth2AuthorizationService} that meets the performance
+ * requirements for its deployment environment.
*
* @author Ovidiu Popa
* @author Joe Grandja
@@ -128,16 +130,23 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
private static final String TABLE_NAME = "oauth2_authorization";
private static final String PK_FILTER = "id = ?";
+
private static final String UNKNOWN_TOKEN_TYPE_FILTER = "state = ? OR authorization_code_value = ? OR "
+ "access_token_value = ? OR oidc_id_token_value = ? OR refresh_token_value = ? OR user_code_value = ? OR "
+ "device_code_value = ?";
private static final String STATE_FILTER = "state = ?";
+
private static final String AUTHORIZATION_CODE_FILTER = "authorization_code_value = ?";
+
private static final String ACCESS_TOKEN_FILTER = "access_token_value = ?";
+
private static final String ID_TOKEN_FILTER = "oidc_id_token_value = ?";
+
private static final String REFRESH_TOKEN_FILTER = "refresh_token_value = ?";
+
private static final String USER_CODE_FILTER = "user_code_value = ?";
+
private static final String DEVICE_CODE_FILTER = "device_code_value = ?";
// @formatter:off
@@ -168,14 +177,16 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
private static Map columnMetadataMap;
private final JdbcOperations jdbcOperations;
+
private final LobHandler lobHandler;
+
private RowMapper authorizationRowMapper;
+
private Function> authorizationParametersMapper;
/**
* Constructs a {@code JdbcOAuth2AuthorizationService} using the provided parameters.
- *
- * @param jdbcOperations the JDBC operations
+ * @param jdbcOperations the JDBC operations
* @param registeredClientRepository the registered client repository
*/
public JdbcOAuth2AuthorizationService(JdbcOperations jdbcOperations,
@@ -185,10 +196,9 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
/**
* Constructs a {@code JdbcOAuth2AuthorizationService} using the provided parameters.
- *
- * @param jdbcOperations the JDBC operations
+ * @param jdbcOperations the JDBC operations
* @param registeredClientRepository the registered client repository
- * @param lobHandler the handler for large binary fields and large text fields
+ * @param lobHandler the handler for large binary fields and large text fields
*/
public JdbcOAuth2AuthorizationService(JdbcOperations jdbcOperations,
RegisteredClientRepository registeredClientRepository, LobHandler lobHandler) {
@@ -197,7 +207,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
Assert.notNull(lobHandler, "lobHandler cannot be null");
this.jdbcOperations = jdbcOperations;
this.lobHandler = lobHandler;
- OAuth2AuthorizationRowMapper authorizationRowMapper = new OAuth2AuthorizationRowMapper(registeredClientRepository);
+ OAuth2AuthorizationRowMapper authorizationRowMapper = new OAuth2AuthorizationRowMapper(
+ registeredClientRepository);
authorizationRowMapper.setLobHandler(lobHandler);
this.authorizationRowMapper = authorizationRowMapper;
this.authorizationParametersMapper = new OAuth2AuthorizationParametersMapper();
@@ -210,7 +221,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
OAuth2Authorization existingAuthorization = findById(authorization.getId());
if (existingAuthorization == null) {
insertAuthorization(authorization);
- } else {
+ }
+ else {
updateAuthorization(authorization);
}
}
@@ -239,8 +251,7 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
public void remove(OAuth2Authorization authorization) {
Assert.notNull(authorization, "authorization cannot be null");
SqlParameterValue[] parameters = new SqlParameterValue[] {
- new SqlParameterValue(Types.VARCHAR, authorization.getId())
- };
+ new SqlParameterValue(Types.VARCHAR, authorization.getId()) };
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters);
this.jdbcOperations.update(REMOVE_AUTHORIZATION_SQL, pss);
}
@@ -268,25 +279,32 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
parameters.add(mapToSqlParameter("user_code_value", token));
parameters.add(mapToSqlParameter("device_code_value", token));
return findBy(UNKNOWN_TOKEN_TYPE_FILTER, parameters);
- } else if (OAuth2ParameterNames.STATE.equals(tokenType.getValue())) {
+ }
+ else if (OAuth2ParameterNames.STATE.equals(tokenType.getValue())) {
parameters.add(new SqlParameterValue(Types.VARCHAR, token));
return findBy(STATE_FILTER, parameters);
- } else if (OAuth2ParameterNames.CODE.equals(tokenType.getValue())) {
+ }
+ else if (OAuth2ParameterNames.CODE.equals(tokenType.getValue())) {
parameters.add(mapToSqlParameter("authorization_code_value", token));
return findBy(AUTHORIZATION_CODE_FILTER, parameters);
- } else if (OAuth2TokenType.ACCESS_TOKEN.equals(tokenType)) {
+ }
+ else if (OAuth2TokenType.ACCESS_TOKEN.equals(tokenType)) {
parameters.add(mapToSqlParameter("access_token_value", token));
return findBy(ACCESS_TOKEN_FILTER, parameters);
- } else if (OidcParameterNames.ID_TOKEN.equals(tokenType.getValue())) {
+ }
+ else if (OidcParameterNames.ID_TOKEN.equals(tokenType.getValue())) {
parameters.add(mapToSqlParameter("oidc_id_token_value", token));
return findBy(ID_TOKEN_FILTER, parameters);
- } else if (OAuth2TokenType.REFRESH_TOKEN.equals(tokenType)) {
+ }
+ else if (OAuth2TokenType.REFRESH_TOKEN.equals(tokenType)) {
parameters.add(mapToSqlParameter("refresh_token_value", token));
return findBy(REFRESH_TOKEN_FILTER, parameters);
- } else if (OAuth2ParameterNames.USER_CODE.equals(tokenType.getValue())) {
+ }
+ else if (OAuth2ParameterNames.USER_CODE.equals(tokenType.getValue())) {
parameters.add(mapToSqlParameter("user_code_value", token));
return findBy(USER_CODE_FILTER, parameters);
- } else if (OAuth2ParameterNames.DEVICE_CODE.equals(tokenType.getValue())) {
+ }
+ else if (OAuth2ParameterNames.DEVICE_CODE.equals(tokenType.getValue())) {
parameters.add(mapToSqlParameter("device_code_value", token));
return findBy(DEVICE_CODE_FILTER, parameters);
}
@@ -297,7 +315,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
try (LobCreator lobCreator = getLobHandler().getLobCreator()) {
PreparedStatementSetter pss = new LobCreatorArgumentPreparedStatementSetter(lobCreator,
parameters.toArray());
- List result = getJdbcOperations().query(LOAD_AUTHORIZATION_SQL + filter, pss, getAuthorizationRowMapper());
+ List result = getJdbcOperations().query(LOAD_AUTHORIZATION_SQL + filter, pss,
+ getAuthorizationRowMapper());
return !result.isEmpty() ? result.get(0) : null;
}
}
@@ -306,9 +325,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
* Sets the {@link RowMapper} used for mapping the current row in
* {@code java.sql.ResultSet} to {@link OAuth2Authorization}. The default is
* {@link OAuth2AuthorizationRowMapper}.
- *
* @param authorizationRowMapper the {@link RowMapper} used for mapping the current
- * row in {@code ResultSet} to {@link OAuth2Authorization}
+ * row in {@code ResultSet} to {@link OAuth2Authorization}
*/
public final void setAuthorizationRowMapper(RowMapper authorizationRowMapper) {
Assert.notNull(authorizationRowMapper, "authorizationRowMapper cannot be null");
@@ -316,12 +334,11 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
}
/**
- * Sets the {@code Function} used for mapping {@link OAuth2Authorization} to
- * a {@code List} of {@link SqlParameterValue}. The default is
+ * Sets the {@code Function} used for mapping {@link OAuth2Authorization} to a
+ * {@code List} of {@link SqlParameterValue}. The default is
* {@link OAuth2AuthorizationParametersMapper}.
- *
* @param authorizationParametersMapper the {@code Function} used for mapping
- * {@link OAuth2Authorization} to a {@code List} of {@link SqlParameterValue}
+ * {@link OAuth2Authorization} to a {@code List} of {@link SqlParameterValue}
*/
public final void setAuthorizationParametersMapper(
Function> authorizationParametersMapper) {
@@ -350,8 +367,11 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
* {@code java.sql.ResultSet} to {@link OAuth2Authorization}.
*/
public static class OAuth2AuthorizationRowMapper implements RowMapper {
+
private final RegisteredClientRepository registeredClientRepository;
+
private LobHandler lobHandler = new DefaultLobHandler();
+
private ObjectMapper objectMapper = new ObjectMapper();
public OAuth2AuthorizationRowMapper(RegisteredClientRepository registeredClientRepository) {
@@ -370,8 +390,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
String registeredClientId = rs.getString("registered_client_id");
RegisteredClient registeredClient = this.registeredClientRepository.findById(registeredClientId);
if (registeredClient == null) {
- throw new DataRetrievalFailureException(
- "The RegisteredClient with id '" + registeredClientId + "' was not found in the RegisteredClientRepository.");
+ throw new DataRetrievalFailureException("The RegisteredClient with id '" + registeredClientId
+ + "' was not found in the RegisteredClientRepository.");
}
OAuth2Authorization.Builder builder = OAuth2Authorization.withRegisteredClient(registeredClient);
@@ -386,10 +406,10 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
Map attributes = parseMap(getLobValue(rs, "attributes"));
builder.id(id)
- .principalName(principalName)
- .authorizationGrantType(new AuthorizationGrantType(authorizationGrantType))
- .authorizedScopes(authorizedScopes)
- .attributes((attrs) -> attrs.putAll(attributes));
+ .principalName(principalName)
+ .authorizationGrantType(new AuthorizationGrantType(authorizationGrantType))
+ .authorizedScopes(authorizedScopes)
+ .attributes((attrs) -> attrs.putAll(attributes));
String state = rs.getString("state");
if (StringUtils.hasText(state)) {
@@ -403,10 +423,11 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
if (StringUtils.hasText(authorizationCodeValue)) {
tokenIssuedAt = rs.getTimestamp("authorization_code_issued_at").toInstant();
tokenExpiresAt = rs.getTimestamp("authorization_code_expires_at").toInstant();
- Map authorizationCodeMetadata = parseMap(getLobValue(rs, "authorization_code_metadata"));
+ Map authorizationCodeMetadata = parseMap(
+ getLobValue(rs, "authorization_code_metadata"));
- OAuth2AuthorizationCode authorizationCode = new OAuth2AuthorizationCode(
- authorizationCodeValue, tokenIssuedAt, tokenExpiresAt);
+ OAuth2AuthorizationCode authorizationCode = new OAuth2AuthorizationCode(authorizationCodeValue,
+ tokenIssuedAt, tokenExpiresAt);
builder.token(authorizationCode, (metadata) -> metadata.putAll(authorizationCodeMetadata));
}
@@ -425,7 +446,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
if (accessTokenScopes != null) {
scopes = StringUtils.commaDelimitedListToSet(accessTokenScopes);
}
- OAuth2AccessToken accessToken = new OAuth2AccessToken(tokenType, accessTokenValue, tokenIssuedAt, tokenExpiresAt, scopes);
+ OAuth2AccessToken accessToken = new OAuth2AccessToken(tokenType, accessTokenValue, tokenIssuedAt,
+ tokenExpiresAt, scopes);
builder.token(accessToken, (metadata) -> metadata.putAll(accessTokenMetadata));
}
@@ -435,8 +457,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
tokenExpiresAt = rs.getTimestamp("oidc_id_token_expires_at").toInstant();
Map oidcTokenMetadata = parseMap(getLobValue(rs, "oidc_id_token_metadata"));
- OidcIdToken oidcToken = new OidcIdToken(
- oidcIdTokenValue, tokenIssuedAt, tokenExpiresAt, (Map) oidcTokenMetadata.get(OAuth2Authorization.Token.CLAIMS_METADATA_NAME));
+ OidcIdToken oidcToken = new OidcIdToken(oidcIdTokenValue, tokenIssuedAt, tokenExpiresAt,
+ (Map) oidcTokenMetadata.get(OAuth2Authorization.Token.CLAIMS_METADATA_NAME));
builder.token(oidcToken, (metadata) -> metadata.putAll(oidcTokenMetadata));
}
@@ -450,8 +472,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
}
Map refreshTokenMetadata = parseMap(getLobValue(rs, "refresh_token_metadata"));
- OAuth2RefreshToken refreshToken = new OAuth2RefreshToken(
- refreshTokenValue, tokenIssuedAt, tokenExpiresAt);
+ OAuth2RefreshToken refreshToken = new OAuth2RefreshToken(refreshTokenValue, tokenIssuedAt,
+ tokenExpiresAt);
builder.token(refreshToken, (metadata) -> metadata.putAll(refreshTokenMetadata));
}
@@ -486,9 +508,11 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
if (columnValueBytes != null) {
columnValue = new String(columnValueBytes, StandardCharsets.UTF_8);
}
- } else if (Types.CLOB == columnMetadata.getDataType()) {
+ }
+ else if (Types.CLOB == columnMetadata.getDataType()) {
columnValue = this.lobHandler.getClobAsString(rs, columnName);
- } else {
+ }
+ else {
columnValue = rs.getString(columnName);
}
return columnValue;
@@ -518,8 +542,10 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
private Map parseMap(String data) {
try {
- return this.objectMapper.readValue(data, new TypeReference>() {});
- } catch (Exception ex) {
+ return this.objectMapper.readValue(data, new TypeReference>() {
+ });
+ }
+ catch (Exception ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
}
@@ -530,7 +556,9 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
* The default {@code Function} that maps {@link OAuth2Authorization} to a
* {@code List} of {@link SqlParameterValue}.
*/
- public static class OAuth2AuthorizationParametersMapper implements Function> {
+ public static class OAuth2AuthorizationParametersMapper
+ implements Function> {
+
private ObjectMapper objectMapper = new ObjectMapper();
public OAuth2AuthorizationParametersMapper() {
@@ -564,46 +592,46 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
}
parameters.add(new SqlParameterValue(Types.VARCHAR, state));
- OAuth2Authorization.Token authorizationCode =
- authorization.getToken(OAuth2AuthorizationCode.class);
- List authorizationCodeSqlParameters = toSqlParameterList(
- "authorization_code_value", "authorization_code_metadata", authorizationCode);
+ OAuth2Authorization.Token authorizationCode = authorization
+ .getToken(OAuth2AuthorizationCode.class);
+ List authorizationCodeSqlParameters = toSqlParameterList("authorization_code_value",
+ "authorization_code_metadata", authorizationCode);
parameters.addAll(authorizationCodeSqlParameters);
- OAuth2Authorization.Token accessToken =
- authorization.getToken(OAuth2AccessToken.class);
- List accessTokenSqlParameters = toSqlParameterList(
- "access_token_value", "access_token_metadata", accessToken);
+ OAuth2Authorization.Token accessToken = authorization.getToken(OAuth2AccessToken.class);
+ List accessTokenSqlParameters = toSqlParameterList("access_token_value",
+ "access_token_metadata", accessToken);
parameters.addAll(accessTokenSqlParameters);
String accessTokenType = null;
String accessTokenScopes = null;
if (accessToken != null) {
accessTokenType = accessToken.getToken().getTokenType().getValue();
if (!CollectionUtils.isEmpty(accessToken.getToken().getScopes())) {
- accessTokenScopes = StringUtils.collectionToDelimitedString(accessToken.getToken().getScopes(), ",");
+ accessTokenScopes = StringUtils.collectionToDelimitedString(accessToken.getToken().getScopes(),
+ ",");
}
}
parameters.add(new SqlParameterValue(Types.VARCHAR, accessTokenType));
parameters.add(new SqlParameterValue(Types.VARCHAR, accessTokenScopes));
OAuth2Authorization.Token oidcIdToken = authorization.getToken(OidcIdToken.class);
- List oidcIdTokenSqlParameters = toSqlParameterList(
- "oidc_id_token_value", "oidc_id_token_metadata", oidcIdToken);
+ List oidcIdTokenSqlParameters = toSqlParameterList("oidc_id_token_value",
+ "oidc_id_token_metadata", oidcIdToken);
parameters.addAll(oidcIdTokenSqlParameters);
OAuth2Authorization.Token refreshToken = authorization.getRefreshToken();
- List refreshTokenSqlParameters = toSqlParameterList(
- "refresh_token_value", "refresh_token_metadata", refreshToken);
+ List refreshTokenSqlParameters = toSqlParameterList("refresh_token_value",
+ "refresh_token_metadata", refreshToken);
parameters.addAll(refreshTokenSqlParameters);
OAuth2Authorization.Token userCode = authorization.getToken(OAuth2UserCode.class);
- List userCodeSqlParameters = toSqlParameterList(
- "user_code_value", "user_code_metadata", userCode);
+ List userCodeSqlParameters = toSqlParameterList("user_code_value", "user_code_metadata",
+ userCode);
parameters.addAll(userCodeSqlParameters);
OAuth2Authorization.Token deviceCode = authorization.getToken(OAuth2DeviceCode.class);
- List deviceCodeSqlParameters = toSqlParameterList(
- "device_code_value", "device_code_metadata", deviceCode);
+ List deviceCodeSqlParameters = toSqlParameterList("device_code_value",
+ "device_code_metadata", deviceCode);
parameters.addAll(deviceCodeSqlParameters);
return parameters;
@@ -618,8 +646,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
return this.objectMapper;
}
- private List toSqlParameterList(
- String tokenColumnName, String tokenMetadataColumnName, OAuth2Authorization.Token token) {
+ private List toSqlParameterList(String tokenColumnName,
+ String tokenMetadataColumnName, OAuth2Authorization.Token token) {
List parameters = new ArrayList<>();
String tokenValue = null;
@@ -647,7 +675,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
private String writeMap(Map data) {
try {
return this.objectMapper.writeValueAsString(data);
- } catch (Exception ex) {
+ }
+ catch (Exception ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
}
@@ -655,6 +684,7 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
}
private static final class LobCreatorArgumentPreparedStatementSetter extends ArgumentPreparedStatementSetter {
+
private final LobCreator lobCreator;
private LobCreatorArgumentPreparedStatementSetter(LobCreator lobCreator, Object[] args) {
@@ -691,7 +721,9 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
}
private static final class ColumnMetadata {
+
private final String columnName;
+
private final int dataType;
private ColumnMetadata(String columnName, int dataType) {
@@ -741,7 +773,8 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
}
- private static ColumnMetadata getColumnMetadata(JdbcOperations jdbcOperations, String columnName, int defaultDataType) {
+ private static ColumnMetadata getColumnMetadata(JdbcOperations jdbcOperations, String columnName,
+ int defaultDataType) {
Integer dataType = jdbcOperations.execute((ConnectionCallback) conn -> {
DatabaseMetaData databaseMetaData = conn.getMetaData();
ResultSet rs = databaseMetaData.getColumns(null, null, TABLE_NAME, columnName);
@@ -749,10 +782,13 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
return rs.getInt("DATA_TYPE");
}
// NOTE: (Applies to HSQL)
- // When a database object is created with one of the CREATE statements or renamed with the ALTER statement,
- // if the name is enclosed in double quotes, the exact name is used as the case-normal form.
+ // When a database object is created with one of the CREATE statements or
+ // renamed with the ALTER statement,
+ // if the name is enclosed in double quotes, the exact name is used as the
+ // case-normal form.
// But if it is not enclosed in double quotes,
- // the name is converted to uppercase and this uppercase version is stored in the database as the case-normal form.
+ // the name is converted to uppercase and this uppercase version is stored in
+ // the database as the case-normal form.
rs = databaseMetaData.getColumns(null, null, TABLE_NAME.toUpperCase(), columnName.toUpperCase());
if (rs.next()) {
return rs.getInt("DATA_TYPE");
@@ -764,9 +800,9 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
private static SqlParameterValue mapToSqlParameter(String columnName, String value) {
ColumnMetadata columnMetadata = columnMetadataMap.get(columnName);
- return Types.BLOB == columnMetadata.getDataType() && StringUtils.hasText(value) ?
- new SqlParameterValue(Types.BLOB, value.getBytes(StandardCharsets.UTF_8)) :
- new SqlParameterValue(columnMetadata.getDataType(), value);
+ return Types.BLOB == columnMetadata.getDataType() && StringUtils.hasText(value)
+ ? new SqlParameterValue(Types.BLOB, value.getBytes(StandardCharsets.UTF_8))
+ : new SqlParameterValue(columnMetadata.getDataType(), value);
}
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2Authorization.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2Authorization.java
index ef8bb69d..d40399cc 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2Authorization.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2Authorization.java
@@ -38,9 +38,10 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
- * A representation of an OAuth 2.0 Authorization, which holds state related to the authorization granted
- * to a {@link #getRegisteredClientId() client}, by the {@link #getPrincipalName() resource owner}
- * or itself in the case of the {@code client_credentials} grant type.
+ * A representation of an OAuth 2.0 Authorization, which holds state related to the
+ * authorization granted to a {@link #getRegisteredClientId() client}, by the
+ * {@link #getPrincipalName() resource owner} or itself in the case of the
+ * {@code client_credentials} grant type.
*
* @author Joe Grandja
* @author Krisztian Toth
@@ -52,13 +53,21 @@ import org.springframework.util.StringUtils;
* @see OAuth2RefreshToken
*/
public class OAuth2Authorization implements Serializable {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private String id;
+
private String registeredClientId;
+
private String principalName;
+
private AuthorizationGrantType authorizationGrantType;
+
private Set authorizedScopes;
+
private Map, Token>> tokens;
+
private Map attributes;
protected OAuth2Authorization() {
@@ -66,7 +75,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the identifier for the authorization.
- *
* @return the identifier for the authorization
*/
public String getId() {
@@ -75,7 +83,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the identifier for the {@link RegisteredClient#getId() registered client}.
- *
* @return the {@link RegisteredClient#getId()}
*/
public String getRegisteredClientId() {
@@ -84,7 +91,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the {@code Principal} name of the resource owner (or client).
- *
* @return the {@code Principal} name of the resource owner (or client)
*/
public String getPrincipalName() {
@@ -92,8 +98,8 @@ public class OAuth2Authorization implements Serializable {
}
/**
- * Returns the {@link AuthorizationGrantType authorization grant type} used for the authorization.
- *
+ * Returns the {@link AuthorizationGrantType authorization grant type} used for the
+ * authorization.
* @return the {@link AuthorizationGrantType} used for the authorization
*/
public AuthorizationGrantType getAuthorizationGrantType() {
@@ -102,7 +108,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the authorized scope(s).
- *
* @return the {@code Set} of authorized scope(s)
* @since 0.4.0
*/
@@ -112,7 +117,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the {@link Token} of type {@link OAuth2AccessToken}.
- *
* @return the {@link Token} of type {@link OAuth2AccessToken}
*/
public Token getAccessToken() {
@@ -121,8 +125,8 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the {@link Token} of type {@link OAuth2RefreshToken}.
- *
- * @return the {@link Token} of type {@link OAuth2RefreshToken}, or {@code null} if not available
+ * @return the {@link Token} of type {@link OAuth2RefreshToken}, or {@code null} if
+ * not available
*/
@Nullable
public Token getRefreshToken() {
@@ -131,7 +135,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the {@link Token} of type {@code tokenType}.
- *
* @param tokenType the token type
* @param the type of the token
* @return the {@link Token}, or {@code null} if not available
@@ -146,7 +149,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the {@link Token} matching the {@code tokenValue}.
- *
* @param tokenValue the token value
* @param the type of the token
* @return the {@link Token}, or {@code null} if not available
@@ -165,7 +167,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the attribute(s) associated to the authorization.
- *
* @return a {@code Map} of the attribute(s)
*/
public Map getAttributes() {
@@ -174,10 +175,10 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the value of an attribute associated to the authorization.
- *
* @param name the name of the attribute
* @param the type of the attribute
- * @return the value of an attribute associated to the authorization, or {@code null} if not available
+ * @return the value of an attribute associated to the authorization, or {@code null}
+ * if not available
*/
@Nullable
@SuppressWarnings("unchecked")
@@ -195,24 +196,22 @@ public class OAuth2Authorization implements Serializable {
return false;
}
OAuth2Authorization that = (OAuth2Authorization) obj;
- return Objects.equals(this.id, that.id) &&
- Objects.equals(this.registeredClientId, that.registeredClientId) &&
- Objects.equals(this.principalName, that.principalName) &&
- Objects.equals(this.authorizationGrantType, that.authorizationGrantType) &&
- Objects.equals(this.authorizedScopes, that.authorizedScopes) &&
- Objects.equals(this.tokens, that.tokens) &&
- Objects.equals(this.attributes, that.attributes);
+ return Objects.equals(this.id, that.id) && Objects.equals(this.registeredClientId, that.registeredClientId)
+ && Objects.equals(this.principalName, that.principalName)
+ && Objects.equals(this.authorizationGrantType, that.authorizationGrantType)
+ && Objects.equals(this.authorizedScopes, that.authorizedScopes)
+ && Objects.equals(this.tokens, that.tokens) && Objects.equals(this.attributes, that.attributes);
}
@Override
public int hashCode() {
- return Objects.hash(this.id, this.registeredClientId, this.principalName,
- this.authorizationGrantType, this.authorizedScopes, this.tokens, this.attributes);
+ return Objects.hash(this.id, this.registeredClientId, this.principalName, this.authorizationGrantType,
+ this.authorizedScopes, this.tokens, this.attributes);
}
/**
- * Returns a new {@link Builder}, initialized with the provided {@link RegisteredClient#getId()}.
- *
+ * Returns a new {@link Builder}, initialized with the provided
+ * {@link RegisteredClient#getId()}.
* @param registeredClient the {@link RegisteredClient}
* @return the {@link Builder}
*/
@@ -222,20 +221,20 @@ public class OAuth2Authorization implements Serializable {
}
/**
- * Returns a new {@link Builder}, initialized with the values from the provided {@code OAuth2Authorization}.
- *
- * @param authorization the {@code OAuth2Authorization} used for initializing the {@link Builder}
+ * Returns a new {@link Builder}, initialized with the values from the provided
+ * {@code OAuth2Authorization}.
+ * @param authorization the {@code OAuth2Authorization} used for initializing the
+ * {@link Builder}
* @return the {@link Builder}
*/
public static Builder from(OAuth2Authorization authorization) {
Assert.notNull(authorization, "authorization cannot be null");
- return new Builder(authorization.getRegisteredClientId())
- .id(authorization.getId())
- .principalName(authorization.getPrincipalName())
- .authorizationGrantType(authorization.getAuthorizationGrantType())
- .authorizedScopes(authorization.getAuthorizedScopes())
- .tokens(authorization.tokens)
- .attributes(attrs -> attrs.putAll(authorization.getAttributes()));
+ return new Builder(authorization.getRegisteredClientId()).id(authorization.getId())
+ .principalName(authorization.getPrincipalName())
+ .authorizationGrantType(authorization.getAuthorizationGrantType())
+ .authorizedScopes(authorization.getAuthorizedScopes())
+ .tokens(authorization.tokens)
+ .attributes(attrs -> attrs.putAll(authorization.getAttributes()));
}
/**
@@ -245,7 +244,9 @@ public class OAuth2Authorization implements Serializable {
* @since 0.1.0
*/
public static class Token implements Serializable {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
protected static final String TOKEN_METADATA_NAMESPACE = "metadata.token.";
/**
@@ -259,6 +260,7 @@ public class OAuth2Authorization implements Serializable {
public static final String CLAIMS_METADATA_NAME = TOKEN_METADATA_NAMESPACE.concat("claims");
private final T token;
+
private final Map metadata;
protected Token(T token) {
@@ -272,7 +274,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the token of type {@link OAuth2Token}.
- *
* @return the token of type {@link OAuth2Token}
*/
public T getToken() {
@@ -280,9 +281,8 @@ public class OAuth2Authorization implements Serializable {
}
/**
- * Returns {@code true} if the token has been invalidated (e.g. revoked).
- * The default is {@code false}.
- *
+ * Returns {@code true} if the token has been invalidated (e.g. revoked). The
+ * default is {@code false}.
* @return {@code true} if the token has been invalidated, {@code false} otherwise
*/
public boolean isInvalidated() {
@@ -291,7 +291,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns {@code true} if the token has expired.
- *
* @return {@code true} if the token has expired, {@code false} otherwise
*/
public boolean isExpired() {
@@ -300,8 +299,8 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns {@code true} if the token is before the time it can be used.
- *
- * @return {@code true} if the token is before the time it can be used, {@code false} otherwise
+ * @return {@code true} if the token is before the time it can be used,
+ * {@code false} otherwise
*/
public boolean isBeforeUse() {
Instant notBefore = null;
@@ -313,7 +312,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns {@code true} if the token is currently active.
- *
* @return {@code true} if the token is currently active, {@code false} otherwise
*/
public boolean isActive() {
@@ -322,7 +320,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the claims associated to the token.
- *
* @return a {@code Map} of the claims, or {@code null} if not available
*/
@Nullable
@@ -332,7 +329,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the value of the metadata associated to the token.
- *
* @param name the name of the metadata
* @param the value type of the metadata
* @return the value of the metadata, or {@code null} if not available
@@ -346,7 +342,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Returns the metadata associated to the token.
- *
* @return a {@code Map} of the metadata
*/
public Map getMetadata() {
@@ -368,27 +363,35 @@ public class OAuth2Authorization implements Serializable {
return false;
}
Token> that = (Token>) obj;
- return Objects.equals(this.token, that.token) &&
- Objects.equals(this.metadata, that.metadata);
+ return Objects.equals(this.token, that.token) && Objects.equals(this.metadata, that.metadata);
}
@Override
public int hashCode() {
return Objects.hash(this.token, this.metadata);
}
+
}
/**
* A builder for {@link OAuth2Authorization}.
*/
public static class Builder implements Serializable {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private String id;
+
private final String registeredClientId;
+
private String principalName;
+
private AuthorizationGrantType authorizationGrantType;
+
private Set authorizedScopes;
+
private Map, Token>> tokens = new HashMap<>();
+
private final Map attributes = new HashMap<>();
protected Builder(String registeredClientId) {
@@ -397,7 +400,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Sets the identifier for the authorization.
- *
* @param id the identifier for the authorization
* @return the {@link Builder}
*/
@@ -408,8 +410,8 @@ public class OAuth2Authorization implements Serializable {
/**
* Sets the {@code Principal} name of the resource owner (or client).
- *
- * @param principalName the {@code Principal} name of the resource owner (or client)
+ * @param principalName the {@code Principal} name of the resource owner (or
+ * client)
* @return the {@link Builder}
*/
public Builder principalName(String principalName) {
@@ -418,8 +420,8 @@ public class OAuth2Authorization implements Serializable {
}
/**
- * Sets the {@link AuthorizationGrantType authorization grant type} used for the authorization.
- *
+ * Sets the {@link AuthorizationGrantType authorization grant type} used for the
+ * authorization.
* @param authorizationGrantType the {@link AuthorizationGrantType}
* @return the {@link Builder}
*/
@@ -430,7 +432,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Sets the authorized scope(s).
- *
* @param authorizedScopes the {@code Set} of authorized scope(s)
* @return the {@link Builder}
* @since 0.4.0
@@ -442,7 +443,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Sets the {@link OAuth2AccessToken access token}.
- *
* @param accessToken the {@link OAuth2AccessToken}
* @return the {@link Builder}
*/
@@ -452,7 +452,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Sets the {@link OAuth2RefreshToken refresh token}.
- *
* @param refreshToken the {@link OAuth2RefreshToken}
* @return the {@link Builder}
*/
@@ -462,25 +461,23 @@ public class OAuth2Authorization implements Serializable {
/**
* Sets the {@link OAuth2Token token}.
- *
* @param token the token
* @param the type of the token
* @return the {@link Builder}
*/
public Builder token(T token) {
- return token(token, (metadata) -> {});
+ return token(token, (metadata) -> {
+ });
}
/**
* Sets the {@link OAuth2Token token} and associated metadata.
- *
* @param token the token
* @param metadataConsumer a {@code Consumer} of the metadata {@code Map}
* @param the type of the token
* @return the {@link Builder}
*/
- public Builder token(T token,
- Consumer> metadataConsumer) {
+ public Builder token(T token, Consumer> metadataConsumer) {
Assert.notNull(token, "token cannot be null");
Map metadata = Token.defaultMetadata();
@@ -501,7 +498,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Adds an attribute associated to the authorization.
- *
* @param name the name of the attribute
* @param value the value of the attribute
* @return the {@link Builder}
@@ -514,9 +510,8 @@ public class OAuth2Authorization implements Serializable {
}
/**
- * A {@code Consumer} of the attributes {@code Map}
- * allowing the ability to add, replace, or remove.
- *
+ * A {@code Consumer} of the attributes {@code Map} allowing the ability to add,
+ * replace, or remove.
* @param attributesConsumer a {@link Consumer} of the attributes {@code Map}
* @return the {@link Builder}
*/
@@ -527,7 +522,6 @@ public class OAuth2Authorization implements Serializable {
/**
* Builds a new {@link OAuth2Authorization}.
- *
* @return the {@link OAuth2Authorization}
*/
public OAuth2Authorization build() {
@@ -542,12 +536,8 @@ public class OAuth2Authorization implements Serializable {
authorization.registeredClientId = this.registeredClientId;
authorization.principalName = this.principalName;
authorization.authorizationGrantType = this.authorizationGrantType;
- authorization.authorizedScopes =
- Collections.unmodifiableSet(
- !CollectionUtils.isEmpty(this.authorizedScopes) ?
- new HashSet<>(this.authorizedScopes) :
- new HashSet<>()
- );
+ authorization.authorizedScopes = Collections.unmodifiableSet(!CollectionUtils.isEmpty(this.authorizedScopes)
+ ? new HashSet<>(this.authorizedScopes) : new HashSet<>());
authorization.tokens = Collections.unmodifiableMap(this.tokens);
authorization.attributes = Collections.unmodifiableMap(this.attributes);
return authorization;
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationCode.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationCode.java
index 9ad711a7..4447962b 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationCode.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationCode.java
@@ -20,13 +20,14 @@ import java.time.Instant;
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
/**
- * An implementation of an {@link AbstractOAuth2Token}
- * representing an OAuth 2.0 Authorization Code Grant.
+ * An implementation of an {@link AbstractOAuth2Token} representing an OAuth 2.0
+ * Authorization Code Grant.
*
* @author Joe Grandja
* @since 0.0.3
* @see AbstractOAuth2Token
- * @see Section 4.1 Authorization Code Grant
+ * @see Section
+ * 4.1 Authorization Code Grant
*/
public class OAuth2AuthorizationCode extends AbstractOAuth2Token {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsent.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsent.java
index 3d13f4bd..5fb89538 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsent.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsent.java
@@ -31,26 +31,33 @@ import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
- * A representation of an OAuth 2.0 "consent" to an Authorization request, which holds state related to the
- * set of {@link #getAuthorities() authorities} granted to a {@link #getRegisteredClientId() client} by the
- * {@link #getPrincipalName() resource owner}.
+ * A representation of an OAuth 2.0 "consent" to an Authorization request, which holds
+ * state related to the set of {@link #getAuthorities() authorities} granted to a
+ * {@link #getRegisteredClientId() client} by the {@link #getPrincipalName() resource
+ * owner}.
*
- * When authorizing access for a given client, the resource owner may only grant a subset of the authorities
- * the client requested. The typical use-case is the {@code authorization_code} flow, in which the client
- * requests a set of {@code scope}s. The resource owner then selects which scopes they grant to the client.
+ * When authorizing access for a given client, the resource owner may only grant a subset
+ * of the authorities the client requested. The typical use-case is the
+ * {@code authorization_code} flow, in which the client requests a set of {@code scope}s.
+ * The resource owner then selects which scopes they grant to the client.
*
* @author Daniel Garnier-Moiroux
* @since 0.1.2
*/
public final class OAuth2AuthorizationConsent implements Serializable {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private static final String AUTHORITIES_SCOPE_PREFIX = "SCOPE_";
private final String registeredClientId;
+
private final String principalName;
+
private final Set authorities;
- private OAuth2AuthorizationConsent(String registeredClientId, String principalName, Set authorities) {
+ private OAuth2AuthorizationConsent(String registeredClientId, String principalName,
+ Set authorities) {
this.registeredClientId = registeredClientId;
this.principalName = principalName;
this.authorities = Collections.unmodifiableSet(authorities);
@@ -58,7 +65,6 @@ public final class OAuth2AuthorizationConsent implements Serializable {
/**
* Returns the identifier for the {@link RegisteredClient#getId() registered client}.
- *
* @return the {@link RegisteredClient#getId()}
*/
public String getRegisteredClientId() {
@@ -67,7 +73,6 @@ public final class OAuth2AuthorizationConsent implements Serializable {
/**
* Returns the {@code Principal} name of the resource owner (or client).
- *
* @return the {@code Principal} name of the resource owner (or client)
*/
public String getPrincipalName() {
@@ -75,18 +80,18 @@ public final class OAuth2AuthorizationConsent implements Serializable {
}
/**
- * Returns the {@link GrantedAuthority authorities} granted to the client by the principal.
- *
- * @return the {@link GrantedAuthority authorities} granted to the client by the principal.
+ * Returns the {@link GrantedAuthority authorities} granted to the client by the
+ * principal.
+ * @return the {@link GrantedAuthority authorities} granted to the client by the
+ * principal.
*/
public Set getAuthorities() {
return this.authorities;
}
/**
- * Convenience method for obtaining the {@code scope}s granted to the client by the principal,
- * extracted from the {@link #getAuthorities() authorities}.
- *
+ * Convenience method for obtaining the {@code scope}s granted to the client by the
+ * principal, extracted from the {@link #getAuthorities() authorities}.
* @return the {@code scope}s granted to the client by the principal.
*/
public Set getScopes() {
@@ -108,9 +113,9 @@ public final class OAuth2AuthorizationConsent implements Serializable {
return false;
}
OAuth2AuthorizationConsent that = (OAuth2AuthorizationConsent) obj;
- return Objects.equals(this.registeredClientId, that.registeredClientId) &&
- Objects.equals(this.principalName, that.principalName) &&
- Objects.equals(this.authorities, that.authorities);
+ return Objects.equals(this.registeredClientId, that.registeredClientId)
+ && Objects.equals(this.principalName, that.principalName)
+ && Objects.equals(this.authorities, that.authorities);
}
@Override
@@ -119,26 +124,24 @@ public final class OAuth2AuthorizationConsent implements Serializable {
}
/**
- * Returns a new {@link Builder}, initialized with the values from the provided {@code OAuth2AuthorizationConsent}.
- *
- * @param authorizationConsent the {@code OAuth2AuthorizationConsent} used for initializing the {@link Builder}
+ * Returns a new {@link Builder}, initialized with the values from the provided
+ * {@code OAuth2AuthorizationConsent}.
+ * @param authorizationConsent the {@code OAuth2AuthorizationConsent} used for
+ * initializing the {@link Builder}
* @return the {@link Builder}
*/
public static Builder from(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
- return new Builder(
- authorizationConsent.getRegisteredClientId(),
- authorizationConsent.getPrincipalName(),
- authorizationConsent.getAuthorities()
- );
+ return new Builder(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName(),
+ authorizationConsent.getAuthorities());
}
/**
- * Returns a new {@link Builder}, initialized with the given {@link RegisteredClient#getClientId() registeredClientId}
- * and {@code Principal} name.
- *
+ * Returns a new {@link Builder}, initialized with the given
+ * {@link RegisteredClient#getClientId() registeredClientId} and {@code Principal}
+ * name.
* @param registeredClientId the {@link RegisteredClient#getId()}
- * @param principalName the {@code Principal} name
+ * @param principalName the {@code Principal} name
* @return the {@link Builder}
*/
public static Builder withId(@NonNull String registeredClientId, @NonNull String principalName) {
@@ -147,15 +150,17 @@ public final class OAuth2AuthorizationConsent implements Serializable {
return new Builder(registeredClientId, principalName);
}
-
/**
* A builder for {@link OAuth2AuthorizationConsent}.
*/
public static final class Builder implements Serializable {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
private final String registeredClientId;
+
private final String principalName;
+
private final Set authorities = new HashSet<>();
private Builder(String registeredClientId, String principalName) {
@@ -171,10 +176,10 @@ public final class OAuth2AuthorizationConsent implements Serializable {
}
/**
- * Adds a scope to the collection of {@code authorities} in the resulting {@link OAuth2AuthorizationConsent},
- * wrapping it in a {@link SimpleGrantedAuthority}, prefixed by {@code SCOPE_}. For example, a
+ * Adds a scope to the collection of {@code authorities} in the resulting
+ * {@link OAuth2AuthorizationConsent}, wrapping it in a
+ * {@link SimpleGrantedAuthority}, prefixed by {@code SCOPE_}. For example, a
* {@code message.write} scope would be stored as {@code SCOPE_message.write}.
- *
* @param scope the scope
* @return the {@code Builder} for further configuration
*/
@@ -186,7 +191,6 @@ public final class OAuth2AuthorizationConsent implements Serializable {
/**
* Adds a {@link GrantedAuthority} to the collection of {@code authorities} in the
* resulting {@link OAuth2AuthorizationConsent}.
- *
* @param authority the {@link GrantedAuthority}
* @return the {@code Builder} for further configuration
*/
@@ -196,8 +200,8 @@ public final class OAuth2AuthorizationConsent implements Serializable {
}
/**
- * A {@code Consumer} of the {@code authorities}, allowing the ability to add, replace or remove.
- *
+ * A {@code Consumer} of the {@code authorities}, allowing the ability to add,
+ * replace or remove.
* @param authoritiesConsumer a {@code Consumer} of the {@code authorities}
* @return the {@code Builder} for further configuration
*/
@@ -209,12 +213,13 @@ public final class OAuth2AuthorizationConsent implements Serializable {
/**
* Validate the authorities and build the {@link OAuth2AuthorizationConsent}.
* There must be at least one {@link GrantedAuthority}.
- *
* @return the {@link OAuth2AuthorizationConsent}
*/
public OAuth2AuthorizationConsent build() {
Assert.notEmpty(this.authorities, "authorities cannot be empty");
return new OAuth2AuthorizationConsent(this.registeredClientId, this.principalName, this.authorities);
}
+
}
+
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentService.java
index 04f6607c..19e0622b 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentService.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentService.java
@@ -21,8 +21,8 @@ import org.springframework.security.oauth2.server.authorization.client.Registere
import java.security.Principal;
/**
- * Implementations of this interface are responsible for the management
- * of {@link OAuth2AuthorizationConsent OAuth 2.0 Authorization Consent(s)}.
+ * Implementations of this interface are responsible for the management of
+ * {@link OAuth2AuthorizationConsent OAuth 2.0 Authorization Consent(s)}.
*
* @author Daniel Garnier-Moiroux
* @since 0.1.2
@@ -32,14 +32,12 @@ public interface OAuth2AuthorizationConsentService {
/**
* Saves the {@link OAuth2AuthorizationConsent}.
- *
* @param authorizationConsent the {@link OAuth2AuthorizationConsent}
*/
void save(OAuth2AuthorizationConsent authorizationConsent);
/**
* Removes the {@link OAuth2AuthorizationConsent}.
- *
* @param authorizationConsent the {@link OAuth2AuthorizationConsent}
*/
void remove(OAuth2AuthorizationConsent authorizationConsent);
@@ -47,7 +45,6 @@ public interface OAuth2AuthorizationConsentService {
/**
* Returns the {@link OAuth2AuthorizationConsent} identified by the provided
* {@code registeredClientId} and {@code principalName}, or {@code null} if not found.
- *
* @param registeredClientId the identifier for the {@link RegisteredClient}
* @param principalName the name of the {@link Principal}
* @return the {@link OAuth2AuthorizationConsent} if found, otherwise {@code null}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadata.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadata.java
index 210a3ac9..e62740a3 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadata.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadata.java
@@ -20,16 +20,16 @@ import java.util.Map;
import org.springframework.util.Assert;
/**
- * A representation of an OAuth 2.0 Authorization Server Metadata response,
- * which is returned from an OAuth 2.0 Authorization Server's Metadata Endpoint,
- * and contains a set of claims about the Authorization Server's configuration.
- * The claims are defined by the OAuth 2.0 Authorization Server Metadata
- * specification (RFC 8414).
+ * A representation of an OAuth 2.0 Authorization Server Metadata response, which is
+ * returned from an OAuth 2.0 Authorization Server's Metadata Endpoint, and contains a set
+ * of claims about the Authorization Server's configuration. The claims are defined by the
+ * OAuth 2.0 Authorization Server Metadata specification (RFC 8414).
*
* @author Daniel Garnier-Moiroux
* @since 0.1.1
* @see AbstractOAuth2AuthorizationServerMetadata
- * @see 3.2. Authorization Server Metadata Response
+ * @see 3.2.
+ * Authorization Server Metadata Response
*/
public final class OAuth2AuthorizationServerMetadata extends AbstractOAuth2AuthorizationServerMetadata {
@@ -39,7 +39,6 @@ public final class OAuth2AuthorizationServerMetadata extends AbstractOAuth2Autho
/**
* Constructs a new {@link Builder} with empty claims.
- *
* @return the {@link Builder}
*/
public static Builder builder() {
@@ -48,14 +47,12 @@ public final class OAuth2AuthorizationServerMetadata extends AbstractOAuth2Autho
/**
* Constructs a new {@link Builder} with the provided claims.
- *
* @param claims the claims to initialize the builder
* @return the {@link Builder}
*/
public static Builder withClaims(Map claims) {
Assert.notEmpty(claims, "claims cannot be empty");
- return new Builder()
- .claims(c -> c.putAll(claims));
+ return new Builder().claims(c -> c.putAll(claims));
}
/**
@@ -69,10 +66,9 @@ public final class OAuth2AuthorizationServerMetadata extends AbstractOAuth2Autho
/**
* Validate the claims and build the {@link OAuth2AuthorizationServerMetadata}.
*
- * The following claims are REQUIRED:
- * {@code issuer}, {@code authorization_endpoint}, {@code token_endpoint}
- * and {@code response_types_supported}.
- *
+ * The following claims are REQUIRED: {@code issuer},
+ * {@code authorization_endpoint}, {@code token_endpoint} and
+ * {@code response_types_supported}.
* @return the {@link OAuth2AuthorizationServerMetadata}
*/
@Override
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataClaimAccessor.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataClaimAccessor.java
index 089944d1..63f21a53 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataClaimAccessor.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataClaimAccessor.java
@@ -21,22 +21,27 @@ import java.util.List;
import org.springframework.security.oauth2.core.ClaimAccessor;
/**
- * A {@link ClaimAccessor} for the "claims" an Authorization Server describes about its configuration,
- * used in OAuth 2.0 Authorization Server Metadata and OpenID Connect Discovery 1.0.
+ * A {@link ClaimAccessor} for the "claims" an Authorization Server describes about its
+ * configuration, used in OAuth 2.0 Authorization Server Metadata and OpenID Connect
+ * Discovery 1.0.
*
* @author Daniel Garnier-Moiroux
* @since 0.1.1
* @see ClaimAccessor
* @see OAuth2AuthorizationServerMetadataClaimNames
- * @see 2. Authorization Server Metadata
- * @see 3. OpenID Provider Metadata
- * @see 4. Device Authorization Grant Metadata
+ * @see 2.
+ * Authorization Server Metadata
+ * @see 3. OpenID
+ * Provider Metadata
+ * @see 4.
+ * Device Authorization Grant Metadata
*/
public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAccessor {
/**
- * Returns the {@code URL} the Authorization Server asserts as its Issuer Identifier {@code (issuer)}.
- *
+ * Returns the {@code URL} the Authorization Server asserts as its Issuer Identifier
+ * {@code (issuer)}.
* @return the {@code URL} the Authorization Server asserts as its Issuer Identifier
*/
default URL getIssuer() {
@@ -44,8 +49,8 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
}
/**
- * Returns the {@code URL} of the OAuth 2.0 Authorization Endpoint {@code (authorization_endpoint)}.
- *
+ * Returns the {@code URL} of the OAuth 2.0 Authorization Endpoint
+ * {@code (authorization_endpoint)}.
* @return the {@code URL} of the OAuth 2.0 Authorization Endpoint
*/
default URL getAuthorizationEndpoint() {
@@ -53,8 +58,8 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
}
/**
- * Returns the {@code URL} of the OAuth 2.0 Device Authorization Endpoint {@code (device_authorization_endpoint)}.
- *
+ * Returns the {@code URL} of the OAuth 2.0 Device Authorization Endpoint
+ * {@code (device_authorization_endpoint)}.
* @return the {@code URL} of the OAuth 2.0 Device Authorization Endpoint
* @since 1.1
*/
@@ -64,7 +69,6 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
/**
* Returns the {@code URL} of the OAuth 2.0 Token Endpoint {@code (token_endpoint)}.
- *
* @return the {@code URL} of the OAuth 2.0 Token Endpoint
*/
default URL getTokenEndpoint() {
@@ -72,8 +76,8 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
}
/**
- * Returns the client authentication methods supported by the OAuth 2.0 Token Endpoint {@code (token_endpoint_auth_methods_supported)}.
- *
+ * Returns the client authentication methods supported by the OAuth 2.0 Token Endpoint
+ * {@code (token_endpoint_auth_methods_supported)}.
* @return the client authentication methods supported by the OAuth 2.0 Token Endpoint
*/
default List getTokenEndpointAuthenticationMethods() {
@@ -82,7 +86,6 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
/**
* Returns the {@code URL} of the JSON Web Key Set {@code (jwks_uri)}.
- *
* @return the {@code URL} of the JSON Web Key Set
*/
default URL getJwkSetUrl() {
@@ -91,7 +94,6 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
/**
* Returns the OAuth 2.0 {@code scope} values supported {@code (scopes_supported)}.
- *
* @return the OAuth 2.0 {@code scope} values supported
*/
default List getScopes() {
@@ -99,8 +101,8 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
}
/**
- * Returns the OAuth 2.0 {@code response_type} values supported {@code (response_types_supported)}.
- *
+ * Returns the OAuth 2.0 {@code response_type} values supported
+ * {@code (response_types_supported)}.
* @return the OAuth 2.0 {@code response_type} values supported
*/
default List getResponseTypes() {
@@ -108,8 +110,8 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
}
/**
- * Returns the OAuth 2.0 {@code grant_type} values supported {@code (grant_types_supported)}.
- *
+ * Returns the OAuth 2.0 {@code grant_type} values supported
+ * {@code (grant_types_supported)}.
* @return the OAuth 2.0 {@code grant_type} values supported
*/
default List getGrantTypes() {
@@ -117,8 +119,8 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
}
/**
- * Returns the {@code URL} of the OAuth 2.0 Token Revocation Endpoint {@code (revocation_endpoint)}.
- *
+ * Returns the {@code URL} of the OAuth 2.0 Token Revocation Endpoint
+ * {@code (revocation_endpoint)}.
* @return the {@code URL} of the OAuth 2.0 Token Revocation Endpoint
*/
default URL getTokenRevocationEndpoint() {
@@ -126,17 +128,19 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
}
/**
- * Returns the client authentication methods supported by the OAuth 2.0 Token Revocation Endpoint {@code (revocation_endpoint_auth_methods_supported)}.
- *
- * @return the client authentication methods supported by the OAuth 2.0 Token Revocation Endpoint
+ * Returns the client authentication methods supported by the OAuth 2.0 Token
+ * Revocation Endpoint {@code (revocation_endpoint_auth_methods_supported)}.
+ * @return the client authentication methods supported by the OAuth 2.0 Token
+ * Revocation Endpoint
*/
default List getTokenRevocationEndpointAuthenticationMethods() {
- return getClaimAsStringList(OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT_AUTH_METHODS_SUPPORTED);
+ return getClaimAsStringList(
+ OAuth2AuthorizationServerMetadataClaimNames.REVOCATION_ENDPOINT_AUTH_METHODS_SUPPORTED);
}
/**
- * Returns the {@code URL} of the OAuth 2.0 Token Introspection Endpoint {@code (introspection_endpoint)}.
- *
+ * Returns the {@code URL} of the OAuth 2.0 Token Introspection Endpoint
+ * {@code (introspection_endpoint)}.
* @return the {@code URL} of the OAuth 2.0 Token Introspection Endpoint
*/
default URL getTokenIntrospectionEndpoint() {
@@ -144,17 +148,19 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
}
/**
- * Returns the client authentication methods supported by the OAuth 2.0 Token Introspection Endpoint {@code (introspection_endpoint_auth_methods_supported)}.
- *
- * @return the client authentication methods supported by the OAuth 2.0 Token Introspection Endpoint
+ * Returns the client authentication methods supported by the OAuth 2.0 Token
+ * Introspection Endpoint {@code (introspection_endpoint_auth_methods_supported)}.
+ * @return the client authentication methods supported by the OAuth 2.0 Token
+ * Introspection Endpoint
*/
default List getTokenIntrospectionEndpointAuthenticationMethods() {
- return getClaimAsStringList(OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED);
+ return getClaimAsStringList(
+ OAuth2AuthorizationServerMetadataClaimNames.INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED);
}
/**
- * Returns the {@code URL} of the OAuth 2.0 Dynamic Client Registration Endpoint {@code (registration_endpoint)}.
- *
+ * Returns the {@code URL} of the OAuth 2.0 Dynamic Client Registration Endpoint
+ * {@code (registration_endpoint)}.
* @return the {@code URL} of the OAuth 2.0 Dynamic Client Registration Endpoint
* @since 0.4.0
*/
@@ -163,8 +169,8 @@ public interface OAuth2AuthorizationServerMetadataClaimAccessor extends ClaimAcc
}
/**
- * Returns the Proof Key for Code Exchange (PKCE) {@code code_challenge_method} values supported {@code (code_challenge_methods_supported)}.
- *
+ * Returns the Proof Key for Code Exchange (PKCE) {@code code_challenge_method} values
+ * supported {@code (code_challenge_methods_supported)}.
* @return the {@code code_challenge_method} values supported
*/
default List getCodeChallengeMethods() {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataClaimNames.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataClaimNames.java
index 831e0ec7..fe7d9107 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataClaimNames.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataClaimNames.java
@@ -21,24 +21,31 @@ package org.springframework.security.oauth2.server.authorization;
*
* @author Daniel Garnier-Moiroux
* @since 0.1.1
- * @see 2. Authorization Server Metadata
- * @see 3. OpenID Provider Metadata
- * @see 4. Device Authorization Grant Metadata
+ * @see 2.
+ * Authorization Server Metadata
+ * @see 3. OpenID
+ * Provider Metadata
+ * @see 4.
+ * Device Authorization Grant Metadata
*/
public class OAuth2AuthorizationServerMetadataClaimNames {
/**
- * {@code issuer} - the {@code URL} the Authorization Server asserts as its Issuer Identifier
+ * {@code issuer} - the {@code URL} the Authorization Server asserts as its Issuer
+ * Identifier
*/
public static final String ISSUER = "issuer";
/**
- * {@code authorization_endpoint} - the {@code URL} of the OAuth 2.0 Authorization Endpoint
+ * {@code authorization_endpoint} - the {@code URL} of the OAuth 2.0 Authorization
+ * Endpoint
*/
public static final String AUTHORIZATION_ENDPOINT = "authorization_endpoint";
/**
- * {@code device_authorization_endpoint} - the {@code URL} of the OAuth 2.0 Device Authorization Endpoint
+ * {@code device_authorization_endpoint} - the {@code URL} of the OAuth 2.0 Device
+ * Authorization Endpoint
* @since 1.1
*/
public static final String DEVICE_AUTHORIZATION_ENDPOINT = "device_authorization_endpoint";
@@ -49,7 +56,8 @@ public class OAuth2AuthorizationServerMetadataClaimNames {
public static final String TOKEN_ENDPOINT = "token_endpoint";
/**
- * {@code token_endpoint_auth_methods_supported} - the client authentication methods supported by the OAuth 2.0 Token Endpoint
+ * {@code token_endpoint_auth_methods_supported} - the client authentication methods
+ * supported by the OAuth 2.0 Token Endpoint
*/
public static final String TOKEN_ENDPOINT_AUTH_METHODS_SUPPORTED = "token_endpoint_auth_methods_supported";
@@ -64,7 +72,8 @@ public class OAuth2AuthorizationServerMetadataClaimNames {
public static final String SCOPES_SUPPORTED = "scopes_supported";
/**
- * {@code response_types_supported} - the OAuth 2.0 {@code response_type} values supported
+ * {@code response_types_supported} - the OAuth 2.0 {@code response_type} values
+ * supported
*/
public static final String RESPONSE_TYPES_SUPPORTED = "response_types_supported";
@@ -74,33 +83,39 @@ public class OAuth2AuthorizationServerMetadataClaimNames {
public static final String GRANT_TYPES_SUPPORTED = "grant_types_supported";
/**
- * {@code revocation_endpoint} - the {@code URL} of the OAuth 2.0 Token Revocation Endpoint
+ * {@code revocation_endpoint} - the {@code URL} of the OAuth 2.0 Token Revocation
+ * Endpoint
*/
public static final String REVOCATION_ENDPOINT = "revocation_endpoint";
/**
- * {@code revocation_endpoint_auth_methods_supported} - the client authentication methods supported by the OAuth 2.0 Token Revocation Endpoint
+ * {@code revocation_endpoint_auth_methods_supported} - the client authentication
+ * methods supported by the OAuth 2.0 Token Revocation Endpoint
*/
public static final String REVOCATION_ENDPOINT_AUTH_METHODS_SUPPORTED = "revocation_endpoint_auth_methods_supported";
/**
- * {@code introspection_endpoint} - the {@code URL} of the OAuth 2.0 Token Introspection Endpoint
+ * {@code introspection_endpoint} - the {@code URL} of the OAuth 2.0 Token
+ * Introspection Endpoint
*/
public static final String INTROSPECTION_ENDPOINT = "introspection_endpoint";
/**
- * {@code introspection_endpoint_auth_methods_supported} - the client authentication methods supported by the OAuth 2.0 Token Introspection Endpoint
+ * {@code introspection_endpoint_auth_methods_supported} - the client authentication
+ * methods supported by the OAuth 2.0 Token Introspection Endpoint
*/
public static final String INTROSPECTION_ENDPOINT_AUTH_METHODS_SUPPORTED = "introspection_endpoint_auth_methods_supported";
/**
- * {@code registration_endpoint} - the {@code URL} of the OAuth 2.0 Dynamic Client Registration Endpoint
+ * {@code registration_endpoint} - the {@code URL} of the OAuth 2.0 Dynamic Client
+ * Registration Endpoint
* @since 0.4.0
*/
public static final String REGISTRATION_ENDPOINT = "registration_endpoint";
/**
- * {@code code_challenge_methods_supported} - the Proof Key for Code Exchange (PKCE) {@code code_challenge_method} values supported
+ * {@code code_challenge_methods_supported} - the Proof Key for Code Exchange (PKCE)
+ * {@code code_challenge_method} values supported
*/
public static final String CODE_CHALLENGE_METHODS_SUPPORTED = "code_challenge_methods_supported";
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationService.java
index 9e4e5553..6e5ed530 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationService.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationService.java
@@ -18,8 +18,8 @@ package org.springframework.security.oauth2.server.authorization;
import org.springframework.lang.Nullable;
/**
- * Implementations of this interface are responsible for the management
- * of {@link OAuth2Authorization OAuth 2.0 Authorization(s)}.
+ * Implementations of this interface are responsible for the management of
+ * {@link OAuth2Authorization OAuth 2.0 Authorization(s)}.
*
* @author Joe Grandja
* @since 0.0.1
@@ -30,22 +30,19 @@ public interface OAuth2AuthorizationService {
/**
* Saves the {@link OAuth2Authorization}.
- *
* @param authorization the {@link OAuth2Authorization}
*/
void save(OAuth2Authorization authorization);
/**
* Removes the {@link OAuth2Authorization}.
- *
* @param authorization the {@link OAuth2Authorization}
*/
void remove(OAuth2Authorization authorization);
/**
- * Returns the {@link OAuth2Authorization} identified by the provided {@code id},
- * or {@code null} if not found.
- *
+ * Returns the {@link OAuth2Authorization} identified by the provided {@code id}, or
+ * {@code null} if not found.
* @param id the authorization identifier
* @return the {@link OAuth2Authorization} if found, otherwise {@code null}
*/
@@ -53,9 +50,8 @@ public interface OAuth2AuthorizationService {
OAuth2Authorization findById(String id);
/**
- * Returns the {@link OAuth2Authorization} containing the provided {@code token},
- * or {@code null} if not found.
- *
+ * Returns the {@link OAuth2Authorization} containing the provided {@code token}, or
+ * {@code null} if not found.
* @param token the token credential
* @param tokenType the {@link OAuth2TokenType token type}
* @return the {@link OAuth2Authorization} if found, otherwise {@code null}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenIntrospection.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenIntrospection.java
index 62b337a3..f2652c3b 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenIntrospection.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenIntrospection.java
@@ -39,10 +39,13 @@ import org.springframework.util.Assert;
* @author Joe Grandja
* @since 0.1.1
* @see OAuth2TokenIntrospectionClaimAccessor
- * @see Section 2.2 Introspection Response
+ * @see Section
+ * 2.2 Introspection Response
*/
public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionClaimAccessor, Serializable {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private final Map claims;
private OAuth2TokenIntrospection(Map claims) {
@@ -51,7 +54,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Returns the claims in the Token Introspection Response.
- *
* @return a {@code Map} of the claims
*/
@Override
@@ -60,8 +62,8 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
}
/**
- * Constructs a new {@link Builder} initialized with the {@link #isActive() active} claim to {@code false}.
- *
+ * Constructs a new {@link Builder} initialized with the {@link #isActive() active}
+ * claim to {@code false}.
* @return the {@link Builder}
*/
public static Builder builder() {
@@ -69,9 +71,10 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
}
/**
- * Constructs a new {@link Builder} initialized with the provided {@link #isActive() active} claim.
- *
- * @param active {@code true} if the token is currently active, {@code false} otherwise
+ * Constructs a new {@link Builder} initialized with the provided {@link #isActive()
+ * active} claim.
+ * @param active {@code true} if the token is currently active, {@code false}
+ * otherwise
* @return the {@link Builder}
*/
public static Builder builder(boolean active) {
@@ -80,7 +83,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Constructs a new {@link Builder} initialized with the provided claims.
- *
* @param claims the claims to initialize the builder
* @return the {@link Builder}
*/
@@ -93,6 +95,7 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
* A builder for {@link OAuth2TokenIntrospection}.
*/
public static class Builder {
+
private final Map claims = new LinkedHashMap<>();
private Builder(boolean active) {
@@ -100,9 +103,10 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
}
/**
- * Sets the indicator of whether or not the presented token is currently active, REQUIRED.
- *
- * @param active {@code true} if the token is currently active, {@code false} otherwise
+ * Sets the indicator of whether or not the presented token is currently active,
+ * REQUIRED.
+ * @param active {@code true} if the token is currently active, {@code false}
+ * otherwise
* @return the {@link Builder} for further configuration
*/
public Builder active(boolean active) {
@@ -111,7 +115,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Add the scope associated with this token, OPTIONAL.
- *
* @param scope the scope associated with this token
* @return the {@link Builder} for further configuration
*/
@@ -121,10 +124,10 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
}
/**
- * A {@code Consumer} of the scope(s) associated with this token,
- * allowing the ability to add, replace, or remove, OPTIONAL.
- *
- * @param scopesConsumer a {@code Consumer} of the scope(s) associated with this token
+ * A {@code Consumer} of the scope(s) associated with this token, allowing the
+ * ability to add, replace, or remove, OPTIONAL.
+ * @param scopesConsumer a {@code Consumer} of the scope(s) associated with this
+ * token
* @return the {@link Builder} for further configuration
*/
public Builder scopes(Consumer> scopesConsumer) {
@@ -133,9 +136,10 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
}
/**
- * Sets the client identifier for the OAuth 2.0 client that requested this token, OPTIONAL.
- *
- * @param clientId the client identifier for the OAuth 2.0 client that requested this token
+ * Sets the client identifier for the OAuth 2.0 client that requested this token,
+ * OPTIONAL.
+ * @param clientId the client identifier for the OAuth 2.0 client that requested
+ * this token
* @return the {@link Builder} for further configuration
*/
public Builder clientId(String clientId) {
@@ -143,9 +147,10 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
}
/**
- * Sets the human-readable identifier for the resource owner who authorized this token, OPTIONAL.
- *
- * @param username the human-readable identifier for the resource owner who authorized this token
+ * Sets the human-readable identifier for the resource owner who authorized this
+ * token, OPTIONAL.
+ * @param username the human-readable identifier for the resource owner who
+ * authorized this token
* @return the {@link Builder} for further configuration
*/
public Builder username(String username) {
@@ -154,7 +159,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Sets the token type (e.g. bearer), OPTIONAL.
- *
* @param tokenType the token type
* @return the {@link Builder} for further configuration
*/
@@ -164,7 +168,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Sets the time indicating when this token will expire, OPTIONAL.
- *
* @param expiresAt the time indicating when this token will expire
* @return the {@link Builder} for further configuration
*/
@@ -174,7 +177,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Sets the time indicating when this token was originally issued, OPTIONAL.
- *
* @param issuedAt the time indicating when this token was originally issued
* @return the {@link Builder} for further configuration
*/
@@ -184,7 +186,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Sets the time indicating when this token is not to be used before, OPTIONAL.
- *
* @param notBefore the time indicating when this token is not to be used before
* @return the {@link Builder} for further configuration
*/
@@ -193,9 +194,8 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
}
/**
- * Sets the subject of the token, usually a machine-readable identifier
- * of the resource owner who authorized this token, OPTIONAL.
- *
+ * Sets the subject of the token, usually a machine-readable identifier of the
+ * resource owner who authorized this token, OPTIONAL.
* @param subject the subject of the token
* @return the {@link Builder} for further configuration
*/
@@ -205,8 +205,8 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Add the identifier representing the intended audience for this token, OPTIONAL.
- *
- * @param audience the identifier representing the intended audience for this token
+ * @param audience the identifier representing the intended audience for this
+ * token
* @return the {@link Builder} for further configuration
*/
public Builder audience(String audience) {
@@ -215,10 +215,10 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
}
/**
- * A {@code Consumer} of the intended audience(s) for this token,
- * allowing the ability to add, replace, or remove, OPTIONAL.
- *
- * @param audiencesConsumer a {@code Consumer} of the intended audience(s) for this token
+ * A {@code Consumer} of the intended audience(s) for this token, allowing the
+ * ability to add, replace, or remove, OPTIONAL.
+ * @param audiencesConsumer a {@code Consumer} of the intended audience(s) for
+ * this token
* @return the {@link Builder} for further configuration
*/
public Builder audiences(Consumer> audiencesConsumer) {
@@ -228,7 +228,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Sets the issuer of this token, OPTIONAL.
- *
* @param issuer the issuer of this token
* @return the {@link Builder} for further configuration
*/
@@ -238,7 +237,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Sets the identifier for the token, OPTIONAL.
- *
* @param jti the identifier for the token
* @return the {@link Builder} for further configuration
*/
@@ -248,7 +246,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Sets the claim.
- *
* @param name the claim name
* @param value the claim value
* @return the {@link Builder} for further configuration
@@ -263,7 +260,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
/**
* Provides access to every {@link #claim(String, Object)} declared so far with
* the possibility to add, replace, or remove.
- *
* @param claimsConsumer a {@code Consumer} of the claims
* @return the {@link Builder} for further configurations
*/
@@ -276,7 +272,6 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
* Validate the claims and build the {@link OAuth2TokenIntrospection}.
*
* The following claims are REQUIRED: {@code active}
- *
* @return the {@link OAuth2TokenIntrospection}
*/
public OAuth2TokenIntrospection build() {
@@ -286,21 +281,27 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
private void validate() {
Assert.notNull(this.claims.get(OAuth2TokenIntrospectionClaimNames.ACTIVE), "active cannot be null");
- Assert.isInstanceOf(Boolean.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.ACTIVE), "active must be of type boolean");
+ Assert.isInstanceOf(Boolean.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.ACTIVE),
+ "active must be of type boolean");
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.SCOPE)) {
- Assert.isInstanceOf(List.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.SCOPE), "scope must be of type List");
+ Assert.isInstanceOf(List.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.SCOPE),
+ "scope must be of type List");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.EXP)) {
- Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.EXP), "exp must be of type Instant");
+ Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.EXP),
+ "exp must be of type Instant");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.IAT)) {
- Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.IAT), "iat must be of type Instant");
+ Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.IAT),
+ "iat must be of type Instant");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.NBF)) {
- Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.NBF), "nbf must be of type Instant");
+ Assert.isInstanceOf(Instant.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.NBF),
+ "nbf must be of type Instant");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.AUD)) {
- Assert.isInstanceOf(List.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.AUD), "aud must be of type List");
+ Assert.isInstanceOf(List.class, this.claims.get(OAuth2TokenIntrospectionClaimNames.AUD),
+ "aud must be of type List");
}
if (this.claims.containsKey(OAuth2TokenIntrospectionClaimNames.ISS)) {
validateURL(this.claims.get(OAuth2TokenIntrospectionClaimNames.ISS), "iss must be a valid URL");
@@ -331,9 +332,12 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
try {
new URI(url.toString()).toURL();
- } catch (Exception ex) {
+ }
+ catch (Exception ex) {
throw new IllegalArgumentException(errorMessage, ex);
}
}
+
}
+
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenType.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenType.java
index 8c25c863..63735785 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenType.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenType.java
@@ -25,17 +25,21 @@ import org.springframework.util.Assert;
*
* @author Joe Grandja
* @since 0.0.1
- * @see 4.1.2 OAuth Token Type Hints Registry
+ * @see 4.1.2
+ * OAuth Token Type Hints Registry
*/
public final class OAuth2TokenType implements Serializable {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
public static final OAuth2TokenType ACCESS_TOKEN = new OAuth2TokenType("access_token");
+
public static final OAuth2TokenType REFRESH_TOKEN = new OAuth2TokenType("refresh_token");
+
private final String value;
/**
* Constructs an {@code OAuth2TokenType} using the provided value.
- *
* @param value the value of the token type
*/
public OAuth2TokenType(String value) {
@@ -45,7 +49,6 @@ public final class OAuth2TokenType implements Serializable {
/**
* Returns the value of the token type.
- *
* @return the value of the token type
*/
public String getValue() {
@@ -68,4 +71,5 @@ public final class OAuth2TokenType implements Serializable {
public int hashCode() {
return getValue().hashCode();
}
+
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProvider.java
index 5010be95..6473ca33 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProvider.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProvider.java
@@ -36,8 +36,9 @@ import org.springframework.security.oauth2.server.authorization.client.Registere
import org.springframework.util.Assert;
/**
- * An {@link AuthenticationProvider} implementation used for OAuth 2.0 Client Authentication,
- * which authenticates the {@link OAuth2ParameterNames#CLIENT_SECRET client_secret} parameter.
+ * An {@link AuthenticationProvider} implementation used for OAuth 2.0 Client
+ * Authentication, which authenticates the {@link OAuth2ParameterNames#CLIENT_SECRET
+ * client_secret} parameter.
*
* @author Patryk Kostrzewa
* @author Joe Grandja
@@ -49,15 +50,20 @@ import org.springframework.util.Assert;
* @see PasswordEncoder
*/
public final class ClientSecretAuthenticationProvider implements AuthenticationProvider {
+
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-3.2.1";
+
private final Log logger = LogFactory.getLog(getClass());
+
private final RegisteredClientRepository registeredClientRepository;
+
private final CodeVerifierAuthenticator codeVerifierAuthenticator;
+
private PasswordEncoder passwordEncoder;
/**
- * Constructs a {@code ClientSecretAuthenticationProvider} using the provided parameters.
- *
+ * Constructs a {@code ClientSecretAuthenticationProvider} using the provided
+ * parameters.
* @param registeredClientRepository the repository of registered clients
* @param authorizationService the authorization service
*/
@@ -71,12 +77,12 @@ public final class ClientSecretAuthenticationProvider implements AuthenticationP
}
/**
- * Sets the {@link PasswordEncoder} used to validate
- * the {@link RegisteredClient#getClientSecret() client secret}.
- * If not set, the client secret will be compared using
+ * Sets the {@link PasswordEncoder} used to validate the
+ * {@link RegisteredClient#getClientSecret() client secret}. If not set, the client
+ * secret will be compared using
* {@link PasswordEncoderFactories#createDelegatingPasswordEncoder()}.
- *
- * @param passwordEncoder the {@link PasswordEncoder} used to validate the client secret
+ * @param passwordEncoder the {@link PasswordEncoder} used to validate the client
+ * secret
*/
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
@@ -85,8 +91,7 @@ public final class ClientSecretAuthenticationProvider implements AuthenticationP
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- OAuth2ClientAuthenticationToken clientAuthentication =
- (OAuth2ClientAuthenticationToken) authentication;
+ OAuth2ClientAuthenticationToken clientAuthentication = (OAuth2ClientAuthenticationToken) authentication;
// @formatter:off
if (!ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(clientAuthentication.getClientAuthenticationMethod()) &&
@@ -105,8 +110,8 @@ public final class ClientSecretAuthenticationProvider implements AuthenticationP
this.logger.trace("Retrieved registered client");
}
- if (!registeredClient.getClientAuthenticationMethods().contains(
- clientAuthentication.getClientAuthenticationMethod())) {
+ if (!registeredClient.getClientAuthenticationMethods()
+ .contains(clientAuthentication.getClientAuthenticationMethod())) {
throwInvalidClient("authentication_method");
}
@@ -119,15 +124,15 @@ public final class ClientSecretAuthenticationProvider implements AuthenticationP
throwInvalidClient(OAuth2ParameterNames.CLIENT_SECRET);
}
- if (registeredClient.getClientSecretExpiresAt() != null &&
- Instant.now().isAfter(registeredClient.getClientSecretExpiresAt())) {
+ if (registeredClient.getClientSecretExpiresAt() != null
+ && Instant.now().isAfter(registeredClient.getClientSecretExpiresAt())) {
throwInvalidClient("client_secret_expires_at");
}
if (this.passwordEncoder.upgradeEncoding(registeredClient.getClientSecret())) {
registeredClient = RegisteredClient.from(registeredClient)
- .clientSecret(this.passwordEncoder.encode(clientSecret))
- .build();
+ .clientSecret(this.passwordEncoder.encode(clientSecret))
+ .build();
this.registeredClientRepository.save(registeredClient);
}
@@ -135,7 +140,8 @@ public final class ClientSecretAuthenticationProvider implements AuthenticationP
this.logger.trace("Validated client authentication parameters");
}
- // Validate the "code_verifier" parameter for the confidential client, if available
+ // Validate the "code_verifier" parameter for the confidential client, if
+ // available
this.codeVerifierAuthenticator.authenticateIfAvailable(clientAuthentication, registeredClient);
if (this.logger.isTraceEnabled()) {
@@ -152,11 +158,8 @@ public final class ClientSecretAuthenticationProvider implements AuthenticationP
}
private static void throwInvalidClient(String parameterName) {
- OAuth2Error error = new OAuth2Error(
- OAuth2ErrorCodes.INVALID_CLIENT,
- "Client authentication failed: " + parameterName,
- ERROR_URI
- );
+ OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT,
+ "Client authentication failed: " + parameterName, ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/CodeVerifierAuthenticator.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/CodeVerifierAuthenticator.java
index e74d60a5..1d16561a 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/CodeVerifierAuthenticator.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/CodeVerifierAuthenticator.java
@@ -39,8 +39,8 @@ import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
- * An authenticator used for OAuth 2.0 Client Authentication,
- * which authenticates the {@link PkceParameterNames#CODE_VERIFIER code_verifier} parameter.
+ * An authenticator used for OAuth 2.0 Client Authentication, which authenticates the
+ * {@link PkceParameterNames#CODE_VERIFIER code_verifier} parameter.
*
* @author Daniel Garnier-Moiroux
* @author Joe Grandja
@@ -49,8 +49,11 @@ import org.springframework.util.StringUtils;
* @see OAuth2AuthorizationService
*/
final class CodeVerifierAuthenticator {
+
private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.CODE);
+
private final Log logger = LogFactory.getLog(getClass());
+
private final OAuth2AuthorizationService authorizationService;
CodeVerifierAuthenticator(OAuth2AuthorizationService authorizationService) {
@@ -58,8 +61,7 @@ final class CodeVerifierAuthenticator {
this.authorizationService = authorizationService;
}
- void authenticateRequired(OAuth2ClientAuthenticationToken clientAuthentication,
- RegisteredClient registeredClient) {
+ void authenticateRequired(OAuth2ClientAuthenticationToken clientAuthentication, RegisteredClient registeredClient) {
if (!authenticate(clientAuthentication, registeredClient)) {
throwInvalidGrant(PkceParameterNames.CODE_VERIFIER);
}
@@ -78,9 +80,8 @@ final class CodeVerifierAuthenticator {
return false;
}
- OAuth2Authorization authorization = this.authorizationService.findByToken(
- (String) parameters.get(OAuth2ParameterNames.CODE),
- AUTHORIZATION_CODE_TOKEN_TYPE);
+ OAuth2Authorization authorization = this.authorizationService
+ .findByToken((String) parameters.get(OAuth2ParameterNames.CODE), AUTHORIZATION_CODE_TOKEN_TYPE);
if (authorization == null) {
throwInvalidGrant(OAuth2ParameterNames.CODE);
}
@@ -89,17 +90,17 @@ final class CodeVerifierAuthenticator {
this.logger.trace("Retrieved authorization with authorization code");
}
- OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
- OAuth2AuthorizationRequest.class.getName());
+ OAuth2AuthorizationRequest authorizationRequest = authorization
+ .getAttribute(OAuth2AuthorizationRequest.class.getName());
String codeChallenge = (String) authorizationRequest.getAdditionalParameters()
- .get(PkceParameterNames.CODE_CHALLENGE);
+ .get(PkceParameterNames.CODE_CHALLENGE);
String codeVerifier = (String) parameters.get(PkceParameterNames.CODE_VERIFIER);
if (!StringUtils.hasText(codeChallenge)) {
- if (registeredClient.getClientSettings().isRequireProofKey() ||
- StringUtils.hasText(codeVerifier)) {
+ if (registeredClient.getClientSettings().isRequireProofKey() || StringUtils.hasText(codeVerifier)) {
throwInvalidGrant(PkceParameterNames.CODE_CHALLENGE);
- } else {
+ }
+ else {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Did not authenticate code verifier since requireProofKey=false");
}
@@ -112,7 +113,7 @@ final class CodeVerifierAuthenticator {
}
String codeChallengeMethod = (String) authorizationRequest.getAdditionalParameters()
- .get(PkceParameterNames.CODE_CHALLENGE_METHOD);
+ .get(PkceParameterNames.CODE_CHALLENGE_METHOD);
if (!codeVerifierValid(codeVerifier, codeChallenge, codeChallengeMethod)) {
throwInvalidGrant(PkceParameterNames.CODE_VERIFIER);
}
@@ -135,14 +136,17 @@ final class CodeVerifierAuthenticator {
private static boolean codeVerifierValid(String codeVerifier, String codeChallenge, String codeChallengeMethod) {
if (!StringUtils.hasText(codeVerifier)) {
return false;
- } else if ("S256".equals(codeChallengeMethod)) {
+ }
+ else if ("S256".equals(codeChallengeMethod)) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(codeVerifier.getBytes(StandardCharsets.US_ASCII));
String encodedVerifier = Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
return encodedVerifier.equals(codeChallenge);
- } catch (NoSuchAlgorithmException ex) {
- // It is unlikely that SHA-256 is not available on the server. If it is not available,
+ }
+ catch (NoSuchAlgorithmException ex) {
+ // It is unlikely that SHA-256 is not available on the server. If it is
+ // not available,
// there will likely be bigger issues as well. We default to SERVER_ERROR.
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.SERVER_ERROR);
}
@@ -151,11 +155,8 @@ final class CodeVerifierAuthenticator {
}
private static void throwInvalidGrant(String parameterName) {
- OAuth2Error error = new OAuth2Error(
- OAuth2ErrorCodes.INVALID_GRANT,
- "Client authentication failed: " + parameterName,
- null
- );
+ OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT,
+ "Client authentication failed: " + parameterName, null);
throw new OAuth2AuthenticationException(error);
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java
index 407fa3aa..9c5c02b2 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java
@@ -37,8 +37,9 @@ import org.springframework.security.oauth2.server.authorization.client.Registere
import org.springframework.util.Assert;
/**
- * An {@link AuthenticationProvider} implementation used for OAuth 2.0 Client Authentication,
- * which authenticates the {@link Jwt} {@link OAuth2ParameterNames#CLIENT_ASSERTION client_assertion} parameter.
+ * An {@link AuthenticationProvider} implementation used for OAuth 2.0 Client
+ * Authentication, which authenticates the {@link Jwt}
+ * {@link OAuth2ParameterNames#CLIENT_ASSERTION client_assertion} parameter.
*
* @author Rafal Lewczuk
* @author Joe Grandja
@@ -50,17 +51,23 @@ import org.springframework.util.Assert;
* @see JwtClientAssertionDecoderFactory
*/
public final class JwtClientAssertionAuthenticationProvider implements AuthenticationProvider {
+
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-3.2.1";
- private static final ClientAuthenticationMethod JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD =
- new ClientAuthenticationMethod("urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
+
+ private static final ClientAuthenticationMethod JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD = new ClientAuthenticationMethod(
+ "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
+
private final Log logger = LogFactory.getLog(getClass());
+
private final RegisteredClientRepository registeredClientRepository;
+
private final CodeVerifierAuthenticator codeVerifierAuthenticator;
+
private JwtDecoderFactory jwtDecoderFactory;
/**
- * Constructs a {@code JwtClientAssertionAuthenticationProvider} using the provided parameters.
- *
+ * Constructs a {@code JwtClientAssertionAuthenticationProvider} using the provided
+ * parameters.
* @param registeredClientRepository the repository of registered clients
* @param authorizationService the authorization service
*/
@@ -75,8 +82,7 @@ public final class JwtClientAssertionAuthenticationProvider implements Authentic
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- OAuth2ClientAuthenticationToken clientAuthentication =
- (OAuth2ClientAuthenticationToken) authentication;
+ OAuth2ClientAuthenticationToken clientAuthentication = (OAuth2ClientAuthenticationToken) authentication;
if (!JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD.equals(clientAuthentication.getClientAuthenticationMethod())) {
return null;
@@ -107,7 +113,8 @@ public final class JwtClientAssertionAuthenticationProvider implements Authentic
JwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(registeredClient);
try {
jwtAssertion = jwtDecoder.decode(clientAuthentication.getCredentials().toString());
- } catch (JwtException ex) {
+ }
+ catch (JwtException ex) {
throwInvalidClient(OAuth2ParameterNames.CLIENT_ASSERTION, ex);
}
@@ -115,7 +122,8 @@ public final class JwtClientAssertionAuthenticationProvider implements Authentic
this.logger.trace("Validated client authentication parameters");
}
- // Validate the "code_verifier" parameter for the confidential client, if available
+ // Validate the "code_verifier" parameter for the confidential client, if
+ // available
this.codeVerifierAuthenticator.authenticateIfAvailable(clientAuthentication, registeredClient);
// @formatter:off
@@ -138,11 +146,12 @@ public final class JwtClientAssertionAuthenticationProvider implements Authentic
}
/**
- * Sets the {@link JwtDecoderFactory} that provides a {@link JwtDecoder} for the specified {@link RegisteredClient}
- * and is used for authenticating a {@link Jwt} Bearer Token during OAuth 2.0 Client Authentication.
- * The default factory is {@link JwtClientAssertionDecoderFactory}.
- *
- * @param jwtDecoderFactory the {@link JwtDecoderFactory} that provides a {@link JwtDecoder} for the specified {@link RegisteredClient}
+ * Sets the {@link JwtDecoderFactory} that provides a {@link JwtDecoder} for the
+ * specified {@link RegisteredClient} and is used for authenticating a {@link Jwt}
+ * Bearer Token during OAuth 2.0 Client Authentication. The default factory is
+ * {@link JwtClientAssertionDecoderFactory}.
+ * @param jwtDecoderFactory the {@link JwtDecoderFactory} that provides a
+ * {@link JwtDecoder} for the specified {@link RegisteredClient}
* @since 0.4.0
*/
public void setJwtDecoderFactory(JwtDecoderFactory jwtDecoderFactory) {
@@ -155,11 +164,8 @@ public final class JwtClientAssertionAuthenticationProvider implements Authentic
}
private static void throwInvalidClient(String parameterName, Throwable cause) {
- OAuth2Error error = new OAuth2Error(
- OAuth2ErrorCodes.INVALID_CLIENT,
- "Client authentication failed: " + parameterName,
- ERROR_URI
- );
+ OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT,
+ "Client authentication failed: " + parameterName, ERROR_URI);
throw new OAuth2AuthenticationException(error, error.toString(), cause);
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactory.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactory.java
index 3e49e7f4..c2e18ad6 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactory.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactory.java
@@ -56,8 +56,9 @@ import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
/**
- * A {@link JwtDecoderFactory factory} that provides a {@link JwtDecoder} for the specified {@link RegisteredClient}
- * and is used for authenticating a {@link Jwt} Bearer Token during OAuth 2.0 Client Authentication.
+ * A {@link JwtDecoderFactory factory} that provides a {@link JwtDecoder} for the
+ * specified {@link RegisteredClient} and is used for authenticating a {@link Jwt} Bearer
+ * Token during OAuth 2.0 Client Authentication.
*
* @author Rafal Lewczuk
* @author Joe Grandja
@@ -72,13 +73,16 @@ import org.springframework.web.util.UriComponentsBuilder;
public final class JwtClientAssertionDecoderFactory implements JwtDecoderFactory {
/**
- * The default {@code OAuth2TokenValidator} factory that validates the {@link JwtClaimNames#ISS iss},
- * {@link JwtClaimNames#SUB sub}, {@link JwtClaimNames#AUD aud}, {@link JwtClaimNames#EXP exp} and
- * {@link JwtClaimNames#NBF nbf} claims of the {@link Jwt} for the specified {@link RegisteredClient}.
+ * The default {@code OAuth2TokenValidator} factory that validates the
+ * {@link JwtClaimNames#ISS iss}, {@link JwtClaimNames#SUB sub},
+ * {@link JwtClaimNames#AUD aud}, {@link JwtClaimNames#EXP exp} and
+ * {@link JwtClaimNames#NBF nbf} claims of the {@link Jwt} for the specified
+ * {@link RegisteredClient}.
*/
public static final Function> DEFAULT_JWT_VALIDATOR_FACTORY = defaultJwtValidatorFactory();
private static final String JWT_CLIENT_AUTHENTICATION_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc7523#section-3";
+
private static final Map JCA_ALGORITHM_MAPPINGS;
static {
@@ -99,6 +103,7 @@ public final class JwtClientAssertionDecoderFactory implements JwtDecoderFactory
}
private final Map jwtDecoders = new ConcurrentHashMap<>();
+
private Function> jwtValidatorFactory = DEFAULT_JWT_VALIDATOR_FACTORY;
@Override
@@ -112,11 +117,12 @@ public final class JwtClientAssertionDecoderFactory implements JwtDecoderFactory
}
/**
- * Sets the factory that provides an {@link OAuth2TokenValidator}
- * for the specified {@link RegisteredClient} and is used by the {@link JwtDecoder}.
- * The default {@code OAuth2TokenValidator} factory is {@link #DEFAULT_JWT_VALIDATOR_FACTORY}.
- *
- * @param jwtValidatorFactory the factory that provides an {@link OAuth2TokenValidator} for the specified {@link RegisteredClient}
+ * Sets the factory that provides an {@link OAuth2TokenValidator} for the specified
+ * {@link RegisteredClient} and is used by the {@link JwtDecoder}. The default
+ * {@code OAuth2TokenValidator} factory is
+ * {@link #DEFAULT_JWT_VALIDATOR_FACTORY}.
+ * @param jwtValidatorFactory the factory that provides an
+ * {@link OAuth2TokenValidator} for the specified {@link RegisteredClient}
*/
public void setJwtValidatorFactory(Function> jwtValidatorFactory) {
Assert.notNull(jwtValidatorFactory, "jwtValidatorFactory cannot be null");
@@ -124,26 +130,27 @@ public final class JwtClientAssertionDecoderFactory implements JwtDecoderFactory
}
private static NimbusJwtDecoder buildDecoder(RegisteredClient registeredClient) {
- JwsAlgorithm jwsAlgorithm = registeredClient.getClientSettings().getTokenEndpointAuthenticationSigningAlgorithm();
+ JwsAlgorithm jwsAlgorithm = registeredClient.getClientSettings()
+ .getTokenEndpointAuthenticationSigningAlgorithm();
if (jwsAlgorithm instanceof SignatureAlgorithm) {
String jwkSetUrl = registeredClient.getClientSettings().getJwkSetUrl();
if (!StringUtils.hasText(jwkSetUrl)) {
OAuth2Error oauth2Error = new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT,
- "Failed to find a Signature Verifier for Client: '"
- + registeredClient.getId()
+ "Failed to find a Signature Verifier for Client: '" + registeredClient.getId()
+ "'. Check to ensure you have configured the JWK Set URL.",
JWT_CLIENT_AUTHENTICATION_ERROR_URI);
throw new OAuth2AuthenticationException(oauth2Error);
}
- return NimbusJwtDecoder.withJwkSetUri(jwkSetUrl).jwsAlgorithm((SignatureAlgorithm) jwsAlgorithm)
- .restOperations(restTemplate).build();
+ return NimbusJwtDecoder.withJwkSetUri(jwkSetUrl)
+ .jwsAlgorithm((SignatureAlgorithm) jwsAlgorithm)
+ .restOperations(restTemplate)
+ .build();
}
if (jwsAlgorithm instanceof MacAlgorithm) {
String clientSecret = registeredClient.getClientSecret();
if (!StringUtils.hasText(clientSecret)) {
OAuth2Error oauth2Error = new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT,
- "Failed to find a Signature Verifier for Client: '"
- + registeredClient.getId()
+ "Failed to find a Signature Verifier for Client: '" + registeredClient.getId()
+ "'. Check to ensure you have configured the client secret.",
JWT_CLIENT_AUTHENTICATION_ERROR_URI);
throw new OAuth2AuthenticationException(oauth2Error);
@@ -153,8 +160,7 @@ public final class JwtClientAssertionDecoderFactory implements JwtDecoderFactory
return NimbusJwtDecoder.withSecretKey(secretKeySpec).macAlgorithm((MacAlgorithm) jwsAlgorithm).build();
}
OAuth2Error oauth2Error = new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT,
- "Failed to find a Signature Verifier for Client: '"
- + registeredClient.getId()
+ "Failed to find a Signature Verifier for Client: '" + registeredClient.getId()
+ "'. Check to ensure you have configured a valid JWS Algorithm: '" + jwsAlgorithm + "'.",
JWT_CLIENT_AUTHENTICATION_ERROR_URI);
throw new OAuth2AuthenticationException(oauth2Error);
@@ -163,13 +169,10 @@ public final class JwtClientAssertionDecoderFactory implements JwtDecoderFactory
private static Function> defaultJwtValidatorFactory() {
return (registeredClient) -> {
String clientId = registeredClient.getClientId();
- return new DelegatingOAuth2TokenValidator<>(
- new JwtClaimValidator<>(JwtClaimNames.ISS, clientId::equals),
+ return new DelegatingOAuth2TokenValidator<>(new JwtClaimValidator<>(JwtClaimNames.ISS, clientId::equals),
new JwtClaimValidator<>(JwtClaimNames.SUB, clientId::equals),
new JwtClaimValidator<>(JwtClaimNames.AUD, containsAudience()),
- new JwtClaimValidator<>(JwtClaimNames.EXP, Objects::nonNull),
- new JwtTimestampValidator()
- );
+ new JwtClaimValidator<>(JwtClaimNames.EXP, Objects::nonNull), new JwtTimestampValidator());
};
}
@@ -194,12 +197,15 @@ public final class JwtClientAssertionDecoderFactory implements JwtDecoderFactory
return Collections.emptyList();
}
- AuthorizationServerSettings authorizationServerSettings = authorizationServerContext.getAuthorizationServerSettings();
+ AuthorizationServerSettings authorizationServerSettings = authorizationServerContext
+ .getAuthorizationServerSettings();
List audience = new ArrayList<>();
audience.add(authorizationServerContext.getIssuer());
audience.add(asUrl(authorizationServerContext.getIssuer(), authorizationServerSettings.getTokenEndpoint()));
- audience.add(asUrl(authorizationServerContext.getIssuer(), authorizationServerSettings.getTokenIntrospectionEndpoint()));
- audience.add(asUrl(authorizationServerContext.getIssuer(), authorizationServerSettings.getTokenRevocationEndpoint()));
+ audience.add(asUrl(authorizationServerContext.getIssuer(),
+ authorizationServerSettings.getTokenIntrospectionEndpoint()));
+ audience.add(asUrl(authorizationServerContext.getIssuer(),
+ authorizationServerSettings.getTokenRevocationEndpoint()));
return audience;
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationToken.java
index 6767c828..12797438 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationToken.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationToken.java
@@ -28,8 +28,8 @@ import org.springframework.security.oauth2.server.authorization.util.SpringAutho
import org.springframework.util.Assert;
/**
- * An {@link Authentication} implementation used when issuing an
- * OAuth 2.0 Access Token and (optional) Refresh Token.
+ * An {@link Authentication} implementation used when issuing an OAuth 2.0 Access Token
+ * and (optional) Refresh Token.
*
* @author Joe Grandja
* @author Madhu Bhat
@@ -41,28 +41,34 @@ import org.springframework.util.Assert;
* @see OAuth2ClientAuthenticationToken
*/
public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthenticationToken {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private final RegisteredClient registeredClient;
+
private final Authentication clientPrincipal;
+
private final OAuth2AccessToken accessToken;
+
private final OAuth2RefreshToken refreshToken;
+
private final Map additionalParameters;
/**
- * Constructs an {@code OAuth2AccessTokenAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AccessTokenAuthenticationToken} using the provided
+ * parameters.
* @param registeredClient the registered client
* @param clientPrincipal the authenticated client principal
* @param accessToken the access token
*/
- public OAuth2AccessTokenAuthenticationToken(RegisteredClient registeredClient,
- Authentication clientPrincipal, OAuth2AccessToken accessToken) {
+ public OAuth2AccessTokenAuthenticationToken(RegisteredClient registeredClient, Authentication clientPrincipal,
+ OAuth2AccessToken accessToken) {
this(registeredClient, clientPrincipal, accessToken, null);
}
/**
- * Constructs an {@code OAuth2AccessTokenAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AccessTokenAuthenticationToken} using the provided
+ * parameters.
* @param registeredClient the registered client
* @param clientPrincipal the authenticated client principal
* @param accessToken the access token
@@ -74,8 +80,8 @@ public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthentication
}
/**
- * Constructs an {@code OAuth2AccessTokenAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AccessTokenAuthenticationToken} using the provided
+ * parameters.
* @param registeredClient the registered client
* @param clientPrincipal the authenticated client principal
* @param accessToken the access token
@@ -83,7 +89,8 @@ public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthentication
* @param additionalParameters the additional parameters
*/
public OAuth2AccessTokenAuthenticationToken(RegisteredClient registeredClient, Authentication clientPrincipal,
- OAuth2AccessToken accessToken, @Nullable OAuth2RefreshToken refreshToken, Map additionalParameters) {
+ OAuth2AccessToken accessToken, @Nullable OAuth2RefreshToken refreshToken,
+ Map additionalParameters) {
super(Collections.emptyList());
Assert.notNull(registeredClient, "registeredClient cannot be null");
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
@@ -108,7 +115,6 @@ public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthentication
/**
* Returns the {@link RegisteredClient registered client}.
- *
* @return the {@link RegisteredClient}
*/
public RegisteredClient getRegisteredClient() {
@@ -117,7 +123,6 @@ public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthentication
/**
* Returns the {@link OAuth2AccessToken access token}.
- *
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
@@ -126,7 +131,6 @@ public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthentication
/**
* Returns the {@link OAuth2RefreshToken refresh token}.
- *
* @return the {@link OAuth2RefreshToken} or {@code null} if not available
*/
@Nullable
@@ -136,10 +140,10 @@ public class OAuth2AccessTokenAuthenticationToken extends AbstractAuthentication
/**
* Returns the additional parameters.
- *
* @return a {@code Map} of the additional parameters, may be empty
*/
public Map getAdditionalParameters() {
return this.additionalParameters;
}
+
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthenticationContext.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthenticationContext.java
index 58c3cbbe..12bc91d9 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthenticationContext.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthenticationContext.java
@@ -36,7 +36,6 @@ public interface OAuth2AuthenticationContext extends Context {
/**
* Returns the {@link Authentication} associated to the context.
- *
* @param the type of the {@code Authentication}
* @return the {@link Authentication}
*/
@@ -53,6 +52,7 @@ public interface OAuth2AuthenticationContext extends Context {
* @since 0.2.1
*/
abstract class AbstractBuilder> {
+
private final Map context = new HashMap<>();
protected AbstractBuilder(Authentication authentication) {
@@ -62,7 +62,6 @@ public interface OAuth2AuthenticationContext extends Context {
/**
* Associates an attribute.
- *
* @param key the key for the attribute
* @param value the value of the attribute
* @return the {@link AbstractBuilder} for further configuration
@@ -75,9 +74,8 @@ public interface OAuth2AuthenticationContext extends Context {
}
/**
- * A {@code Consumer} of the attributes {@code Map}
- * allowing the ability to add, replace, or remove.
- *
+ * A {@code Consumer} of the attributes {@code Map} allowing the ability to add,
+ * replace, or remove.
* @param contextConsumer a {@link Consumer} of the attributes {@code Map}
* @return the {@link AbstractBuilder} for further configuration
*/
@@ -102,7 +100,6 @@ public interface OAuth2AuthenticationContext extends Context {
/**
* Builds a new {@link OAuth2AuthenticationContext}.
- *
* @return the {@link OAuth2AuthenticationContext}
*/
public abstract T build();
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthenticationProviderUtils.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthenticationProviderUtils.java
index 97bc402f..2802e133 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthenticationProviderUtils.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthenticationProviderUtils.java
@@ -46,8 +46,7 @@ final class OAuth2AuthenticationProviderUtils {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
}
- static OAuth2Authorization invalidate(
- OAuth2Authorization authorization, T token) {
+ static OAuth2Authorization invalidate(OAuth2Authorization authorization, T token) {
// @formatter:off
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.from(authorization)
@@ -74,4 +73,5 @@ final class OAuth2AuthenticationProviderUtils {
return authorizationBuilder.build();
}
+
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java
index c2ef44c8..4de4aaaa 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java
@@ -67,7 +67,8 @@ import org.springframework.util.StringUtils;
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
/**
- * An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization Code Grant.
+ * An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization Code
+ * Grant.
*
* @author Joe Grandja
* @author Daniel Garnier-Moiroux
@@ -77,23 +78,32 @@ import static org.springframework.security.oauth2.server.authorization.authentic
* @see OAuth2AuthorizationCodeRequestAuthenticationProvider
* @see OAuth2AuthorizationService
* @see OAuth2TokenGenerator
- * @see Section 4.1 Authorization Code Grant
- * @see Section 4.1.3 Access Token Request
+ * @see Section 4.1 Authorization
+ * Code Grant
+ * @see Section 4.1.3 Access
+ * Token Request
*/
public final class OAuth2AuthorizationCodeAuthenticationProvider implements AuthenticationProvider {
+
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
- private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE =
- new OAuth2TokenType(OAuth2ParameterNames.CODE);
- private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE =
- new OAuth2TokenType(OidcParameterNames.ID_TOKEN);
+
+ private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.CODE);
+
+ private static final OAuth2TokenType ID_TOKEN_TOKEN_TYPE = new OAuth2TokenType(OidcParameterNames.ID_TOKEN);
+
private final Log logger = LogFactory.getLog(getClass());
+
private final OAuth2AuthorizationService authorizationService;
+
private final OAuth2TokenGenerator extends OAuth2Token> tokenGenerator;
+
private SessionRegistry sessionRegistry;
/**
- * Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the
+ * provided parameters.
* @param authorizationService the authorization service
* @param tokenGenerator the token generator
* @since 0.2.3
@@ -108,19 +118,18 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication =
- (OAuth2AuthorizationCodeAuthenticationToken) authentication;
+ OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
- OAuth2ClientAuthenticationToken clientPrincipal =
- getAuthenticatedClientElseThrowInvalidClient(authorizationCodeAuthentication);
+ OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
+ authorizationCodeAuthentication);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
if (this.logger.isTraceEnabled()) {
this.logger.trace("Retrieved registered client");
}
- OAuth2Authorization authorization = this.authorizationService.findByToken(
- authorizationCodeAuthentication.getCode(), AUTHORIZATION_CODE_TOKEN_TYPE);
+ OAuth2Authorization authorization = this.authorizationService
+ .findByToken(authorizationCodeAuthentication.getCode(), AUTHORIZATION_CODE_TOKEN_TYPE);
if (authorization == null) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
}
@@ -129,40 +138,45 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
this.logger.trace("Retrieved authorization with authorization code");
}
- OAuth2Authorization.Token authorizationCode =
- authorization.getToken(OAuth2AuthorizationCode.class);
+ OAuth2Authorization.Token authorizationCode = authorization
+ .getToken(OAuth2AuthorizationCode.class);
- OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(
- OAuth2AuthorizationRequest.class.getName());
+ OAuth2AuthorizationRequest authorizationRequest = authorization
+ .getAttribute(OAuth2AuthorizationRequest.class.getName());
if (!registeredClient.getClientId().equals(authorizationRequest.getClientId())) {
if (!authorizationCode.isInvalidated()) {
- // Invalidate the authorization code given that a different client is attempting to use it
- authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, authorizationCode.getToken());
+ // Invalidate the authorization code given that a different client is
+ // attempting to use it
+ authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization,
+ authorizationCode.getToken());
this.authorizationService.save(authorization);
if (this.logger.isWarnEnabled()) {
- this.logger.warn(LogMessage.format("Invalidated authorization code used by registered client '%s'", registeredClient.getId()));
+ this.logger.warn(LogMessage.format("Invalidated authorization code used by registered client '%s'",
+ registeredClient.getId()));
}
}
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
}
- if (StringUtils.hasText(authorizationRequest.getRedirectUri()) &&
- !authorizationRequest.getRedirectUri().equals(authorizationCodeAuthentication.getRedirectUri())) {
+ if (StringUtils.hasText(authorizationRequest.getRedirectUri())
+ && !authorizationRequest.getRedirectUri().equals(authorizationCodeAuthentication.getRedirectUri())) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
}
if (!authorizationCode.isActive()) {
if (authorizationCode.isInvalidated()) {
- OAuth2Authorization.Token extends OAuth2Token> token = authorization.getRefreshToken() != null ?
- authorization.getRefreshToken() :
- authorization.getAccessToken();
+ OAuth2Authorization.Token extends OAuth2Token> token = authorization.getRefreshToken() != null
+ ? authorization.getRefreshToken() : authorization.getAccessToken();
if (token != null) {
- // Invalidate the access (and refresh) token as the client is attempting to use the authorization code more than once
+ // Invalidate the access (and refresh) token as the client is
+ // attempting to use the authorization code more than once
authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, token.getToken());
this.authorizationService.save(authorization);
if (this.logger.isWarnEnabled()) {
- this.logger.warn(LogMessage.format("Invalidated authorization token(s) previously issued to registered client '%s'", registeredClient.getId()));
+ this.logger.warn(LogMessage.format(
+ "Invalidated authorization token(s) previously issued to registered client '%s'",
+ registeredClient.getId()));
}
}
}
@@ -205,17 +219,19 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
if (generatedAccessToken instanceof ClaimAccessor) {
- authorizationBuilder.token(accessToken, (metadata) ->
- metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims()));
- } else {
+ authorizationBuilder.token(accessToken,
+ (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME,
+ ((ClaimAccessor) generatedAccessToken).getClaims()));
+ }
+ else {
authorizationBuilder.accessToken(accessToken);
}
// ----- Refresh token -----
OAuth2RefreshToken refreshToken = null;
// Do not issue refresh token to public client
- if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) &&
- !clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
+ if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN)
+ && !clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
@@ -242,7 +258,8 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
// Compute (and use) hash for Session ID
sessionInformation = new SessionInformation(sessionInformation.getPrincipal(),
createHash(sessionInformation.getSessionId()), sessionInformation.getLastRequest());
- } catch (NoSuchAlgorithmException ex) {
+ }
+ catch (NoSuchAlgorithmException ex) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
"Failed to compute hash for Session ID.", ERROR_URI);
throw new OAuth2AuthenticationException(error);
@@ -268,9 +285,10 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
idToken = new OidcIdToken(generatedIdToken.getTokenValue(), generatedIdToken.getIssuedAt(),
generatedIdToken.getExpiresAt(), ((Jwt) generatedIdToken).getClaims());
- authorizationBuilder.token(idToken, (metadata) ->
- metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()));
- } else {
+ authorizationBuilder.token(idToken,
+ (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()));
+ }
+ else {
idToken = null;
}
@@ -295,8 +313,8 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
this.logger.trace("Authenticated token request");
}
- return new OAuth2AccessTokenAuthenticationToken(
- registeredClient, clientPrincipal, accessToken, refreshToken, additionalParameters);
+ return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken,
+ additionalParameters);
}
@Override
@@ -306,8 +324,8 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
/**
* Sets the {@link SessionRegistry} used to track OpenID Connect sessions.
- *
- * @param sessionRegistry the {@link SessionRegistry} used to track OpenID Connect sessions
+ * @param sessionRegistry the {@link SessionRegistry} used to track OpenID Connect
+ * sessions
* @since 1.1
*/
public void setSessionRegistry(SessionRegistry sessionRegistry) {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationToken.java
index 6f38750e..63e7c09d 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationToken.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationToken.java
@@ -23,7 +23,8 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.util.Assert;
/**
- * An {@link Authentication} implementation used for the OAuth 2.0 Authorization Code Grant.
+ * An {@link Authentication} implementation used for the OAuth 2.0 Authorization Code
+ * Grant.
*
* @author Joe Grandja
* @author Madhu Bhat
@@ -33,12 +34,14 @@ import org.springframework.util.Assert;
* @see OAuth2AuthorizationCodeAuthenticationProvider
*/
public class OAuth2AuthorizationCodeAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
+
private final String code;
+
private final String redirectUri;
/**
- * Constructs an {@code OAuth2AuthorizationCodeAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AuthorizationCodeAuthenticationToken} using the provided
+ * parameters.
* @param code the authorization code
* @param clientPrincipal the authenticated client principal
* @param redirectUri the redirect uri
@@ -54,7 +57,6 @@ public class OAuth2AuthorizationCodeAuthenticationToken extends OAuth2Authorizat
/**
* Returns the authorization code.
- *
* @return the authorization code
*/
public String getCode() {
@@ -63,11 +65,11 @@ public class OAuth2AuthorizationCodeAuthenticationToken extends OAuth2Authorizat
/**
* Returns the redirect uri.
- *
* @return the redirect uri
*/
@Nullable
public String getRedirectUri() {
return this.redirectUri;
}
+
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeGenerator.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeGenerator.java
index 9e5b6e28..aa051704 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeGenerator.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeGenerator.java
@@ -37,18 +37,19 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke
* @see OAuth2AuthorizationConsentAuthenticationProvider
*/
final class OAuth2AuthorizationCodeGenerator implements OAuth2TokenGenerator {
- private final StringKeyGenerator authorizationCodeGenerator =
- new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96);
+
+ private final StringKeyGenerator authorizationCodeGenerator = new Base64StringKeyGenerator(
+ Base64.getUrlEncoder().withoutPadding(), 96);
@Nullable
@Override
public OAuth2AuthorizationCode generate(OAuth2TokenContext context) {
- if (context.getTokenType() == null ||
- !OAuth2ParameterNames.CODE.equals(context.getTokenType().getValue())) {
+ if (context.getTokenType() == null || !OAuth2ParameterNames.CODE.equals(context.getTokenType().getValue())) {
return null;
}
Instant issuedAt = Instant.now();
- Instant expiresAt = issuedAt.plus(context.getRegisteredClient().getTokenSettings().getAuthorizationCodeTimeToLive());
+ Instant expiresAt = issuedAt
+ .plus(context.getRegisteredClient().getTokenSettings().getAuthorizationCodeTimeToLive());
return new OAuth2AuthorizationCode(this.authorizationCodeGenerator.generateKey(), issuedAt, expiresAt);
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationContext.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationContext.java
index c158d940..a60dc938 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationContext.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationContext.java
@@ -25,8 +25,10 @@ import org.springframework.security.oauth2.server.authorization.client.Registere
import org.springframework.util.Assert;
/**
- * An {@link OAuth2AuthenticationContext} that holds an {@link OAuth2AuthorizationCodeRequestAuthenticationToken} and additional information
- * and is used when validating the OAuth 2.0 Authorization Request used in the Authorization Code Grant.
+ * An {@link OAuth2AuthenticationContext} that holds an
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationToken} and additional information
+ * and is used when validating the OAuth 2.0 Authorization Request used in the
+ * Authorization Code Grant.
*
* @author Joe Grandja
* @since 0.4.0
@@ -35,6 +37,7 @@ import org.springframework.util.Assert;
* @see OAuth2AuthorizationCodeRequestAuthenticationProvider#setAuthenticationValidator(Consumer)
*/
public final class OAuth2AuthorizationCodeRequestAuthenticationContext implements OAuth2AuthenticationContext {
+
private final Map context;
private OAuth2AuthorizationCodeRequestAuthenticationContext(Map context) {
@@ -56,7 +59,6 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationContext implement
/**
* Returns the {@link RegisteredClient registered client}.
- *
* @return the {@link RegisteredClient}
*/
public RegisteredClient getRegisteredClient() {
@@ -64,8 +66,8 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationContext implement
}
/**
- * Constructs a new {@link Builder} with the provided {@link OAuth2AuthorizationCodeRequestAuthenticationToken}.
- *
+ * Constructs a new {@link Builder} with the provided
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationToken}.
* @param authentication the {@link OAuth2AuthorizationCodeRequestAuthenticationToken}
* @return the {@link Builder}
*/
@@ -76,7 +78,8 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationContext implement
/**
* A builder for {@link OAuth2AuthorizationCodeRequestAuthenticationContext}.
*/
- public static final class Builder extends AbstractBuilder {
+ public static final class Builder
+ extends AbstractBuilder {
private Builder(OAuth2AuthorizationCodeRequestAuthenticationToken authentication) {
super(authentication);
@@ -84,7 +87,6 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationContext implement
/**
* Sets the {@link RegisteredClient registered client}.
- *
* @param registeredClient the {@link RegisteredClient}
* @return the {@link Builder} for further configuration
*/
@@ -94,7 +96,6 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationContext implement
/**
* Builds a new {@link OAuth2AuthorizationCodeRequestAuthenticationContext}.
- *
* @return the {@link OAuth2AuthorizationCodeRequestAuthenticationContext}
*/
public OAuth2AuthorizationCodeRequestAuthenticationContext build() {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationException.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationException.java
index 8888ba29..36409cdb 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationException.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationException.java
@@ -21,8 +21,9 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
/**
- * This exception is thrown by {@link OAuth2AuthorizationCodeRequestAuthenticationProvider}
- * when an attempt to authenticate the OAuth 2.0 Authorization Request (or Consent) fails.
+ * This exception is thrown by
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationProvider} when an attempt to
+ * authenticate the OAuth 2.0 Authorization Request (or Consent) fails.
*
* @author Joe Grandja
* @since 0.1.2
@@ -30,13 +31,15 @@ import org.springframework.security.oauth2.core.OAuth2Error;
* @see OAuth2AuthorizationCodeRequestAuthenticationProvider
*/
public class OAuth2AuthorizationCodeRequestAuthenticationException extends OAuth2AuthenticationException {
+
private final OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication;
/**
- * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationException} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationException} using
+ * the provided parameters.
* @param error the {@link OAuth2Error OAuth 2.0 Error}
- * @param authorizationCodeRequestAuthentication the {@link Authentication} instance of the OAuth 2.0 Authorization Request (or Consent)
+ * @param authorizationCodeRequestAuthentication the {@link Authentication} instance
+ * of the OAuth 2.0 Authorization Request (or Consent)
*/
public OAuth2AuthorizationCodeRequestAuthenticationException(OAuth2Error error,
@Nullable OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication) {
@@ -45,11 +48,12 @@ public class OAuth2AuthorizationCodeRequestAuthenticationException extends OAuth
}
/**
- * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationException} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationException} using
+ * the provided parameters.
* @param error the {@link OAuth2Error OAuth 2.0 Error}
* @param cause the root cause
- * @param authorizationCodeRequestAuthentication the {@link Authentication} instance of the OAuth 2.0 Authorization Request (or Consent)
+ * @param authorizationCodeRequestAuthentication the {@link Authentication} instance
+ * of the OAuth 2.0 Authorization Request (or Consent)
*/
public OAuth2AuthorizationCodeRequestAuthenticationException(OAuth2Error error, Throwable cause,
@Nullable OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication) {
@@ -58,8 +62,8 @@ public class OAuth2AuthorizationCodeRequestAuthenticationException extends OAuth
}
/**
- * Returns the {@link Authentication} instance of the OAuth 2.0 Authorization Request (or Consent), or {@code null} if not available.
- *
+ * Returns the {@link Authentication} instance of the OAuth 2.0 Authorization Request
+ * (or Consent), or {@code null} if not available.
* @return the {@link OAuth2AuthorizationCodeRequestAuthenticationToken}
*/
@Nullable
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java
index aecc5b38..04db9883 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java
@@ -52,8 +52,8 @@ import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
- * An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization Request
- * used in the Authorization Code Grant.
+ * An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization
+ * Request used in the Authorization Code Grant.
*
* @author Joe Grandja
* @author Steve Riesenberg
@@ -65,30 +65,41 @@ import org.springframework.util.StringUtils;
* @see RegisteredClientRepository
* @see OAuth2AuthorizationService
* @see OAuth2AuthorizationConsentService
- * @see Section 4.1.1 Authorization Request
+ * @see Section 4.1.1
+ * Authorization Request
*/
public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implements AuthenticationProvider {
+
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1";
+
private static final String PKCE_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc7636#section-4.4.1";
- private static final StringKeyGenerator DEFAULT_STATE_GENERATOR =
- new Base64StringKeyGenerator(Base64.getUrlEncoder());
+
+ private static final StringKeyGenerator DEFAULT_STATE_GENERATOR = new Base64StringKeyGenerator(
+ Base64.getUrlEncoder());
+
private final Log logger = LogFactory.getLog(getClass());
+
private final RegisteredClientRepository registeredClientRepository;
+
private final OAuth2AuthorizationService authorizationService;
+
private final OAuth2AuthorizationConsentService authorizationConsentService;
+
private OAuth2TokenGenerator authorizationCodeGenerator = new OAuth2AuthorizationCodeGenerator();
- private Consumer authenticationValidator =
- new OAuth2AuthorizationCodeRequestAuthenticationValidator();
+
+ private Consumer authenticationValidator = new OAuth2AuthorizationCodeRequestAuthenticationValidator();
/**
- * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationProvider} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationProvider} using
+ * the provided parameters.
* @param registeredClientRepository the repository of registered clients
* @param authorizationService the authorization service
* @param authorizationConsentService the authorization consent service
*/
public OAuth2AuthorizationCodeRequestAuthenticationProvider(RegisteredClientRepository registeredClientRepository,
- OAuth2AuthorizationService authorizationService, OAuth2AuthorizationConsentService authorizationConsentService) {
+ OAuth2AuthorizationService authorizationService,
+ OAuth2AuthorizationConsentService authorizationConsentService) {
Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null");
Assert.notNull(authorizationService, "authorizationService cannot be null");
Assert.notNull(authorizationConsentService, "authorizationConsentService cannot be null");
@@ -99,11 +110,10 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication =
- (OAuth2AuthorizationCodeRequestAuthenticationToken) authentication;
+ OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = (OAuth2AuthorizationCodeRequestAuthenticationToken) authentication;
- RegisteredClient registeredClient = this.registeredClientRepository.findByClientId(
- authorizationCodeRequestAuthentication.getClientId());
+ RegisteredClient registeredClient = this.registeredClientRepository
+ .findByClientId(authorizationCodeRequestAuthentication.getClientId());
if (registeredClient == null) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID,
authorizationCodeRequestAuthentication, null);
@@ -113,10 +123,10 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
this.logger.trace("Retrieved registered client");
}
- OAuth2AuthorizationCodeRequestAuthenticationContext authenticationContext =
- OAuth2AuthorizationCodeRequestAuthenticationContext.with(authorizationCodeRequestAuthentication)
- .registeredClient(registeredClient)
- .build();
+ OAuth2AuthorizationCodeRequestAuthenticationContext authenticationContext = OAuth2AuthorizationCodeRequestAuthenticationContext
+ .with(authorizationCodeRequestAuthentication)
+ .registeredClient(registeredClient)
+ .build();
this.authenticationValidator.accept(authenticationContext);
if (!registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.AUTHORIZATION_CODE)) {
@@ -125,14 +135,17 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
}
// code_challenge (REQUIRED for public clients) - RFC 7636 (PKCE)
- String codeChallenge = (String) authorizationCodeRequestAuthentication.getAdditionalParameters().get(PkceParameterNames.CODE_CHALLENGE);
+ String codeChallenge = (String) authorizationCodeRequestAuthentication.getAdditionalParameters()
+ .get(PkceParameterNames.CODE_CHALLENGE);
if (StringUtils.hasText(codeChallenge)) {
- String codeChallengeMethod = (String) authorizationCodeRequestAuthentication.getAdditionalParameters().get(PkceParameterNames.CODE_CHALLENGE_METHOD);
+ String codeChallengeMethod = (String) authorizationCodeRequestAuthentication.getAdditionalParameters()
+ .get(PkceParameterNames.CODE_CHALLENGE_METHOD);
if (!StringUtils.hasText(codeChallengeMethod) || !"S256".equals(codeChallengeMethod)) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD, PKCE_ERROR_URI,
authorizationCodeRequestAuthentication, registeredClient, null);
}
- } else if (registeredClient.getClientSettings().isRequireProofKey()) {
+ }
+ else if (registeredClient.getClientSettings().isRequireProofKey()) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE, PKCE_ERROR_URI,
authorizationCodeRequestAuthentication, registeredClient, null);
}
@@ -155,22 +168,22 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
}
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
- .authorizationUri(authorizationCodeRequestAuthentication.getAuthorizationUri())
- .clientId(registeredClient.getClientId())
- .redirectUri(authorizationCodeRequestAuthentication.getRedirectUri())
- .scopes(authorizationCodeRequestAuthentication.getScopes())
- .state(authorizationCodeRequestAuthentication.getState())
- .additionalParameters(authorizationCodeRequestAuthentication.getAdditionalParameters())
- .build();
+ .authorizationUri(authorizationCodeRequestAuthentication.getAuthorizationUri())
+ .clientId(registeredClient.getClientId())
+ .redirectUri(authorizationCodeRequestAuthentication.getRedirectUri())
+ .scopes(authorizationCodeRequestAuthentication.getScopes())
+ .state(authorizationCodeRequestAuthentication.getState())
+ .additionalParameters(authorizationCodeRequestAuthentication.getAdditionalParameters())
+ .build();
- OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService.findById(
- registeredClient.getId(), principal.getName());
+ OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService
+ .findById(registeredClient.getId(), principal.getName());
if (requireAuthorizationConsent(registeredClient, authorizationRequest, currentAuthorizationConsent)) {
String state = DEFAULT_STATE_GENERATOR.generateKey();
OAuth2Authorization authorization = authorizationBuilder(registeredClient, principal, authorizationRequest)
- .attribute(OAuth2ParameterNames.STATE, state)
- .build();
+ .attribute(OAuth2ParameterNames.STATE, state)
+ .build();
if (this.logger.isTraceEnabled()) {
logger.trace("Generated authorization consent state");
@@ -178,8 +191,8 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
this.authorizationService.save(authorization);
- Set currentAuthorizedScopes = currentAuthorizationConsent != null ?
- currentAuthorizationConsent.getScopes() : null;
+ Set currentAuthorizedScopes = currentAuthorizationConsent != null
+ ? currentAuthorizationConsent.getScopes() : null;
if (this.logger.isTraceEnabled()) {
this.logger.trace("Saved authorization");
@@ -189,8 +202,8 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
registeredClient.getClientId(), principal, state, currentAuthorizedScopes, null);
}
- OAuth2TokenContext tokenContext = createAuthorizationCodeTokenContext(
- authorizationCodeRequestAuthentication, registeredClient, null, authorizationRequest.getScopes());
+ OAuth2TokenContext tokenContext = createAuthorizationCodeTokenContext(authorizationCodeRequestAuthentication,
+ registeredClient, null, authorizationRequest.getScopes());
OAuth2AuthorizationCode authorizationCode = this.authorizationCodeGenerator.generate(tokenContext);
if (authorizationCode == null) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
@@ -203,9 +216,9 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
}
OAuth2Authorization authorization = authorizationBuilder(registeredClient, principal, authorizationRequest)
- .authorizedScopes(authorizationRequest.getScopes())
- .token(authorizationCode)
- .build();
+ .authorizedScopes(authorizationRequest.getScopes())
+ .token(authorizationCode)
+ .build();
this.authorizationService.save(authorization);
if (this.logger.isTraceEnabled()) {
@@ -232,40 +245,47 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
}
/**
- * Sets the {@link OAuth2TokenGenerator} that generates the {@link OAuth2AuthorizationCode}.
- *
- * @param authorizationCodeGenerator the {@link OAuth2TokenGenerator} that generates the {@link OAuth2AuthorizationCode}
+ * Sets the {@link OAuth2TokenGenerator} that generates the
+ * {@link OAuth2AuthorizationCode}.
+ * @param authorizationCodeGenerator the {@link OAuth2TokenGenerator} that generates
+ * the {@link OAuth2AuthorizationCode}
* @since 0.2.3
*/
- public void setAuthorizationCodeGenerator(OAuth2TokenGenerator authorizationCodeGenerator) {
+ public void setAuthorizationCodeGenerator(
+ OAuth2TokenGenerator authorizationCodeGenerator) {
Assert.notNull(authorizationCodeGenerator, "authorizationCodeGenerator cannot be null");
this.authorizationCodeGenerator = authorizationCodeGenerator;
}
/**
- * Sets the {@code Consumer} providing access to the {@link OAuth2AuthorizationCodeRequestAuthenticationContext}
- * and is responsible for validating specific OAuth 2.0 Authorization Request parameters
- * associated in the {@link OAuth2AuthorizationCodeRequestAuthenticationToken}.
- * The default authentication validator is {@link OAuth2AuthorizationCodeRequestAuthenticationValidator}.
+ * Sets the {@code Consumer} providing access to the
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationContext} and is responsible for
+ * validating specific OAuth 2.0 Authorization Request parameters associated in the
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationToken}. The default
+ * authentication validator is
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationValidator}.
*
*
- * NOTE: The authentication validator MUST throw {@link OAuth2AuthorizationCodeRequestAuthenticationException} if validation fails.
- *
- * @param authenticationValidator the {@code Consumer} providing access to the {@link OAuth2AuthorizationCodeRequestAuthenticationContext} and is responsible for validating specific OAuth 2.0 Authorization Request parameters
+ * NOTE: The authentication validator MUST throw
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationException} if validation fails.
+ * @param authenticationValidator the {@code Consumer} providing access to the
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationContext} and is responsible for
+ * validating specific OAuth 2.0 Authorization Request parameters
* @since 0.4.0
*/
- public void setAuthenticationValidator(Consumer authenticationValidator) {
+ public void setAuthenticationValidator(
+ Consumer authenticationValidator) {
Assert.notNull(authenticationValidator, "authenticationValidator cannot be null");
this.authenticationValidator = authenticationValidator;
}
- private static OAuth2Authorization.Builder authorizationBuilder(RegisteredClient registeredClient, Authentication principal,
- OAuth2AuthorizationRequest authorizationRequest) {
+ private static OAuth2Authorization.Builder authorizationBuilder(RegisteredClient registeredClient,
+ Authentication principal, OAuth2AuthorizationRequest authorizationRequest) {
return OAuth2Authorization.withRegisteredClient(registeredClient)
- .principalName(principal.getName())
- .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
- .attribute(Principal.class.getName(), principal)
- .attribute(OAuth2AuthorizationRequest.class.getName(), authorizationRequest);
+ .principalName(principal.getName())
+ .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
+ .attribute(Principal.class.getName(), principal)
+ .attribute(OAuth2AuthorizationRequest.class.getName(), authorizationRequest);
}
private static OAuth2TokenContext createAuthorizationCodeTokenContext(
@@ -297,13 +317,13 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
return false;
}
// 'openid' scope does not require consent
- if (authorizationRequest.getScopes().contains(OidcScopes.OPENID) &&
- authorizationRequest.getScopes().size() == 1) {
+ if (authorizationRequest.getScopes().contains(OidcScopes.OPENID)
+ && authorizationRequest.getScopes().size() == 1) {
return false;
}
- if (authorizationConsent != null &&
- authorizationConsent.getScopes().containsAll(authorizationRequest.getScopes())) {
+ if (authorizationConsent != null
+ && authorizationConsent.getScopes().containsAll(authorizationRequest.getScopes())) {
return false;
}
@@ -311,9 +331,8 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
}
private static boolean isPrincipalAuthenticated(Authentication principal) {
- return principal != null &&
- !AnonymousAuthenticationToken.class.isAssignableFrom(principal.getClass()) &&
- principal.isAuthenticated();
+ return principal != null && !AnonymousAuthenticationToken.class.isAssignableFrom(principal.getClass())
+ && principal.isAuthenticated();
}
private static void throwError(String errorCode, String parameterName,
@@ -326,35 +345,39 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication,
RegisteredClient registeredClient, OAuth2AuthorizationRequest authorizationRequest) {
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
- throwError(error, parameterName, authorizationCodeRequestAuthentication, registeredClient, authorizationRequest);
+ throwError(error, parameterName, authorizationCodeRequestAuthentication, registeredClient,
+ authorizationRequest);
}
private static void throwError(OAuth2Error error, String parameterName,
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication,
RegisteredClient registeredClient, OAuth2AuthorizationRequest authorizationRequest) {
- String redirectUri = resolveRedirectUri(authorizationCodeRequestAuthentication, authorizationRequest, registeredClient);
- if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_REQUEST) &&
- (parameterName.equals(OAuth2ParameterNames.CLIENT_ID) ||
- parameterName.equals(OAuth2ParameterNames.STATE))) {
- redirectUri = null; // Prevent redirects
+ String redirectUri = resolveRedirectUri(authorizationCodeRequestAuthentication, authorizationRequest,
+ registeredClient);
+ if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_REQUEST)
+ && (parameterName.equals(OAuth2ParameterNames.CLIENT_ID)
+ || parameterName.equals(OAuth2ParameterNames.STATE))) {
+ redirectUri = null; // Prevent redirects
}
- OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult =
- new OAuth2AuthorizationCodeRequestAuthenticationToken(
- authorizationCodeRequestAuthentication.getAuthorizationUri(), authorizationCodeRequestAuthentication.getClientId(),
- (Authentication) authorizationCodeRequestAuthentication.getPrincipal(), redirectUri,
- authorizationCodeRequestAuthentication.getState(), authorizationCodeRequestAuthentication.getScopes(),
- authorizationCodeRequestAuthentication.getAdditionalParameters());
+ OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken(
+ authorizationCodeRequestAuthentication.getAuthorizationUri(),
+ authorizationCodeRequestAuthentication.getClientId(),
+ (Authentication) authorizationCodeRequestAuthentication.getPrincipal(), redirectUri,
+ authorizationCodeRequestAuthentication.getState(), authorizationCodeRequestAuthentication.getScopes(),
+ authorizationCodeRequestAuthentication.getAdditionalParameters());
- throw new OAuth2AuthorizationCodeRequestAuthenticationException(error, authorizationCodeRequestAuthenticationResult);
+ throw new OAuth2AuthorizationCodeRequestAuthenticationException(error,
+ authorizationCodeRequestAuthenticationResult);
}
private static String resolveRedirectUri(
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication,
OAuth2AuthorizationRequest authorizationRequest, RegisteredClient registeredClient) {
- if (authorizationCodeRequestAuthentication != null && StringUtils.hasText(authorizationCodeRequestAuthentication.getRedirectUri())) {
+ if (authorizationCodeRequestAuthentication != null
+ && StringUtils.hasText(authorizationCodeRequestAuthentication.getRedirectUri())) {
return authorizationCodeRequestAuthentication.getRedirectUri();
}
if (authorizationRequest != null && StringUtils.hasText(authorizationRequest.getRedirectUri())) {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationToken.java
index a7fab020..83cf1651 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationToken.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationToken.java
@@ -29,8 +29,8 @@ import org.springframework.security.oauth2.server.authorization.util.SpringAutho
import org.springframework.util.Assert;
/**
- * An {@link Authentication} implementation for the OAuth 2.0 Authorization Request
- * used in the Authorization Code Grant.
+ * An {@link Authentication} implementation for the OAuth 2.0 Authorization Request used
+ * in the Authorization Code Grant.
*
* @author Joe Grandja
* @since 0.1.2
@@ -38,19 +38,28 @@ import org.springframework.util.Assert;
* @see OAuth2AuthorizationConsentAuthenticationProvider
*/
public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractAuthenticationToken {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private final String authorizationUri;
+
private final String clientId;
+
private final Authentication principal;
+
private final String redirectUri;
+
private final String state;
+
private final Set scopes;
+
private final Map additionalParameters;
+
private final OAuth2AuthorizationCode authorizationCode;
/**
- * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationToken} using the
+ * provided parameters.
* @param authorizationUri the authorization URI
* @param clientId the client identifier
* @param principal the {@code Principal} (Resource Owner)
@@ -60,8 +69,9 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
* @param additionalParameters the additional parameters
* @since 0.4.0
*/
- public OAuth2AuthorizationCodeRequestAuthenticationToken(String authorizationUri, String clientId, Authentication principal,
- @Nullable String redirectUri, @Nullable String state, @Nullable Set scopes, @Nullable Map additionalParameters) {
+ public OAuth2AuthorizationCodeRequestAuthenticationToken(String authorizationUri, String clientId,
+ Authentication principal, @Nullable String redirectUri, @Nullable String state,
+ @Nullable Set scopes, @Nullable Map additionalParameters) {
super(Collections.emptyList());
Assert.hasText(authorizationUri, "authorizationUri cannot be empty");
Assert.hasText(clientId, "clientId cannot be empty");
@@ -71,20 +81,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
this.principal = principal;
this.redirectUri = redirectUri;
this.state = state;
- this.scopes = Collections.unmodifiableSet(
- scopes != null ?
- new HashSet<>(scopes) :
- Collections.emptySet());
+ this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
this.additionalParameters = Collections.unmodifiableMap(
- additionalParameters != null ?
- new HashMap<>(additionalParameters) :
- Collections.emptyMap());
+ additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
this.authorizationCode = null;
}
/**
- * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AuthorizationCodeRequestAuthenticationToken} using the
+ * provided parameters.
* @param authorizationUri the authorization URI
* @param clientId the client identifier
* @param principal the {@code Principal} (Resource Owner)
@@ -94,8 +99,9 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
* @param scopes the authorized scope(s)
* @since 0.4.0
*/
- public OAuth2AuthorizationCodeRequestAuthenticationToken(String authorizationUri, String clientId, Authentication principal,
- OAuth2AuthorizationCode authorizationCode, @Nullable String redirectUri, @Nullable String state, @Nullable Set scopes) {
+ public OAuth2AuthorizationCodeRequestAuthenticationToken(String authorizationUri, String clientId,
+ Authentication principal, OAuth2AuthorizationCode authorizationCode, @Nullable String redirectUri,
+ @Nullable String state, @Nullable Set scopes) {
super(Collections.emptyList());
Assert.hasText(authorizationUri, "authorizationUri cannot be empty");
Assert.hasText(clientId, "clientId cannot be empty");
@@ -107,10 +113,7 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
this.authorizationCode = authorizationCode;
this.redirectUri = redirectUri;
this.state = state;
- this.scopes = Collections.unmodifiableSet(
- scopes != null ?
- new HashSet<>(scopes) :
- Collections.emptySet());
+ this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
this.additionalParameters = Collections.emptyMap();
setAuthenticated(true);
}
@@ -127,7 +130,6 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
/**
* Returns the authorization URI.
- *
* @return the authorization URI
*/
public String getAuthorizationUri() {
@@ -136,7 +138,6 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
/**
* Returns the client identifier.
- *
* @return the client identifier
*/
public String getClientId() {
@@ -145,7 +146,6 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
/**
* Returns the redirect uri.
- *
* @return the redirect uri
*/
@Nullable
@@ -155,7 +155,6 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
/**
* Returns the state.
- *
* @return the state
*/
@Nullable
@@ -165,8 +164,8 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
/**
* Returns the requested (or authorized) scope(s).
- *
- * @return the requested (or authorized) scope(s), or an empty {@code Set} if not available
+ * @return the requested (or authorized) scope(s), or an empty {@code Set} if not
+ * available
*/
public Set getScopes() {
return this.scopes;
@@ -174,7 +173,6 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
/**
* Returns the additional parameters.
- *
* @return the additional parameters, or an empty {@code Map} if not available
*/
public Map getAdditionalParameters() {
@@ -183,7 +181,6 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
/**
* Returns the {@link OAuth2AuthorizationCode}.
- *
* @return the {@link OAuth2AuthorizationCode}
*/
@Nullable
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationValidator.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationValidator.java
index 2c8dc2ad..05f66096 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationValidator.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationValidator.java
@@ -29,15 +29,18 @@ import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
/**
- * A {@code Consumer} providing access to the {@link OAuth2AuthorizationCodeRequestAuthenticationContext}
- * containing an {@link OAuth2AuthorizationCodeRequestAuthenticationToken}
- * and is the default {@link OAuth2AuthorizationCodeRequestAuthenticationProvider#setAuthenticationValidator(Consumer) authentication validator}
- * used for validating specific OAuth 2.0 Authorization Request parameters used in the Authorization Code Grant.
+ * A {@code Consumer} providing access to the
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationContext} containing an
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationToken} and is the default
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationProvider#setAuthenticationValidator(Consumer)
+ * authentication validator} used for validating specific OAuth 2.0 Authorization Request
+ * parameters used in the Authorization Code Grant.
*
*
- * The default implementation first validates {@link OAuth2AuthorizationCodeRequestAuthenticationToken#getRedirectUri()}
- * and then {@link OAuth2AuthorizationCodeRequestAuthenticationToken#getScopes()}.
- * If validation fails, an {@link OAuth2AuthorizationCodeRequestAuthenticationException} is thrown.
+ * The default implementation first validates
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationToken#getRedirectUri()} and then
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationToken#getScopes()}. If validation
+ * fails, an {@link OAuth2AuthorizationCodeRequestAuthenticationException} is thrown.
*
* @author Joe Grandja
* @since 0.4.0
@@ -45,23 +48,25 @@ import org.springframework.web.util.UriComponentsBuilder;
* @see OAuth2AuthorizationCodeRequestAuthenticationToken
* @see OAuth2AuthorizationCodeRequestAuthenticationProvider#setAuthenticationValidator(Consumer)
*/
-public final class OAuth2AuthorizationCodeRequestAuthenticationValidator implements Consumer {
+public final class OAuth2AuthorizationCodeRequestAuthenticationValidator
+ implements Consumer {
+
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1";
/**
- * The default validator for {@link OAuth2AuthorizationCodeRequestAuthenticationToken#getScopes()}.
+ * The default validator for
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationToken#getScopes()}.
*/
- public static final Consumer DEFAULT_SCOPE_VALIDATOR =
- OAuth2AuthorizationCodeRequestAuthenticationValidator::validateScope;
+ public static final Consumer DEFAULT_SCOPE_VALIDATOR = OAuth2AuthorizationCodeRequestAuthenticationValidator::validateScope;
/**
- * The default validator for {@link OAuth2AuthorizationCodeRequestAuthenticationToken#getRedirectUri()}.
+ * The default validator for
+ * {@link OAuth2AuthorizationCodeRequestAuthenticationToken#getRedirectUri()}.
*/
- public static final Consumer DEFAULT_REDIRECT_URI_VALIDATOR =
- OAuth2AuthorizationCodeRequestAuthenticationValidator::validateRedirectUri;
+ public static final Consumer DEFAULT_REDIRECT_URI_VALIDATOR = OAuth2AuthorizationCodeRequestAuthenticationValidator::validateRedirectUri;
- private final Consumer authenticationValidator =
- DEFAULT_REDIRECT_URI_VALIDATOR.andThen(DEFAULT_SCOPE_VALIDATOR);
+ private final Consumer authenticationValidator = DEFAULT_REDIRECT_URI_VALIDATOR
+ .andThen(DEFAULT_SCOPE_VALIDATOR);
@Override
public void accept(OAuth2AuthorizationCodeRequestAuthenticationContext authenticationContext) {
@@ -69,8 +74,8 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationValidator impleme
}
private static void validateScope(OAuth2AuthorizationCodeRequestAuthenticationContext authenticationContext) {
- OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication =
- authenticationContext.getAuthentication();
+ OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = authenticationContext
+ .getAuthentication();
RegisteredClient registeredClient = authenticationContext.getRegisteredClient();
Set requestedScopes = authorizationCodeRequestAuthentication.getScopes();
@@ -82,8 +87,8 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationValidator impleme
}
private static void validateRedirectUri(OAuth2AuthorizationCodeRequestAuthenticationContext authenticationContext) {
- OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication =
- authenticationContext.getAuthentication();
+ OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = authenticationContext
+ .getAuthentication();
RegisteredClient registeredClient = authenticationContext.getRegisteredClient();
String requestedRedirectUri = authorizationCodeRequestAuthentication.getRedirectUri();
@@ -94,22 +99,27 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationValidator impleme
UriComponents requestedRedirect = null;
try {
requestedRedirect = UriComponentsBuilder.fromUriString(requestedRedirectUri).build();
- } catch (Exception ex) { }
+ }
+ catch (Exception ex) {
+ }
if (requestedRedirect == null || requestedRedirect.getFragment() != null) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI,
authorizationCodeRequestAuthentication, registeredClient);
}
if (!isLoopbackAddress(requestedRedirect.getHost())) {
- // As per https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-22#section-4.1.3
+ // As per
+ // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-22#section-4.1.3
// When comparing client redirect URIs against pre-registered URIs,
// authorization servers MUST utilize exact string matching.
if (!registeredClient.getRedirectUris().contains(requestedRedirectUri)) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI,
authorizationCodeRequestAuthentication, registeredClient);
}
- } else {
- // As per https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-08#section-8.4.2
+ }
+ else {
+ // As per
+ // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-08#section-8.4.2
// The authorization server MUST allow any port to be specified at the
// time of the request for loopback IP redirect URIs, to accommodate
// clients that obtain an available ephemeral port from the operating
@@ -129,11 +139,12 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationValidator impleme
}
}
- } else {
+ }
+ else {
// ***** redirect_uri is NOT available in authorization request
- if (authorizationCodeRequestAuthentication.getScopes().contains(OidcScopes.OPENID) ||
- registeredClient.getRedirectUris().size() != 1) {
+ if (authorizationCodeRequestAuthentication.getScopes().contains(OidcScopes.OPENID)
+ || registeredClient.getRedirectUris().size() != 1) {
// redirect_uri is REQUIRED for OpenID Connect
throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI,
authorizationCodeRequestAuthentication, registeredClient);
@@ -156,12 +167,13 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationValidator impleme
}
try {
int[] address = new int[ipv4Octets.length];
- for (int i=0; i < ipv4Octets.length; i++) {
+ for (int i = 0; i < ipv4Octets.length; i++) {
address[i] = Integer.parseInt(ipv4Octets[i]);
}
- return address[0] == 127 && address[1] >= 0 && address[1] <= 255 && address[2] >= 0 &&
- address[2] <= 255 && address[3] >= 1 && address[3] <= 255;
- } catch (NumberFormatException ex) {
+ return address[0] == 127 && address[1] >= 0 && address[1] <= 255 && address[2] >= 0 && address[2] <= 255
+ && address[3] >= 1 && address[3] <= 255;
+ }
+ catch (NumberFormatException ex) {
return false;
}
}
@@ -177,23 +189,24 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationValidator impleme
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication,
RegisteredClient registeredClient) {
- String redirectUri = StringUtils.hasText(authorizationCodeRequestAuthentication.getRedirectUri()) ?
- authorizationCodeRequestAuthentication.getRedirectUri() :
- registeredClient.getRedirectUris().iterator().next();
- if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_REQUEST) &&
- parameterName.equals(OAuth2ParameterNames.REDIRECT_URI)) {
- redirectUri = null; // Prevent redirects
+ String redirectUri = StringUtils.hasText(authorizationCodeRequestAuthentication.getRedirectUri())
+ ? authorizationCodeRequestAuthentication.getRedirectUri()
+ : registeredClient.getRedirectUris().iterator().next();
+ if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_REQUEST)
+ && parameterName.equals(OAuth2ParameterNames.REDIRECT_URI)) {
+ redirectUri = null; // Prevent redirects
}
- OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult =
- new OAuth2AuthorizationCodeRequestAuthenticationToken(
- authorizationCodeRequestAuthentication.getAuthorizationUri(), authorizationCodeRequestAuthentication.getClientId(),
- (Authentication) authorizationCodeRequestAuthentication.getPrincipal(), redirectUri,
- authorizationCodeRequestAuthentication.getState(), authorizationCodeRequestAuthentication.getScopes(),
- authorizationCodeRequestAuthentication.getAdditionalParameters());
+ OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken(
+ authorizationCodeRequestAuthentication.getAuthorizationUri(),
+ authorizationCodeRequestAuthentication.getClientId(),
+ (Authentication) authorizationCodeRequestAuthentication.getPrincipal(), redirectUri,
+ authorizationCodeRequestAuthentication.getState(), authorizationCodeRequestAuthentication.getScopes(),
+ authorizationCodeRequestAuthentication.getAdditionalParameters());
authorizationCodeRequestAuthenticationResult.setAuthenticated(true);
- throw new OAuth2AuthorizationCodeRequestAuthenticationException(error, authorizationCodeRequestAuthenticationResult);
+ throw new OAuth2AuthorizationCodeRequestAuthenticationException(error,
+ authorizationCodeRequestAuthenticationResult);
}
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContext.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContext.java
index a60f0398..aff7c9d3 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContext.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContext.java
@@ -29,8 +29,9 @@ import org.springframework.security.oauth2.server.authorization.client.Registere
import org.springframework.util.Assert;
/**
- * An {@link OAuth2AuthenticationContext} that holds an {@link OAuth2AuthorizationConsent.Builder} and additional information
- * and is used when customizing the building of the {@link OAuth2AuthorizationConsent}.
+ * An {@link OAuth2AuthenticationContext} that holds an
+ * {@link OAuth2AuthorizationConsent.Builder} and additional information and is used when
+ * customizing the building of the {@link OAuth2AuthorizationConsent}.
*
* @author Steve Riesenberg
* @author Joe Grandja
@@ -40,6 +41,7 @@ import org.springframework.util.Assert;
* @see OAuth2AuthorizationConsentAuthenticationProvider#setAuthorizationConsentCustomizer(Consumer)
*/
public final class OAuth2AuthorizationConsentAuthenticationContext implements OAuth2AuthenticationContext {
+
private final Map context;
private OAuth2AuthorizationConsentAuthenticationContext(Map context) {
@@ -60,8 +62,8 @@ public final class OAuth2AuthorizationConsentAuthenticationContext implements OA
}
/**
- * Returns the {@link OAuth2AuthorizationConsent.Builder authorization consent builder}.
- *
+ * Returns the {@link OAuth2AuthorizationConsent.Builder authorization consent
+ * builder}.
* @return the {@link OAuth2AuthorizationConsent.Builder}
*/
public OAuth2AuthorizationConsent.Builder getAuthorizationConsent() {
@@ -70,7 +72,6 @@ public final class OAuth2AuthorizationConsentAuthenticationContext implements OA
/**
* Returns the {@link RegisteredClient registered client}.
- *
* @return the {@link RegisteredClient}
*/
public RegisteredClient getRegisteredClient() {
@@ -79,7 +80,6 @@ public final class OAuth2AuthorizationConsentAuthenticationContext implements OA
/**
* Returns the {@link OAuth2Authorization authorization}.
- *
* @return the {@link OAuth2Authorization}
*/
public OAuth2Authorization getAuthorization() {
@@ -88,7 +88,6 @@ public final class OAuth2AuthorizationConsentAuthenticationContext implements OA
/**
* Returns the {@link OAuth2AuthorizationRequest authorization request}.
- *
* @return the {@link OAuth2AuthorizationRequest}
*/
public OAuth2AuthorizationRequest getAuthorizationRequest() {
@@ -96,8 +95,8 @@ public final class OAuth2AuthorizationConsentAuthenticationContext implements OA
}
/**
- * Constructs a new {@link Builder} with the provided {@link OAuth2AuthorizationConsentAuthenticationToken}.
- *
+ * Constructs a new {@link Builder} with the provided
+ * {@link OAuth2AuthorizationConsentAuthenticationToken}.
* @param authentication the {@link OAuth2AuthorizationConsentAuthenticationToken}
* @return the {@link Builder}
*/
@@ -108,15 +107,16 @@ public final class OAuth2AuthorizationConsentAuthenticationContext implements OA
/**
* A builder for {@link OAuth2AuthorizationConsentAuthenticationContext}.
*/
- public static final class Builder extends AbstractBuilder {
+ public static final class Builder
+ extends AbstractBuilder {
private Builder(OAuth2AuthorizationConsentAuthenticationToken authentication) {
super(authentication);
}
/**
- * Sets the {@link OAuth2AuthorizationConsent.Builder authorization consent builder}.
- *
+ * Sets the {@link OAuth2AuthorizationConsent.Builder authorization consent
+ * builder}.
* @param authorizationConsent the {@link OAuth2AuthorizationConsent.Builder}
* @return the {@link Builder} for further configuration
*/
@@ -126,7 +126,6 @@ public final class OAuth2AuthorizationConsentAuthenticationContext implements OA
/**
* Sets the {@link RegisteredClient registered client}.
- *
* @param registeredClient the {@link RegisteredClient}
* @return the {@link Builder} for further configuration
*/
@@ -136,7 +135,6 @@ public final class OAuth2AuthorizationConsentAuthenticationContext implements OA
/**
* Sets the {@link OAuth2Authorization authorization}.
- *
* @param authorization the {@link OAuth2Authorization}
* @return the {@link Builder} for further configuration
*/
@@ -146,7 +144,6 @@ public final class OAuth2AuthorizationConsentAuthenticationContext implements OA
/**
* Sets the {@link OAuth2AuthorizationRequest authorization request}.
- *
* @param authorizationRequest the {@link OAuth2AuthorizationRequest}
* @return the {@link Builder} for further configuration
*/
@@ -156,7 +153,6 @@ public final class OAuth2AuthorizationConsentAuthenticationContext implements OA
/**
* Builds a new {@link OAuth2AuthorizationConsentAuthenticationContext}.
- *
* @return the {@link OAuth2AuthorizationConsentAuthenticationContext}
*/
public OAuth2AuthorizationConsentAuthenticationContext build() {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProvider.java
index 8cdd789b..a644b636 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProvider.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProvider.java
@@ -50,8 +50,8 @@ import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
- * An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization Consent
- * used in the Authorization Code Grant.
+ * An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization
+ * Consent used in the Authorization Code Grant.
*
* @author Joe Grandja
* @since 0.4.0
@@ -63,24 +63,33 @@ import org.springframework.util.StringUtils;
* @see OAuth2AuthorizationConsentService
*/
public final class OAuth2AuthorizationConsentAuthenticationProvider implements AuthenticationProvider {
+
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1";
+
private static final OAuth2TokenType STATE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.STATE);
+
private final Log logger = LogFactory.getLog(getClass());
+
private final RegisteredClientRepository registeredClientRepository;
+
private final OAuth2AuthorizationService authorizationService;
+
private final OAuth2AuthorizationConsentService authorizationConsentService;
+
private OAuth2TokenGenerator authorizationCodeGenerator = new OAuth2AuthorizationCodeGenerator();
+
private Consumer authorizationConsentCustomizer;
/**
- * Constructs an {@code OAuth2AuthorizationConsentAuthenticationProvider} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AuthorizationConsentAuthenticationProvider} using the
+ * provided parameters.
* @param registeredClientRepository the repository of registered clients
* @param authorizationService the authorization service
* @param authorizationConsentService the authorization consent service
*/
public OAuth2AuthorizationConsentAuthenticationProvider(RegisteredClientRepository registeredClientRepository,
- OAuth2AuthorizationService authorizationService, OAuth2AuthorizationConsentService authorizationConsentService) {
+ OAuth2AuthorizationService authorizationService,
+ OAuth2AuthorizationConsentService authorizationConsentService) {
Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null");
Assert.notNull(authorizationService, "authorizationService cannot be null");
Assert.notNull(authorizationConsentService, "authorizationConsentService cannot be null");
@@ -92,19 +101,20 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (authentication instanceof OAuth2DeviceAuthorizationConsentAuthenticationToken) {
- // This is NOT an OAuth 2.0 Authorization Consent for the Authorization Code Grant,
- // return null and let OAuth2DeviceAuthorizationConsentAuthenticationProvider handle it instead
+ // This is NOT an OAuth 2.0 Authorization Consent for the Authorization Code
+ // Grant,
+ // return null and let OAuth2DeviceAuthorizationConsentAuthenticationProvider
+ // handle it instead
return null;
}
- OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthentication =
- (OAuth2AuthorizationConsentAuthenticationToken) authentication;
+ OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthentication = (OAuth2AuthorizationConsentAuthenticationToken) authentication;
- OAuth2Authorization authorization = this.authorizationService.findByToken(
- authorizationConsentAuthentication.getState(), STATE_TOKEN_TYPE);
+ OAuth2Authorization authorization = this.authorizationService
+ .findByToken(authorizationConsentAuthentication.getState(), STATE_TOKEN_TYPE);
if (authorization == null) {
- throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE,
- authorizationConsentAuthentication, null, null);
+ throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, authorizationConsentAuthentication,
+ null, null);
}
if (this.logger.isTraceEnabled()) {
@@ -114,12 +124,12 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
// The 'in-flight' authorization must be associated to the current principal
Authentication principal = (Authentication) authorizationConsentAuthentication.getPrincipal();
if (!isPrincipalAuthenticated(principal) || !principal.getName().equals(authorization.getPrincipalName())) {
- throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE,
- authorizationConsentAuthentication, null, null);
+ throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, authorizationConsentAuthentication,
+ null, null);
}
- RegisteredClient registeredClient = this.registeredClientRepository.findByClientId(
- authorizationConsentAuthentication.getClientId());
+ RegisteredClient registeredClient = this.registeredClientRepository
+ .findByClientId(authorizationConsentAuthentication.getClientId());
if (registeredClient == null || !registeredClient.getId().equals(authorization.getRegisteredClientId())) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID,
authorizationConsentAuthentication, registeredClient, null);
@@ -129,22 +139,23 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
this.logger.trace("Retrieved registered client");
}
- OAuth2AuthorizationRequest authorizationRequest = authorization.getAttribute(OAuth2AuthorizationRequest.class.getName());
+ OAuth2AuthorizationRequest authorizationRequest = authorization
+ .getAttribute(OAuth2AuthorizationRequest.class.getName());
Set requestedScopes = authorizationRequest.getScopes();
Set authorizedScopes = new HashSet<>(authorizationConsentAuthentication.getScopes());
if (!requestedScopes.containsAll(authorizedScopes)) {
- throwError(OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE,
- authorizationConsentAuthentication, registeredClient, authorizationRequest);
+ throwError(OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE, authorizationConsentAuthentication,
+ registeredClient, authorizationRequest);
}
if (this.logger.isTraceEnabled()) {
this.logger.trace("Validated authorization consent request parameters");
}
- OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService.findById(
- authorization.getRegisteredClientId(), authorization.getPrincipalName());
- Set currentAuthorizedScopes = currentAuthorizationConsent != null ?
- currentAuthorizationConsent.getScopes() : Collections.emptySet();
+ OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService
+ .findById(authorization.getRegisteredClientId(), authorization.getPrincipalName());
+ Set currentAuthorizedScopes = currentAuthorizationConsent != null
+ ? currentAuthorizationConsent.getScopes() : Collections.emptySet();
if (!currentAuthorizedScopes.isEmpty()) {
for (String requestedScope : requestedScopes) {
@@ -165,9 +176,10 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
this.logger.trace("Retrieved existing authorization consent");
}
authorizationConsentBuilder = OAuth2AuthorizationConsent.from(currentAuthorizationConsent);
- } else {
- authorizationConsentBuilder = OAuth2AuthorizationConsent.withId(
- authorization.getRegisteredClientId(), authorization.getPrincipalName());
+ }
+ else {
+ authorizationConsentBuilder = OAuth2AuthorizationConsent.withId(authorization.getRegisteredClientId(),
+ authorization.getPrincipalName());
}
authorizedScopes.forEach(authorizationConsentBuilder::scope);
@@ -214,8 +226,8 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
}
}
- OAuth2TokenContext tokenContext = createAuthorizationCodeTokenContext(
- authorizationConsentAuthentication, registeredClient, authorization, authorizedScopes);
+ OAuth2TokenContext tokenContext = createAuthorizationCodeTokenContext(authorizationConsentAuthentication,
+ registeredClient, authorization, authorizedScopes);
OAuth2AuthorizationCode authorizationCode = this.authorizationCodeGenerator.generate(tokenContext);
if (authorizationCode == null) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
@@ -228,12 +240,12 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
}
OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
- .authorizedScopes(authorizedScopes)
- .token(authorizationCode)
- .attributes(attrs -> {
- attrs.remove(OAuth2ParameterNames.STATE);
- })
- .build();
+ .authorizedScopes(authorizedScopes)
+ .token(authorizationCode)
+ .attributes(attrs -> {
+ attrs.remove(OAuth2ParameterNames.STATE);
+ })
+ .build();
this.authorizationService.save(updatedAuthorization);
if (this.logger.isTraceEnabled()) {
@@ -249,9 +261,9 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
this.logger.trace("Authenticated authorization consent request");
}
- return new OAuth2AuthorizationCodeRequestAuthenticationToken(
- authorizationRequest.getAuthorizationUri(), registeredClient.getClientId(), principal, authorizationCode,
- redirectUri, authorizationRequest.getState(), authorizedScopes);
+ return new OAuth2AuthorizationCodeRequestAuthenticationToken(authorizationRequest.getAuthorizationUri(),
+ registeredClient.getClientId(), principal, authorizationCode, redirectUri,
+ authorizationRequest.getState(), authorizedScopes);
}
@Override
@@ -260,36 +272,42 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
}
/**
- * Sets the {@link OAuth2TokenGenerator} that generates the {@link OAuth2AuthorizationCode}.
- *
- * @param authorizationCodeGenerator the {@link OAuth2TokenGenerator} that generates the {@link OAuth2AuthorizationCode}
+ * Sets the {@link OAuth2TokenGenerator} that generates the
+ * {@link OAuth2AuthorizationCode}.
+ * @param authorizationCodeGenerator the {@link OAuth2TokenGenerator} that generates
+ * the {@link OAuth2AuthorizationCode}
*/
- public void setAuthorizationCodeGenerator(OAuth2TokenGenerator authorizationCodeGenerator) {
+ public void setAuthorizationCodeGenerator(
+ OAuth2TokenGenerator authorizationCodeGenerator) {
Assert.notNull(authorizationCodeGenerator, "authorizationCodeGenerator cannot be null");
this.authorizationCodeGenerator = authorizationCodeGenerator;
}
/**
- * Sets the {@code Consumer} providing access to the {@link OAuth2AuthorizationConsentAuthenticationContext}
- * containing an {@link OAuth2AuthorizationConsent.Builder} and additional context information.
+ * Sets the {@code Consumer} providing access to the
+ * {@link OAuth2AuthorizationConsentAuthenticationContext} containing an
+ * {@link OAuth2AuthorizationConsent.Builder} and additional context information.
*
*
* The following context attributes are available:
*
- * The {@link OAuth2AuthorizationConsent.Builder} used to build the authorization consent
- * prior to {@link OAuth2AuthorizationConsentService#save(OAuth2AuthorizationConsent)}.
+ * The {@link OAuth2AuthorizationConsent.Builder} used to build the authorization
+ * consent prior to
+ * {@link OAuth2AuthorizationConsentService#save(OAuth2AuthorizationConsent)}.
* The {@link Authentication} of type
* {@link OAuth2AuthorizationConsentAuthenticationToken}.
* The {@link RegisteredClient} associated with the authorization request.
- * The {@link OAuth2Authorization} associated with the state token presented in the
- * authorization consent request.
- * The {@link OAuth2AuthorizationRequest} associated with the authorization consent request.
+ * The {@link OAuth2Authorization} associated with the state token presented in
+ * the authorization consent request.
+ * The {@link OAuth2AuthorizationRequest} associated with the authorization
+ * consent request.
*
- *
* @param authorizationConsentCustomizer the {@code Consumer} providing access to the
- * {@link OAuth2AuthorizationConsentAuthenticationContext} containing an {@link OAuth2AuthorizationConsent.Builder}
+ * {@link OAuth2AuthorizationConsentAuthenticationContext} containing an
+ * {@link OAuth2AuthorizationConsent.Builder}
*/
- public void setAuthorizationConsentCustomizer(Consumer authorizationConsentCustomizer) {
+ public void setAuthorizationConsentCustomizer(
+ Consumer authorizationConsentCustomizer) {
Assert.notNull(authorizationConsentCustomizer, "authorizationConsentCustomizer cannot be null");
this.authorizationConsentCustomizer = authorizationConsentCustomizer;
}
@@ -313,9 +331,8 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
}
private static boolean isPrincipalAuthenticated(Authentication principal) {
- return principal != null &&
- !AnonymousAuthenticationToken.class.isAssignableFrom(principal.getClass()) &&
- principal.isAuthenticated();
+ return principal != null && !AnonymousAuthenticationToken.class.isAssignableFrom(principal.getClass())
+ && principal.isAuthenticated();
}
private static void throwError(String errorCode, String parameterName,
@@ -330,29 +347,29 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
RegisteredClient registeredClient, OAuth2AuthorizationRequest authorizationRequest) {
String redirectUri = resolveRedirectUri(authorizationRequest, registeredClient);
- if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_REQUEST) &&
- (parameterName.equals(OAuth2ParameterNames.CLIENT_ID) ||
- parameterName.equals(OAuth2ParameterNames.STATE))) {
- redirectUri = null; // Prevent redirects
+ if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_REQUEST)
+ && (parameterName.equals(OAuth2ParameterNames.CLIENT_ID)
+ || parameterName.equals(OAuth2ParameterNames.STATE))) {
+ redirectUri = null; // Prevent redirects
}
- String state = authorizationRequest != null ?
- authorizationRequest.getState() :
- authorizationConsentAuthentication.getState();
- Set requestedScopes = authorizationRequest != null ?
- authorizationRequest.getScopes() :
- authorizationConsentAuthentication.getScopes();
+ String state = authorizationRequest != null ? authorizationRequest.getState()
+ : authorizationConsentAuthentication.getState();
+ Set requestedScopes = authorizationRequest != null ? authorizationRequest.getScopes()
+ : authorizationConsentAuthentication.getScopes();
- OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult =
- new OAuth2AuthorizationCodeRequestAuthenticationToken(
- authorizationConsentAuthentication.getAuthorizationUri(), authorizationConsentAuthentication.getClientId(),
- (Authentication) authorizationConsentAuthentication.getPrincipal(), redirectUri,
- state, requestedScopes, null);
+ OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken(
+ authorizationConsentAuthentication.getAuthorizationUri(),
+ authorizationConsentAuthentication.getClientId(),
+ (Authentication) authorizationConsentAuthentication.getPrincipal(), redirectUri, state, requestedScopes,
+ null);
- throw new OAuth2AuthorizationCodeRequestAuthenticationException(error, authorizationCodeRequestAuthenticationResult);
+ throw new OAuth2AuthorizationCodeRequestAuthenticationException(error,
+ authorizationCodeRequestAuthenticationResult);
}
- private static String resolveRedirectUri(OAuth2AuthorizationRequest authorizationRequest, RegisteredClient registeredClient) {
+ private static String resolveRedirectUri(OAuth2AuthorizationRequest authorizationRequest,
+ RegisteredClient registeredClient) {
if (authorizationRequest != null && StringUtils.hasText(authorizationRequest.getRedirectUri())) {
return authorizationRequest.getRedirectUri();
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationToken.java
index dd068d63..abe8fbc9 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationToken.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationToken.java
@@ -28,8 +28,8 @@ import org.springframework.security.oauth2.server.authorization.util.SpringAutho
import org.springframework.util.Assert;
/**
- * An {@link Authentication} implementation for the OAuth 2.0 Authorization Consent
- * used in the Authorization Code Grant.
+ * An {@link Authentication} implementation for the OAuth 2.0 Authorization Consent used
+ * in the Authorization Code Grant.
*
* @author Joe Grandja
* @since 0.4.0
@@ -37,17 +37,24 @@ import org.springframework.util.Assert;
* @see OAuth2AuthorizationCodeRequestAuthenticationProvider
*/
public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthenticationToken {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private final String authorizationUri;
+
private final String clientId;
+
private final Authentication principal;
+
private final String state;
+
private final Set scopes;
+
private final Map additionalParameters;
/**
- * Constructs an {@code OAuth2AuthorizationConsentAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2AuthorizationConsentAuthenticationToken} using the
+ * provided parameters.
* @param authorizationUri the authorization URI
* @param clientId the client identifier
* @param principal the {@code Principal} (Resource Owner)
@@ -55,8 +62,9 @@ public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthe
* @param scopes the requested (or authorized) scope(s)
* @param additionalParameters the additional parameters
*/
- public OAuth2AuthorizationConsentAuthenticationToken(String authorizationUri, String clientId, Authentication principal,
- String state, @Nullable Set scopes, @Nullable Map additionalParameters) {
+ public OAuth2AuthorizationConsentAuthenticationToken(String authorizationUri, String clientId,
+ Authentication principal, String state, @Nullable Set scopes,
+ @Nullable Map additionalParameters) {
super(Collections.emptyList());
Assert.hasText(authorizationUri, "authorizationUri cannot be empty");
Assert.hasText(clientId, "clientId cannot be empty");
@@ -66,14 +74,9 @@ public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthe
this.clientId = clientId;
this.principal = principal;
this.state = state;
- this.scopes = Collections.unmodifiableSet(
- scopes != null ?
- new HashSet<>(scopes) :
- Collections.emptySet());
+ this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
this.additionalParameters = Collections.unmodifiableMap(
- additionalParameters != null ?
- new HashMap<>(additionalParameters) :
- Collections.emptyMap());
+ additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
setAuthenticated(true);
}
@@ -89,7 +92,6 @@ public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthe
/**
* Returns the authorization URI.
- *
* @return the authorization URI
*/
public String getAuthorizationUri() {
@@ -98,7 +100,6 @@ public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthe
/**
* Returns the client identifier.
- *
* @return the client identifier
*/
public String getClientId() {
@@ -107,7 +108,6 @@ public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthe
/**
* Returns the state.
- *
* @return the state
*/
public String getState() {
@@ -116,8 +116,8 @@ public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthe
/**
* Returns the requested (or authorized) scope(s).
- *
- * @return the requested (or authorized) scope(s), or an empty {@code Set} if not available
+ * @return the requested (or authorized) scope(s), or an empty {@code Set} if not
+ * available
*/
public Set getScopes() {
return this.scopes;
@@ -125,7 +125,6 @@ public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthe
/**
* Returns the additional parameters.
- *
* @return the additional parameters, or an empty {@code Map} if not available
*/
public Map getAdditionalParameters() {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationGrantAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationGrantAuthenticationToken.java
index 659a85b5..59f4e4b5 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationGrantAuthenticationToken.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationGrantAuthenticationToken.java
@@ -27,24 +27,29 @@ import org.springframework.security.oauth2.server.authorization.util.SpringAutho
import org.springframework.util.Assert;
/**
- * Base implementation of an {@link Authentication} representing an OAuth 2.0 Authorization Grant.
+ * Base implementation of an {@link Authentication} representing an OAuth 2.0
+ * Authorization Grant.
*
* @author Joe Grandja
* @since 0.1.0
* @see AbstractAuthenticationToken
* @see AuthorizationGrantType
* @see OAuth2ClientAuthenticationToken
- * @see Section 1.3 Authorization Grant
+ * @see Section
+ * 1.3 Authorization Grant
*/
public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthenticationToken {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private final AuthorizationGrantType authorizationGrantType;
+
private final Authentication clientPrincipal;
+
private final Map additionalParameters;
/**
* Sub-class constructor.
- *
* @param authorizationGrantType the authorization grant type
* @param clientPrincipal the authenticated client principal
* @param additionalParameters the additional parameters
@@ -57,14 +62,11 @@ public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthent
this.authorizationGrantType = authorizationGrantType;
this.clientPrincipal = clientPrincipal;
this.additionalParameters = Collections.unmodifiableMap(
- additionalParameters != null ?
- new HashMap<>(additionalParameters) :
- Collections.emptyMap());
+ additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
}
/**
* Returns the authorization grant type.
- *
* @return the authorization grant type
*/
public AuthorizationGrantType getGrantType() {
@@ -83,10 +85,10 @@ public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthent
/**
* Returns the additional parameters.
- *
* @return the additional parameters
*/
public Map getAdditionalParameters() {
return this.additionalParameters;
}
+
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientAuthenticationToken.java
index 561d7901..cd898750 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientAuthenticationToken.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientAuthenticationToken.java
@@ -42,16 +42,22 @@ import org.springframework.util.Assert;
*/
@Transient
public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private final String clientId;
+
private final RegisteredClient registeredClient;
+
private final ClientAuthenticationMethod clientAuthenticationMethod;
+
private final Object credentials;
+
private final Map additionalParameters;
/**
- * Constructs an {@code OAuth2ClientAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2ClientAuthenticationToken} using the provided
+ * parameters.
* @param clientId the client identifier
* @param clientAuthenticationMethod the authentication method used by the client
* @param credentials the client credentials
@@ -66,19 +72,19 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken
this.registeredClient = null;
this.clientAuthenticationMethod = clientAuthenticationMethod;
this.credentials = credentials;
- this.additionalParameters = Collections.unmodifiableMap(
- additionalParameters != null ? additionalParameters : Collections.emptyMap());
+ this.additionalParameters = Collections
+ .unmodifiableMap(additionalParameters != null ? additionalParameters : Collections.emptyMap());
}
/**
- * Constructs an {@code OAuth2ClientAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2ClientAuthenticationToken} using the provided
+ * parameters.
* @param registeredClient the authenticated registered client
* @param clientAuthenticationMethod the authentication method used by the client
* @param credentials the client credentials
*/
- public OAuth2ClientAuthenticationToken(RegisteredClient registeredClient, ClientAuthenticationMethod clientAuthenticationMethod,
- @Nullable Object credentials) {
+ public OAuth2ClientAuthenticationToken(RegisteredClient registeredClient,
+ ClientAuthenticationMethod clientAuthenticationMethod, @Nullable Object credentials) {
super(Collections.emptyList());
Assert.notNull(registeredClient, "registeredClient cannot be null");
Assert.notNull(clientAuthenticationMethod, "clientAuthenticationMethod cannot be null");
@@ -102,9 +108,10 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken
}
/**
- * Returns the authenticated {@link RegisteredClient registered client}, or {@code null} if not authenticated.
- *
- * @return the authenticated {@link RegisteredClient}, or {@code null} if not authenticated
+ * Returns the authenticated {@link RegisteredClient registered client}, or
+ * {@code null} if not authenticated.
+ * @return the authenticated {@link RegisteredClient}, or {@code null} if not
+ * authenticated
*/
@Nullable
public RegisteredClient getRegisteredClient() {
@@ -112,8 +119,8 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken
}
/**
- * Returns the {@link ClientAuthenticationMethod authentication method} used by the client.
- *
+ * Returns the {@link ClientAuthenticationMethod authentication method} used by the
+ * client.
* @return the {@link ClientAuthenticationMethod} used by the client
*/
public ClientAuthenticationMethod getClientAuthenticationMethod() {
@@ -122,7 +129,6 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken
/**
* Returns the additional parameters.
- *
* @return the additional parameters
*/
public Map getAdditionalParameters() {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProvider.java
index dc0fcff1..c8fcf167 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProvider.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProvider.java
@@ -46,7 +46,8 @@ import org.springframework.util.CollectionUtils;
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
/**
- * An {@link AuthenticationProvider} implementation for the OAuth 2.0 Client Credentials Grant.
+ * An {@link AuthenticationProvider} implementation for the OAuth 2.0 Client Credentials
+ * Grant.
*
* @author Alexey Nesterov
* @author Joe Grandja
@@ -55,18 +56,26 @@ import static org.springframework.security.oauth2.server.authorization.authentic
* @see OAuth2AccessTokenAuthenticationToken
* @see OAuth2AuthorizationService
* @see OAuth2TokenGenerator
- * @see Section 4.4 Client Credentials Grant
- * @see Section 4.4.2 Access Token Request
+ * @see Section 4.4 Client
+ * Credentials Grant
+ * @see Section 4.4.2 Access
+ * Token Request
*/
public final class OAuth2ClientCredentialsAuthenticationProvider implements AuthenticationProvider {
+
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
+
private final Log logger = LogFactory.getLog(getClass());
+
private final OAuth2AuthorizationService authorizationService;
+
private final OAuth2TokenGenerator extends OAuth2Token> tokenGenerator;
/**
- * Constructs an {@code OAuth2ClientCredentialsAuthenticationProvider} using the provided parameters.
- *
+ * Constructs an {@code OAuth2ClientCredentialsAuthenticationProvider} using the
+ * provided parameters.
* @param authorizationService the authorization service
* @param tokenGenerator the token generator
* @since 0.2.3
@@ -81,11 +90,10 @@ public final class OAuth2ClientCredentialsAuthenticationProvider implements Auth
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication =
- (OAuth2ClientCredentialsAuthenticationToken) authentication;
+ OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication = (OAuth2ClientCredentialsAuthenticationToken) authentication;
- OAuth2ClientAuthenticationToken clientPrincipal =
- getAuthenticatedClientElseThrowInvalidClient(clientCredentialsAuthentication);
+ OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
+ clientCredentialsAuthentication);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
if (this.logger.isTraceEnabled()) {
@@ -144,9 +152,11 @@ public final class OAuth2ClientCredentialsAuthenticationProvider implements Auth
.authorizedScopes(authorizedScopes);
// @formatter:on
if (generatedAccessToken instanceof ClaimAccessor) {
- authorizationBuilder.token(accessToken, (metadata) ->
- metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims()));
- } else {
+ authorizationBuilder.token(accessToken,
+ (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME,
+ ((ClaimAccessor) generatedAccessToken).getClaims()));
+ }
+ else {
authorizationBuilder.accessToken(accessToken);
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationToken.java
index 83849489..59ef7d3a 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationToken.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationToken.java
@@ -25,7 +25,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
/**
- * An {@link Authentication} implementation used for the OAuth 2.0 Client Credentials Grant.
+ * An {@link Authentication} implementation used for the OAuth 2.0 Client Credentials
+ * Grant.
*
* @author Alexey Nesterov
* @since 0.0.1
@@ -33,28 +34,28 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
* @see OAuth2ClientCredentialsAuthenticationProvider
*/
public class OAuth2ClientCredentialsAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
+
private final Set scopes;
/**
- * Constructs an {@code OAuth2ClientCredentialsAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2ClientCredentialsAuthenticationToken} using the provided
+ * parameters.
* @param clientPrincipal the authenticated client principal
* @param scopes the requested scope(s)
* @param additionalParameters the additional parameters
*/
- public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal,
- @Nullable Set scopes, @Nullable Map additionalParameters) {
+ public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal, @Nullable Set scopes,
+ @Nullable Map additionalParameters) {
super(AuthorizationGrantType.CLIENT_CREDENTIALS, clientPrincipal, additionalParameters);
- this.scopes = Collections.unmodifiableSet(
- scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
+ this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
}
/**
* Returns the requested scope(s).
- *
* @return the requested scope(s), or an empty {@code Set} if not available
*/
public Set getScopes() {
return this.scopes;
}
+
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProvider.java
index a3cc37aa..38f15c7b 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProvider.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProvider.java
@@ -64,20 +64,23 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
static final OAuth2TokenType STATE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.STATE);
private final Log logger = LogFactory.getLog(getClass());
+
private final RegisteredClientRepository registeredClientRepository;
+
private final OAuth2AuthorizationService authorizationService;
+
private final OAuth2AuthorizationConsentService authorizationConsentService;
+
private Consumer authorizationConsentCustomizer;
/**
- * Constructs an {@code OAuth2DeviceAuthorizationConsentAuthenticationProvider} using the provided parameters.
- *
+ * Constructs an {@code OAuth2DeviceAuthorizationConsentAuthenticationProvider} using
+ * the provided parameters.
* @param registeredClientRepository the repository of registered clients
* @param authorizationService the authorization service
* @param authorizationConsentService the authorization consent service
*/
- public OAuth2DeviceAuthorizationConsentAuthenticationProvider(
- RegisteredClientRepository registeredClientRepository,
+ public OAuth2DeviceAuthorizationConsentAuthenticationProvider(RegisteredClientRepository registeredClientRepository,
OAuth2AuthorizationService authorizationService,
OAuth2AuthorizationConsentService authorizationConsentService) {
Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null");
@@ -90,11 +93,10 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- OAuth2DeviceAuthorizationConsentAuthenticationToken deviceAuthorizationConsentAuthentication =
- (OAuth2DeviceAuthorizationConsentAuthenticationToken) authentication;
+ OAuth2DeviceAuthorizationConsentAuthenticationToken deviceAuthorizationConsentAuthentication = (OAuth2DeviceAuthorizationConsentAuthenticationToken) authentication;
- OAuth2Authorization authorization = this.authorizationService.findByToken(
- deviceAuthorizationConsentAuthentication.getState(), STATE_TOKEN_TYPE);
+ OAuth2Authorization authorization = this.authorizationService
+ .findByToken(deviceAuthorizationConsentAuthentication.getState(), STATE_TOKEN_TYPE);
if (authorization == null) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE);
}
@@ -109,8 +111,8 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE);
}
- RegisteredClient registeredClient = this.registeredClientRepository.findByClientId(
- deviceAuthorizationConsentAuthentication.getClientId());
+ RegisteredClient registeredClient = this.registeredClientRepository
+ .findByClientId(deviceAuthorizationConsentAuthentication.getClientId());
if (registeredClient == null || !registeredClient.getId().equals(authorization.getRegisteredClientId())) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID);
}
@@ -129,10 +131,10 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
this.logger.trace("Validated device authorization consent request parameters");
}
- OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService.findById(
- authorization.getRegisteredClientId(), principal.getName());
- Set currentAuthorizedScopes = currentAuthorizationConsent != null ?
- currentAuthorizationConsent.getScopes() : Collections.emptySet();
+ OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService
+ .findById(authorization.getRegisteredClientId(), principal.getName());
+ Set currentAuthorizedScopes = currentAuthorizationConsent != null
+ ? currentAuthorizationConsent.getScopes() : Collections.emptySet();
if (!currentAuthorizedScopes.isEmpty()) {
for (String requestedScope : requestedScopes) {
@@ -148,9 +150,10 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
this.logger.trace("Retrieved existing authorization consent");
}
authorizationConsentBuilder = OAuth2AuthorizationConsent.from(currentAuthorizationConsent);
- } else {
- authorizationConsentBuilder = OAuth2AuthorizationConsent.withId(
- authorization.getRegisteredClientId(), principal.getName());
+ }
+ else {
+ authorizationConsentBuilder = OAuth2AuthorizationConsent.withId(authorization.getRegisteredClientId(),
+ principal.getName());
}
authorizedScopes.forEach(authorizationConsentBuilder::scope);
@@ -184,12 +187,12 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
}
}
authorization = OAuth2Authorization.from(authorization)
- .token(deviceCodeToken.getToken(), metadata ->
- metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
- .token(userCodeToken.getToken(), metadata ->
- metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
- .attributes(attrs -> attrs.remove(OAuth2ParameterNames.STATE))
- .build();
+ .token(deviceCodeToken.getToken(),
+ metadata -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
+ .token(userCodeToken.getToken(),
+ metadata -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
+ .attributes(attrs -> attrs.remove(OAuth2ParameterNames.STATE))
+ .build();
this.authorizationService.save(authorization);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Invalidated device code and user code because authorization consent was denied");
@@ -206,12 +209,12 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
}
authorization = OAuth2Authorization.from(authorization)
- .authorizedScopes(authorizedScopes)
- .token(userCodeToken.getToken(), metadata ->
- metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
- .attributes(attrs -> attrs.remove(OAuth2ParameterNames.STATE))
- .attributes(attrs -> attrs.remove(OAuth2ParameterNames.SCOPE))
- .build();
+ .authorizedScopes(authorizedScopes)
+ .token(userCodeToken.getToken(),
+ metadata -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
+ .attributes(attrs -> attrs.remove(OAuth2ParameterNames.STATE))
+ .attributes(attrs -> attrs.remove(OAuth2ParameterNames.SCOPE))
+ .build();
this.authorizationService.save(authorization);
if (this.logger.isTraceEnabled()) {
@@ -230,33 +233,36 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
}
/**
- * Sets the {@code Consumer} providing access to the {@link OAuth2AuthorizationConsentAuthenticationContext}
- * containing an {@link OAuth2AuthorizationConsent.Builder} and additional context information.
+ * Sets the {@code Consumer} providing access to the
+ * {@link OAuth2AuthorizationConsentAuthenticationContext} containing an
+ * {@link OAuth2AuthorizationConsent.Builder} and additional context information.
*
*
* The following context attributes are available:
*
- * The {@link OAuth2AuthorizationConsent.Builder} used to build the authorization consent
- * prior to {@link OAuth2AuthorizationConsentService#save(OAuth2AuthorizationConsent)}.
+ * The {@link OAuth2AuthorizationConsent.Builder} used to build the authorization
+ * consent prior to
+ * {@link OAuth2AuthorizationConsentService#save(OAuth2AuthorizationConsent)}.
* The {@link Authentication} of type
* {@link OAuth2DeviceAuthorizationConsentAuthenticationToken}.
- * The {@link RegisteredClient} associated with the device authorization request.
- * The {@link OAuth2Authorization} associated with the state token presented in the
- * device authorization consent request.
+ * The {@link RegisteredClient} associated with the device authorization
+ * request.
+ * The {@link OAuth2Authorization} associated with the state token presented in
+ * the device authorization consent request.
*
- *
* @param authorizationConsentCustomizer the {@code Consumer} providing access to the
- * {@link OAuth2AuthorizationConsentAuthenticationContext} containing an {@link OAuth2AuthorizationConsent.Builder}
+ * {@link OAuth2AuthorizationConsentAuthenticationContext} containing an
+ * {@link OAuth2AuthorizationConsent.Builder}
*/
- public void setAuthorizationConsentCustomizer(Consumer authorizationConsentCustomizer) {
+ public void setAuthorizationConsentCustomizer(
+ Consumer authorizationConsentCustomizer) {
Assert.notNull(authorizationConsentCustomizer, "authorizationConsentCustomizer cannot be null");
this.authorizationConsentCustomizer = authorizationConsentCustomizer;
}
private static boolean isPrincipalAuthenticated(Authentication principal) {
- return principal != null &&
- !AnonymousAuthenticationToken.class.isAssignableFrom(principal.getClass()) &&
- principal.isAuthenticated();
+ return principal != null && !AnonymousAuthenticationToken.class.isAssignableFrom(principal.getClass())
+ && principal.isAuthenticated();
}
private static void throwError(String errorCode, String parameterName) {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationToken.java
index fbfe3d35..12d34272 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationToken.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationToken.java
@@ -27,8 +27,8 @@ import org.springframework.security.oauth2.server.authorization.util.SpringAutho
import org.springframework.util.Assert;
/**
- * An {@link Authentication} implementation for the Device Authorization Consent used
- * in the OAuth 2.0 Device Authorization Grant.
+ * An {@link Authentication} implementation for the Device Authorization Consent used in
+ * the OAuth 2.0 Device Authorization Grant.
*
* @author Steve Riesenberg
* @since 1.1
@@ -36,13 +36,16 @@ import org.springframework.util.Assert;
* @see OAuth2DeviceAuthorizationConsentAuthenticationProvider
*/
public class OAuth2DeviceAuthorizationConsentAuthenticationToken extends OAuth2AuthorizationConsentAuthenticationToken {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private final String userCode;
+
private final Set requestedScopes;
/**
- * Constructs an {@code OAuth2DeviceAuthorizationConsentAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2DeviceAuthorizationConsentAuthenticationToken} using the
+ * provided parameters.
* @param authorizationUri the authorization URI
* @param clientId the client identifier
* @param principal the {@code Principal} (Resource Owner)
@@ -62,8 +65,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationToken extends OAuth2A
}
/**
- * Constructs an {@code OAuth2DeviceAuthorizationConsentAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2DeviceAuthorizationConsentAuthenticationToken} using the
+ * provided parameters.
* @param authorizationUri the authorization URI
* @param clientId the client identifier
* @param principal the {@code Principal} (Resource Owner)
@@ -78,16 +81,13 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationToken extends OAuth2A
super(authorizationUri, clientId, principal, state, authorizedScopes, null);
Assert.hasText(userCode, "userCode cannot be empty");
this.userCode = userCode;
- this.requestedScopes = Collections.unmodifiableSet(
- requestedScopes != null ?
- new HashSet<>(requestedScopes) :
- Collections.emptySet());
+ this.requestedScopes = Collections
+ .unmodifiableSet(requestedScopes != null ? new HashSet<>(requestedScopes) : Collections.emptySet());
setAuthenticated(true);
}
/**
* Returns the user code.
- *
* @return the user code
*/
public String getUserCode() {
@@ -96,7 +96,6 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationToken extends OAuth2A
/**
* Returns the requested scopes.
- *
* @return the requested scopes
*/
public Set getRequestedScopes() {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProvider.java
index d21ed9c4..610c7c46 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProvider.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProvider.java
@@ -63,8 +63,11 @@ import static org.springframework.security.oauth2.server.authorization.authentic
* @see OAuth2DeviceCodeAuthenticationProvider
* @see OAuth2AuthorizationService
* @see OAuth2TokenGenerator
- * @see OAuth 2.0 Device Authorization Grant
- * @see Section 3.1 Device Authorization Request
+ * @see OAuth 2.0
+ * Device Authorization Grant
+ * @see Section 3.1 Device
+ * Authorization Request
*/
public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implements AuthenticationProvider {
@@ -73,13 +76,16 @@ public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implem
static final OAuth2TokenType USER_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.USER_CODE);
private final Log logger = LogFactory.getLog(getClass());
+
private final OAuth2AuthorizationService authorizationService;
+
private OAuth2TokenGenerator deviceCodeGenerator = new OAuth2DeviceCodeGenerator();
+
private OAuth2TokenGenerator userCodeGenerator = new OAuth2UserCodeGenerator();
/**
- * Constructs an {@code OAuth2DeviceAuthorizationRequestAuthenticationProvider} using the provided parameters.
- *
+ * Constructs an {@code OAuth2DeviceAuthorizationRequestAuthenticationProvider} using
+ * the provided parameters.
* @param authorizationService the authorization service
*/
public OAuth2DeviceAuthorizationRequestAuthenticationProvider(OAuth2AuthorizationService authorizationService) {
@@ -89,11 +95,10 @@ public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implem
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- OAuth2DeviceAuthorizationRequestAuthenticationToken deviceAuthorizationRequestAuthentication =
- (OAuth2DeviceAuthorizationRequestAuthenticationToken) authentication;
+ OAuth2DeviceAuthorizationRequestAuthenticationToken deviceAuthorizationRequestAuthentication = (OAuth2DeviceAuthorizationRequestAuthenticationToken) authentication;
- OAuth2ClientAuthenticationToken clientPrincipal =
- getAuthenticatedClientElseThrowInvalidClient(deviceAuthorizationRequestAuthentication);
+ OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
+ deviceAuthorizationRequestAuthentication);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
if (this.logger.isTraceEnabled()) {
@@ -171,8 +176,8 @@ public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implem
this.logger.trace("Authenticated device authorization request");
}
- return new OAuth2DeviceAuthorizationRequestAuthenticationToken(
- clientPrincipal, requestedScopes, deviceCode, userCode);
+ return new OAuth2DeviceAuthorizationRequestAuthenticationToken(clientPrincipal, requestedScopes, deviceCode,
+ userCode);
}
@Override
@@ -182,8 +187,8 @@ public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implem
/**
* Sets the {@link OAuth2TokenGenerator} that generates the {@link OAuth2DeviceCode}.
- *
- * @param deviceCodeGenerator the {@link OAuth2TokenGenerator} that generates the {@link OAuth2DeviceCode}
+ * @param deviceCodeGenerator the {@link OAuth2TokenGenerator} that generates the
+ * {@link OAuth2DeviceCode}
*/
public void setDeviceCodeGenerator(OAuth2TokenGenerator deviceCodeGenerator) {
Assert.notNull(deviceCodeGenerator, "deviceCodeGenerator cannot be null");
@@ -192,8 +197,8 @@ public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implem
/**
* Sets the {@link OAuth2TokenGenerator} that generates the {@link OAuth2UserCode}.
- *
- * @param userCodeGenerator the {@link OAuth2TokenGenerator} that generates the {@link OAuth2UserCode}
+ * @param userCodeGenerator the {@link OAuth2TokenGenerator} that generates the
+ * {@link OAuth2UserCode}
*/
public void setUserCodeGenerator(OAuth2TokenGenerator userCodeGenerator) {
Assert.notNull(userCodeGenerator, "userCodeGenerator cannot be null");
@@ -207,18 +212,19 @@ public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implem
private static final class OAuth2DeviceCodeGenerator implements OAuth2TokenGenerator {
- private final StringKeyGenerator deviceCodeGenerator =
- new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96);
+ private final StringKeyGenerator deviceCodeGenerator = new Base64StringKeyGenerator(
+ Base64.getUrlEncoder().withoutPadding(), 96);
@Nullable
@Override
public OAuth2DeviceCode generate(OAuth2TokenContext context) {
- if (context.getTokenType() == null ||
- !OAuth2ParameterNames.DEVICE_CODE.equals(context.getTokenType().getValue())) {
+ if (context.getTokenType() == null
+ || !OAuth2ParameterNames.DEVICE_CODE.equals(context.getTokenType().getValue())) {
return null;
}
Instant issuedAt = Instant.now();
- Instant expiresAt = issuedAt.plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
+ Instant expiresAt = issuedAt
+ .plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
return new OAuth2DeviceCode(this.deviceCodeGenerator.generateKey(), issuedAt, expiresAt);
}
@@ -256,12 +262,13 @@ public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implem
@Nullable
@Override
public OAuth2UserCode generate(OAuth2TokenContext context) {
- if (context.getTokenType() == null ||
- !OAuth2ParameterNames.USER_CODE.equals(context.getTokenType().getValue())) {
+ if (context.getTokenType() == null
+ || !OAuth2ParameterNames.USER_CODE.equals(context.getTokenType().getValue())) {
return null;
}
Instant issuedAt = Instant.now();
- Instant expiresAt = issuedAt.plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
+ Instant expiresAt = issuedAt
+ .plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
return new OAuth2UserCode(this.userCodeGenerator.generateKey(), issuedAt, expiresAt);
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationToken.java
index c80d9b64..7d4a7e91 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationToken.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationToken.java
@@ -30,8 +30,8 @@ import org.springframework.security.oauth2.server.authorization.util.SpringAutho
import org.springframework.util.Assert;
/**
- * An {@link Authentication} implementation for the Device Authorization Request
- * used in the OAuth 2.0 Device Authorization Grant.
+ * An {@link Authentication} implementation for the Device Authorization Request used in
+ * the OAuth 2.0 Device Authorization Grant.
*
* @author Steve Riesenberg
* @since 1.1
@@ -40,17 +40,24 @@ import org.springframework.util.Assert;
* @see OAuth2DeviceAuthorizationRequestAuthenticationProvider
*/
public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends AbstractAuthenticationToken {
+
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
+
private final Authentication clientPrincipal;
+
private final String authorizationUri;
+
private final Set scopes;
+
private final OAuth2DeviceCode deviceCode;
+
private final OAuth2UserCode userCode;
+
private final Map additionalParameters;
/**
- * Constructs an {@code OAuth2DeviceAuthorizationRequestAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2DeviceAuthorizationRequestAuthenticationToken} using the
+ * provided parameters.
* @param clientPrincipal the authenticated client principal
* @param authorizationUri the authorization {@code URI}
* @param scopes the requested scope(s)
@@ -63,37 +70,29 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac
Assert.hasText(authorizationUri, "authorizationUri cannot be empty");
this.clientPrincipal = clientPrincipal;
this.authorizationUri = authorizationUri;
- this.scopes = Collections.unmodifiableSet(
- scopes != null ?
- new HashSet<>(scopes) :
- Collections.emptySet());
+ this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
this.additionalParameters = Collections.unmodifiableMap(
- additionalParameters != null ?
- new HashMap<>(additionalParameters) :
- Collections.emptyMap());
+ additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
this.deviceCode = null;
this.userCode = null;
}
/**
- * Constructs an {@code OAuth2DeviceAuthorizationRequestAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2DeviceAuthorizationRequestAuthenticationToken} using the
+ * provided parameters.
* @param clientPrincipal the authenticated client principal
* @param scopes the requested scope(s)
* @param deviceCode the {@link OAuth2DeviceCode}
* @param userCode the {@link OAuth2UserCode}
*/
- public OAuth2DeviceAuthorizationRequestAuthenticationToken(Authentication clientPrincipal, @Nullable Set scopes,
- OAuth2DeviceCode deviceCode, OAuth2UserCode userCode) {
+ public OAuth2DeviceAuthorizationRequestAuthenticationToken(Authentication clientPrincipal,
+ @Nullable Set scopes, OAuth2DeviceCode deviceCode, OAuth2UserCode userCode) {
super(Collections.emptyList());
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
Assert.notNull(deviceCode, "deviceCode cannot be null");
Assert.notNull(userCode, "userCode cannot be null");
this.clientPrincipal = clientPrincipal;
- this.scopes = Collections.unmodifiableSet(
- scopes != null ?
- new HashSet<>(scopes) :
- Collections.emptySet());
+ this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
this.deviceCode = deviceCode;
this.userCode = userCode;
this.authorizationUri = null;
@@ -113,7 +112,6 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac
/**
* Returns the authorization {@code URI}.
- *
* @return the authorization {@code URI}
*/
public String getAuthorizationUri() {
@@ -122,7 +120,6 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac
/**
* Returns the requested scope(s).
- *
* @return the requested scope(s)
*/
public Set getScopes() {
@@ -131,7 +128,6 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac
/**
* Returns the device code.
- *
* @return the device code
*/
public OAuth2DeviceCode getDeviceCode() {
@@ -140,7 +136,6 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac
/**
* Returns the user code.
- *
* @return the user code
*/
public OAuth2UserCode getUserCode() {
@@ -149,7 +144,6 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac
/**
* Returns the additional parameters.
- *
* @return the additional parameters
*/
public Map getAdditionalParameters() {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProvider.java
index 5e08ea54..6e5b51be 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProvider.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProvider.java
@@ -60,30 +60,37 @@ import static org.springframework.security.oauth2.server.authorization.authentic
* @see OAuth2DeviceAuthorizationConsentAuthenticationProvider
* @see OAuth2AuthorizationService
* @see OAuth2TokenGenerator
- * @see OAuth 2.0 Device Authorization Grant
- * @see Section 3.4 Device Access Token Request
- * @see Section 3.5 Device Access Token Response
+ * @see OAuth 2.0
+ * Device Authorization Grant
+ * @see Section 3.4 Device Access
+ * Token Request
+ * @see Section 3.5 Device Access
+ * Token Response
*/
public final class OAuth2DeviceCodeAuthenticationProvider implements AuthenticationProvider {
private static final String DEFAULT_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
+
private static final String DEVICE_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc8628#section-3.5";
static final OAuth2TokenType DEVICE_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.DEVICE_CODE);
static final String EXPIRED_TOKEN = "expired_token";
static final String AUTHORIZATION_PENDING = "authorization_pending";
private final Log logger = LogFactory.getLog(getClass());
+
private final OAuth2AuthorizationService authorizationService;
+
private final OAuth2TokenGenerator extends OAuth2Token> tokenGenerator;
/**
- * Constructs an {@code OAuth2DeviceCodeAuthenticationProvider} using the provided parameters.
- *
+ * Constructs an {@code OAuth2DeviceCodeAuthenticationProvider} using the provided
+ * parameters.
* @param authorizationService the authorization service
* @param tokenGenerator the token generator
*/
- public OAuth2DeviceCodeAuthenticationProvider(
- OAuth2AuthorizationService authorizationService,
+ public OAuth2DeviceCodeAuthenticationProvider(OAuth2AuthorizationService authorizationService,
OAuth2TokenGenerator extends OAuth2Token> tokenGenerator) {
Assert.notNull(authorizationService, "authorizationService cannot be null");
Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
@@ -93,19 +100,18 @@ public final class OAuth2DeviceCodeAuthenticationProvider implements Authenticat
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- OAuth2DeviceCodeAuthenticationToken deviceCodeAuthentication =
- (OAuth2DeviceCodeAuthenticationToken) authentication;
+ OAuth2DeviceCodeAuthenticationToken deviceCodeAuthentication = (OAuth2DeviceCodeAuthenticationToken) authentication;
- OAuth2ClientAuthenticationToken clientPrincipal =
- getAuthenticatedClientElseThrowInvalidClient(deviceCodeAuthentication);
+ OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
+ deviceCodeAuthentication);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
if (this.logger.isTraceEnabled()) {
this.logger.trace("Retrieved registered client");
}
- OAuth2Authorization authorization = this.authorizationService.findByToken(
- deviceCodeAuthentication.getDeviceCode(), DEVICE_CODE_TOKEN_TYPE);
+ OAuth2Authorization authorization = this.authorizationService
+ .findByToken(deviceCodeAuthentication.getDeviceCode(), DEVICE_CODE_TOKEN_TYPE);
if (authorization == null) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
}
@@ -119,12 +125,13 @@ public final class OAuth2DeviceCodeAuthenticationProvider implements Authenticat
if (!registeredClient.getId().equals(authorization.getRegisteredClientId())) {
if (!deviceCode.isInvalidated()) {
- // Invalidate the device code given that a different client is attempting to use it
+ // Invalidate the device code given that a different client is attempting
+ // to use it
authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, deviceCode.getToken());
this.authorizationService.save(authorization);
if (this.logger.isWarnEnabled()) {
- this.logger.warn(LogMessage.format(
- "Invalidated device code used by registered client '%s'", authorization.getRegisteredClientId()));
+ this.logger.warn(LogMessage.format("Invalidated device code used by registered client '%s'",
+ authorization.getRegisteredClientId()));
}
}
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
@@ -133,46 +140,46 @@ public final class OAuth2DeviceCodeAuthenticationProvider implements Authenticat
// In https://www.rfc-editor.org/rfc/rfc8628.html#section-3.5,
// the following error codes are defined:
- // authorization_pending
- // The authorization request is still pending as the end user hasn't
- // yet completed the user-interaction steps (Section 3.3). The
- // client SHOULD repeat the access token request to the token
- // endpoint (a process known as polling). Before each new request,
- // the client MUST wait at least the number of seconds specified by
- // the "interval" parameter of the device authorization response (see
- // Section 3.2), or 5 seconds if none was provided, and respect any
- // increase in the polling interval required by the "slow_down"
- // error.
+ // authorization_pending
+ // The authorization request is still pending as the end user hasn't
+ // yet completed the user-interaction steps (Section 3.3). The
+ // client SHOULD repeat the access token request to the token
+ // endpoint (a process known as polling). Before each new request,
+ // the client MUST wait at least the number of seconds specified by
+ // the "interval" parameter of the device authorization response (see
+ // Section 3.2), or 5 seconds if none was provided, and respect any
+ // increase in the polling interval required by the "slow_down"
+ // error.
if (!userCode.isInvalidated()) {
OAuth2Error error = new OAuth2Error(AUTHORIZATION_PENDING, null, DEVICE_ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
- // slow_down
- // A variant of "authorization_pending", the authorization request is
- // still pending and polling should continue, but the interval MUST
- // be increased by 5 seconds for this and all subsequent requests.
- // NOTE: This error is not handled in the framework.
+ // slow_down
+ // A variant of "authorization_pending", the authorization request is
+ // still pending and polling should continue, but the interval MUST
+ // be increased by 5 seconds for this and all subsequent requests.
+ // NOTE: This error is not handled in the framework.
- // access_denied
- // The authorization request was denied.
+ // access_denied
+ // The authorization request was denied.
if (deviceCode.isInvalidated()) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED, null, DEVICE_ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
- // expired_token
- // The "device_code" has expired, and the device authorization
- // session has concluded. The client MAY commence a new device
- // authorization request but SHOULD wait for user interaction before
- // restarting to avoid unnecessary polling.
+ // expired_token
+ // The "device_code" has expired, and the device authorization
+ // session has concluded. The client MAY commence a new device
+ // authorization request but SHOULD wait for user interaction before
+ // restarting to avoid unnecessary polling.
if (deviceCode.isExpired()) {
// Invalidate the device code
authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, deviceCode.getToken());
this.authorizationService.save(authorization);
if (this.logger.isWarnEnabled()) {
- this.logger.warn(LogMessage.format(
- "Invalidated device code used by registered client '%s'", authorization.getRegisteredClientId()));
+ this.logger.warn(LogMessage.format("Invalidated device code used by registered client '%s'",
+ authorization.getRegisteredClientId()));
}
OAuth2Error error = new OAuth2Error(EXPIRED_TOKEN, null, DEVICE_ERROR_URI);
throw new OAuth2AuthenticationException(error);
@@ -217,9 +224,11 @@ public final class OAuth2DeviceCodeAuthenticationProvider implements Authenticat
generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
if (generatedAccessToken instanceof ClaimAccessor) {
- authorizationBuilder.token(accessToken, (metadata) ->
- metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims()));
- } else {
+ authorizationBuilder.token(accessToken,
+ (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME,
+ ((ClaimAccessor) generatedAccessToken).getClaims()));
+ }
+ else {
authorizationBuilder.accessToken(accessToken);
}
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationToken.java
index 29f7cfdf..5ca6196a 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationToken.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationToken.java
@@ -23,8 +23,8 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.util.Assert;
/**
- * An {@link Authentication} implementation for the Device Access Token Request
- * used in the OAuth 2.0 Device Authorization Grant.
+ * An {@link Authentication} implementation for the Device Access Token Request used in
+ * the OAuth 2.0 Device Authorization Grant.
*
* @author Steve Riesenberg
* @since 1.1
@@ -36,8 +36,8 @@ public class OAuth2DeviceCodeAuthenticationToken extends OAuth2AuthorizationGran
private final String deviceCode;
/**
- * Constructs an {@code OAuth2DeviceCodeAuthenticationToken} using the provided parameters.
- *
+ * Constructs an {@code OAuth2DeviceCodeAuthenticationToken} using the provided
+ * parameters.
* @param deviceCode the device code
* @param clientPrincipal the authenticated client principal
* @param additionalParameters the additional parameters
@@ -51,7 +51,6 @@ public class OAuth2DeviceCodeAuthenticationToken extends OAuth2AuthorizationGran
/**
* Returns the device code.
- *
* @return the device code
*/
public String getDeviceCode() {
diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProvider.java
index d0b0c2e9..519dbe1a 100644
--- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProvider.java
+++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProvider.java
@@ -56,29 +56,35 @@ import org.springframework.util.Assert;
* @see RegisteredClientRepository
* @see OAuth2AuthorizationService
* @see OAuth2AuthorizationConsentService
- * @see OAuth 2.0 Device Authorization Grant
- * @see Section 3.3 User Interaction
+ * @see OAuth 2.0
+ * Device Authorization Grant
+ * @see Section 3.3 User
+ * Interaction
*/
public final class OAuth2DeviceVerificationAuthenticationProvider implements AuthenticationProvider {
static final OAuth2TokenType USER_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.USER_CODE);
- private static final StringKeyGenerator DEFAULT_STATE_GENERATOR =
- new Base64StringKeyGenerator(Base64.getUrlEncoder());
+
+ private static final StringKeyGenerator DEFAULT_STATE_GENERATOR = new Base64StringKeyGenerator(
+ Base64.getUrlEncoder());
private final Log logger = LogFactory.getLog(getClass());
+
private final RegisteredClientRepository registeredClientRepository;
+
private final OAuth2AuthorizationService authorizationService;
+
private final OAuth2AuthorizationConsentService authorizationConsentService;
/**
- * Constructs an {@code OAuth2DeviceVerificationAuthenticationProvider} using the provided parameters.
- *
+ * Constructs an {@code OAuth2DeviceVerificationAuthenticationProvider} using the
+ * provided parameters.
* @param registeredClientRepository the repository of registered clients
* @param authorizationService the authorization service
* @param authorizationConsentService the authorization consent service
*/
- public OAuth2DeviceVerificationAuthenticationProvider(
- RegisteredClientRepository registeredClientRepository,
+ public OAuth2DeviceVerificationAuthenticationProvider(RegisteredClientRepository registeredClientRepository,
OAuth2AuthorizationService authorizationService,
OAuth2AuthorizationConsentService authorizationConsentService) {
Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null");
@@ -91,11 +97,10 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- OAuth2DeviceVerificationAuthenticationToken deviceVerificationAuthentication =
- (OAuth2DeviceVerificationAuthenticationToken) authentication;
+ OAuth2DeviceVerificationAuthenticationToken deviceVerificationAuthentication = (OAuth2DeviceVerificationAuthenticationToken) authentication;
- OAuth2Authorization authorization = this.authorizationService.findByToken(
- deviceVerificationAuthentication.getUserCode(), USER_CODE_TOKEN_TYPE);
+ OAuth2Authorization authorization = this.authorizationService
+ .findByToken(deviceVerificationAuthentication.getUserCode(), USER_CODE_TOKEN_TYPE);
if (authorization == null) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_GRANT);
}
@@ -109,12 +114,13 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut
if (this.logger.isTraceEnabled()) {
this.logger.trace("Did not authenticate device verification request since principal not authenticated");
}
- // Return the device verification request as-is where isAuthenticated() is false
+ // Return the device verification request as-is where isAuthenticated() is
+ // false
return deviceVerificationAuthentication;
}
- RegisteredClient registeredClient = this.registeredClientRepository.findById(
- authorization.getRegisteredClientId());
+ RegisteredClient registeredClient = this.registeredClientRepository
+ .findById(authorization.getRegisteredClientId());
if (this.logger.isTraceEnabled()) {
this.logger.trace("Retrieved registered client");
@@ -122,16 +128,16 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut
Set requestedScopes = authorization.getAttribute(OAuth2ParameterNames.SCOPE);
- OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService.findById(
- registeredClient.getId(), principal.getName());
+ OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService
+ .findById(registeredClient.getId(), principal.getName());
if (requiresAuthorizationConsent(requestedScopes, currentAuthorizationConsent)) {
String state = DEFAULT_STATE_GENERATOR.generateKey();
authorization = OAuth2Authorization.from(authorization)
- .principalName(principal.getName())
- .attribute(Principal.class.getName(), principal)
- .attribute(OAuth2ParameterNames.STATE, state)
- .build();
+ .principalName(principal.getName())
+ .attribute(Principal.class.getName(), principal)
+ .attribute(OAuth2ParameterNames.STATE, state)
+ .build();
if (this.logger.isTraceEnabled()) {
this.logger.trace("Generated device authorization consent state");
@@ -143,11 +149,11 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut
this.logger.trace("Saved authorization");
}
- Set currentAuthorizedScopes = currentAuthorizationConsent != null ?
- currentAuthorizationConsent.getScopes() : null;
+ Set currentAuthorizedScopes = currentAuthorizationConsent != null
+ ? currentAuthorizationConsent.getScopes() : null;
- AuthorizationServerSettings authorizationServerSettings =
- AuthorizationServerContextHolder.getContext().getAuthorizationServerSettings();
+ AuthorizationServerSettings authorizationServerSettings = AuthorizationServerContextHolder.getContext()
+ .getAuthorizationServerSettings();
String deviceVerificationUri = authorizationServerSettings.getDeviceVerificationEndpoint();
return new OAuth2DeviceAuthorizationConsentAuthenticationToken(deviceVerificationUri,
@@ -183,11 +189,10 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut
return OAuth2DeviceVerificationAuthenticationToken.class.isAssignableFrom(authentication);
}
- private static boolean requiresAuthorizationConsent(
- Set