Merge branch '1.2.x'
This commit is contained in:
8
etc/checkstyle/checkstyle-suppressions.xml
Normal file
8
etc/checkstyle/checkstyle-suppressions.xml
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<!DOCTYPE suppressions PUBLIC
|
||||||
|
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
|
||||||
|
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
|
||||||
|
<suppressions>
|
||||||
|
<suppress files=".*" checks="JavadocStyle" />
|
||||||
|
<suppress files="SpringAuthorizationServerVersion\.java" checks="HideUtilityClassConstructor"/>
|
||||||
|
</suppressions>
|
||||||
@@ -1,51 +1,18 @@
|
|||||||
<?xml version="1.0"?>
|
<?xml version="1.0"?>
|
||||||
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
|
<!DOCTYPE module PUBLIC
|
||||||
"https://www.puppycrawl.com/dtds/configuration_1_3.dtd">
|
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
|
||||||
<module name="Checker">
|
"https://checkstyle.org/dtds/configuration_1_3.dtd">
|
||||||
<!-- Suppressions -->
|
<module name="com.puppycrawl.tools.checkstyle.Checker">
|
||||||
<module name="SuppressionFilter">
|
<module name="SuppressionFilter">
|
||||||
<property name="file" value="${config_loc}/suppressions.xml"/>
|
<property name="file"
|
||||||
|
value="${config_loc}/checkstyle-suppressions.xml" />
|
||||||
</module>
|
</module>
|
||||||
|
<module name="com.puppycrawl.tools.checkstyle.checks.header.RegexpHeaderCheck">
|
||||||
<!-- Root Checks -->
|
<property name="headerFile" value="${config_loc}/header.txt" />
|
||||||
<module name="RegexpHeader">
|
<property name="fileExtensions" value="java" />
|
||||||
<property name="headerFile" value="${config_loc}/header.txt"/>
|
|
||||||
<property name="fileExtensions" value="java"/>
|
|
||||||
</module>
|
</module>
|
||||||
|
<module name="io.spring.javaformat.checkstyle.SpringChecks">
|
||||||
<!-- Root Checks -->
|
<property name="excludes" value="io.spring.javaformat.checkstyle.check.SpringHeaderCheck" />
|
||||||
<module name="TreeWalker">
|
<property name="excludes" value="com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck" />
|
||||||
<!-- Annotations -->
|
|
||||||
<module name="MissingOverrideCheck" />
|
|
||||||
|
|
||||||
<!-- Coding -->
|
|
||||||
<module name="EmptyStatementCheck" />
|
|
||||||
<module name="RedundantModifier" />
|
|
||||||
|
|
||||||
<!-- Imports -->
|
|
||||||
<module name="UnusedImportsCheck">
|
|
||||||
<property name="processJavadoc" value="true" />
|
|
||||||
</module>
|
|
||||||
|
|
||||||
<!-- Regexp -->
|
|
||||||
<module name="RegexpSinglelineJava">
|
|
||||||
<property name="format" value="^\t* +\t*\S"/>
|
|
||||||
<property name="message" value="Line has leading space characters; indentation should be performed with tabs only."/>
|
|
||||||
<property name="ignoreComments" value="true"/>
|
|
||||||
</module>
|
|
||||||
<module name="RegexpSinglelineJava">
|
|
||||||
<property name="maximum" value="0"/>
|
|
||||||
<property name="format" value="org\.junit\.Assert\.assert"/>
|
|
||||||
<property name="message" value="Please use AssertJ imports."/>
|
|
||||||
<property name="ignoreComments" value="true"/>
|
|
||||||
</module>
|
|
||||||
<module name="Regexp">
|
|
||||||
<property name="format" value="[ \t]+$"/>
|
|
||||||
<property name="illegalPattern" value="true"/>
|
|
||||||
<property name="message" value="Trailing whitespace"/>
|
|
||||||
</module>
|
|
||||||
|
|
||||||
<!-- Whitespace -->
|
|
||||||
<module name="WhitespaceAfterCheck" />
|
|
||||||
</module>
|
</module>
|
||||||
</module>
|
</module>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
^\Q/*\E$
|
^\Q/*\E$
|
||||||
^\Q * Copyright\E (\d{4}(\-\d{4})? the original author or authors\.|(\d{4}, )*(\d{4}) Acegi Technology Pty Limited)$
|
^\Q * Copyright \E20\d\d\-20\d\d\Q the original author or authors.\E$
|
||||||
^\Q *\E$
|
^\Q *\E$
|
||||||
^\Q * Licensed under the Apache License, Version 2.0 (the "License");\E$
|
^\Q * Licensed under the Apache License, Version 2.0 (the "License");\E$
|
||||||
^\Q * you may not use this file except in compliance with the License.\E$
|
^\Q * you may not use this file except in compliance with the License.\E$
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
<?xml version="1.0"?>
|
|
||||||
<!DOCTYPE suppressions PUBLIC
|
|
||||||
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
|
|
||||||
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
|
|
||||||
<suppressions>
|
|
||||||
<suppress files=".+Application\.java" checks="HideUtilityClassConstructor"/>
|
|
||||||
<suppress files=".+Configuration\.java" checks="HideUtilityClassConstructor"/>
|
|
||||||
<suppress files="[\\/]BCrypt(Tests)?\.java" checks="RegexpHeader"/>
|
|
||||||
|
|
||||||
<suppress files="[\\/]src[\\/]test[\\/]java[\\/]" checks="Javadoc"/>
|
|
||||||
<suppress files="[\\/]src[\\/]integration-test[\\/]java[\\/]" checks="Javadoc"/>
|
|
||||||
|
|
||||||
<suppress files="[\\/]docs[\\/]" checks="Javadoc"/>
|
|
||||||
<suppress files="[\\/]docs[\\/]" checks="CommentsIndentation"/>
|
|
||||||
<suppress files="[\\/]docs[\\/]" checks="InnerTypeLast"/>
|
|
||||||
|
|
||||||
<suppress files="[\\/]samples[\\/]" checks="Javadoc"/>
|
|
||||||
<suppress files="[\\/]samples[\\/]" checks="CommentsIndentation"/>
|
|
||||||
<suppress files="[\\/]samples[\\/]" checks="InnerTypeLast"/>
|
|
||||||
</suppressions>
|
|
||||||
@@ -36,8 +36,8 @@ import org.springframework.util.Assert;
|
|||||||
*
|
*
|
||||||
* @author Daniel Garnier-Moiroux
|
* @author Daniel Garnier-Moiroux
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @see OAuth2AuthorizationServerMetadataClaimAccessor
|
|
||||||
* @since 0.1.1
|
* @since 0.1.1
|
||||||
|
* @see OAuth2AuthorizationServerMetadataClaimAccessor
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc8414#section-3.2">3.2.
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc8414#section-3.2">3.2.
|
||||||
* Authorization Server Metadata Response</a>
|
* Authorization Server Metadata Response</a>
|
||||||
* @see <a target="_blank" href=
|
* @see <a target="_blank" href=
|
||||||
@@ -72,8 +72,11 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A builder for subclasses of {@link AbstractOAuth2AuthorizationServerMetadata}.
|
* A builder for subclasses of {@link AbstractOAuth2AuthorizationServerMetadata}.
|
||||||
|
*
|
||||||
|
* @param <T> the type of object
|
||||||
|
* @param <B> the type of the builder
|
||||||
*/
|
*/
|
||||||
protected static abstract class AbstractBuilder<T extends AbstractOAuth2AuthorizationServerMetadata, B extends AbstractBuilder<T, B>> {
|
protected abstract static class AbstractBuilder<T extends AbstractOAuth2AuthorizationServerMetadata, B extends AbstractBuilder<T, B>> {
|
||||||
|
|
||||||
private final Map<String, Object> claims = new LinkedHashMap<>();
|
private final Map<String, Object> claims = new LinkedHashMap<>();
|
||||||
|
|
||||||
@@ -509,7 +512,7 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata
|
|||||||
private void addClaimToClaimList(String name, String value) {
|
private void addClaimToClaimList(String name, String value) {
|
||||||
Assert.hasText(name, "name cannot be empty");
|
Assert.hasText(name, "name cannot be empty");
|
||||||
Assert.notNull(value, "value cannot be null");
|
Assert.notNull(value, "value cannot be null");
|
||||||
getClaims().computeIfAbsent(name, k -> new LinkedList<String>());
|
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
|
||||||
((List<String>) getClaims().get(name)).add(value);
|
((List<String>) getClaims().get(name)).add(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -517,7 +520,7 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata
|
|||||||
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
|
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
|
||||||
Assert.hasText(name, "name cannot be empty");
|
Assert.hasText(name, "name cannot be empty");
|
||||||
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
|
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
|
||||||
getClaims().computeIfAbsent(name, k -> new LinkedList<String>());
|
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
|
||||||
List<String> values = (List<String>) getClaims().get(name);
|
List<String> values = (List<String>) getClaims().get(name);
|
||||||
valuesConsumer.accept(values);
|
valuesConsumer.accept(values);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ public final class InMemoryOAuth2AuthorizationConsentService implements OAuth2Au
|
|||||||
*/
|
*/
|
||||||
public InMemoryOAuth2AuthorizationConsentService(List<OAuth2AuthorizationConsent> authorizationConsents) {
|
public InMemoryOAuth2AuthorizationConsentService(List<OAuth2AuthorizationConsent> authorizationConsents) {
|
||||||
Assert.notNull(authorizationConsents, "authorizationConsents cannot be null");
|
Assert.notNull(authorizationConsents, "authorizationConsents cannot be null");
|
||||||
authorizationConsents.forEach(authorizationConsent -> {
|
authorizationConsents.forEach((authorizationConsent) -> {
|
||||||
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
|
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
|
||||||
int id = getId(authorizationConsent);
|
int id = getId(authorizationConsent);
|
||||||
Assert.isTrue(!this.authorizationConsents.containsKey(id),
|
Assert.isTrue(!this.authorizationConsents.containsKey(id),
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
|
|||||||
*/
|
*/
|
||||||
public InMemoryOAuth2AuthorizationService(List<OAuth2Authorization> authorizations) {
|
public InMemoryOAuth2AuthorizationService(List<OAuth2Authorization> authorizations) {
|
||||||
Assert.notNull(authorizations, "authorizations cannot be null");
|
Assert.notNull(authorizations, "authorizations cannot be null");
|
||||||
authorizations.forEach(authorization -> {
|
authorizations.forEach((authorization) -> {
|
||||||
Assert.notNull(authorization, "authorization cannot be null");
|
Assert.notNull(authorization, "authorization cannot be null");
|
||||||
Assert.isTrue(!this.authorizations.containsKey(authorization.getId()),
|
Assert.isTrue(!this.authorizations.containsKey(authorization.getId()),
|
||||||
"The authorization must be unique. Found duplicate identifier: " + authorization.getId());
|
"The authorization must be unique. Found duplicate identifier: " + authorization.getId());
|
||||||
@@ -129,7 +129,7 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
|
|||||||
public OAuth2Authorization findById(String id) {
|
public OAuth2Authorization findById(String id) {
|
||||||
Assert.hasText(id, "id cannot be empty");
|
Assert.hasText(id, "id cannot be empty");
|
||||||
OAuth2Authorization authorization = this.authorizations.get(id);
|
OAuth2Authorization authorization = this.authorizations.get(id);
|
||||||
return authorization != null ? authorization : this.initializedAuthorizations.get(id);
|
return (authorization != null) ? authorization : this.initializedAuthorizations.get(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
@@ -164,19 +164,26 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
|
|||||||
matchesRefreshToken(authorization, token) ||
|
matchesRefreshToken(authorization, token) ||
|
||||||
matchesDeviceCode(authorization, token) ||
|
matchesDeviceCode(authorization, token) ||
|
||||||
matchesUserCode(authorization, token);
|
matchesUserCode(authorization, token);
|
||||||
} else if (OAuth2ParameterNames.STATE.equals(tokenType.getValue())) {
|
}
|
||||||
|
else if (OAuth2ParameterNames.STATE.equals(tokenType.getValue())) {
|
||||||
return matchesState(authorization, token);
|
return matchesState(authorization, token);
|
||||||
} else if (OAuth2ParameterNames.CODE.equals(tokenType.getValue())) {
|
}
|
||||||
|
else if (OAuth2ParameterNames.CODE.equals(tokenType.getValue())) {
|
||||||
return matchesAuthorizationCode(authorization, token);
|
return matchesAuthorizationCode(authorization, token);
|
||||||
} else if (OAuth2TokenType.ACCESS_TOKEN.equals(tokenType)) {
|
}
|
||||||
|
else if (OAuth2TokenType.ACCESS_TOKEN.equals(tokenType)) {
|
||||||
return matchesAccessToken(authorization, token);
|
return matchesAccessToken(authorization, token);
|
||||||
} else if (OidcParameterNames.ID_TOKEN.equals(tokenType.getValue())) {
|
}
|
||||||
|
else if (OidcParameterNames.ID_TOKEN.equals(tokenType.getValue())) {
|
||||||
return matchesIdToken(authorization, token);
|
return matchesIdToken(authorization, token);
|
||||||
} else if (OAuth2TokenType.REFRESH_TOKEN.equals(tokenType)) {
|
}
|
||||||
|
else if (OAuth2TokenType.REFRESH_TOKEN.equals(tokenType)) {
|
||||||
return matchesRefreshToken(authorization, token);
|
return matchesRefreshToken(authorization, token);
|
||||||
} else if (OAuth2ParameterNames.DEVICE_CODE.equals(tokenType.getValue())) {
|
}
|
||||||
|
else if (OAuth2ParameterNames.DEVICE_CODE.equals(tokenType.getValue())) {
|
||||||
return matchesDeviceCode(authorization, token);
|
return matchesDeviceCode(authorization, token);
|
||||||
} else if (OAuth2ParameterNames.USER_CODE.equals(tokenType.getValue())) {
|
}
|
||||||
|
else if (OAuth2ParameterNames.USER_CODE.equals(tokenType.getValue())) {
|
||||||
return matchesUserCode(authorization, token);
|
return matchesUserCode(authorization, token);
|
||||||
}
|
}
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|||||||
@@ -71,17 +71,6 @@ import org.springframework.util.StringUtils;
|
|||||||
@ImportRuntimeHints(JdbcOAuth2AuthorizationConsentService.JdbcOAuth2AuthorizationConsentServiceRuntimeHintsRegistrar.class)
|
@ImportRuntimeHints(JdbcOAuth2AuthorizationConsentService.JdbcOAuth2AuthorizationConsentServiceRuntimeHintsRegistrar.class)
|
||||||
public class JdbcOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {
|
public class JdbcOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {
|
||||||
|
|
||||||
static class JdbcOAuth2AuthorizationConsentServiceRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
|
||||||
hints.resources()
|
|
||||||
.registerResource(new ClassPathResource(
|
|
||||||
"org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql"));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
private static final String COLUMN_NAMES = "registered_client_id, "
|
private static final String COLUMN_NAMES = "registered_client_id, "
|
||||||
+ "principal_name, "
|
+ "principal_name, "
|
||||||
@@ -288,4 +277,15 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static class JdbcOAuth2AuthorizationConsentServiceRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
||||||
|
hints.resources()
|
||||||
|
.registerResource(new ClassPathResource(
|
||||||
|
"org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -97,17 +97,6 @@ import org.springframework.util.StringUtils;
|
|||||||
@ImportRuntimeHints(JdbcOAuth2AuthorizationService.JdbcOAuth2AuthorizationServiceRuntimeHintsRegistrar.class)
|
@ImportRuntimeHints(JdbcOAuth2AuthorizationService.JdbcOAuth2AuthorizationServiceRuntimeHintsRegistrar.class)
|
||||||
public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationService {
|
public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationService {
|
||||||
|
|
||||||
static class JdbcOAuth2AuthorizationServiceRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
|
||||||
hints.resources()
|
|
||||||
.registerResource(new ClassPathResource(
|
|
||||||
"org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql"));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
private static final String COLUMN_NAMES = "id, "
|
private static final String COLUMN_NAMES = "id, "
|
||||||
+ "registered_client_id, "
|
+ "registered_client_id, "
|
||||||
@@ -379,6 +368,70 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
|
|||||||
return this.authorizationParametersMapper;
|
return this.authorizationParametersMapper;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void initColumnMetadata(JdbcOperations jdbcOperations) {
|
||||||
|
columnMetadataMap = new HashMap<>();
|
||||||
|
ColumnMetadata columnMetadata;
|
||||||
|
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "attributes", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "authorization_code_value", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "authorization_code_metadata", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "access_token_value", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "access_token_metadata", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "oidc_id_token_value", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "oidc_id_token_metadata", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "refresh_token_value", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "refresh_token_metadata", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "user_code_value", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "user_code_metadata", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "device_code_value", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
columnMetadata = getColumnMetadata(jdbcOperations, "device_code_metadata", Types.BLOB);
|
||||||
|
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ColumnMetadata getColumnMetadata(JdbcOperations jdbcOperations, String columnName,
|
||||||
|
int defaultDataType) {
|
||||||
|
Integer dataType = jdbcOperations.execute((ConnectionCallback<Integer>) (conn) -> {
|
||||||
|
DatabaseMetaData databaseMetaData = conn.getMetaData();
|
||||||
|
ResultSet rs = databaseMetaData.getColumns(null, null, TABLE_NAME, columnName);
|
||||||
|
if (rs.next()) {
|
||||||
|
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.
|
||||||
|
// 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.
|
||||||
|
rs = databaseMetaData.getColumns(null, null, TABLE_NAME.toUpperCase(), columnName.toUpperCase());
|
||||||
|
if (rs.next()) {
|
||||||
|
return rs.getInt("DATA_TYPE");
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
return new ColumnMetadata(columnName, (dataType != null) ? dataType : defaultDataType);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The default {@link RowMapper} that maps the current row in
|
* The default {@link RowMapper} that maps the current row in
|
||||||
* {@code java.sql.ResultSet} to {@link OAuth2Authorization}.
|
* {@code java.sql.ResultSet} to {@link OAuth2Authorization}.
|
||||||
@@ -758,68 +811,15 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void initColumnMetadata(JdbcOperations jdbcOperations) {
|
static class JdbcOAuth2AuthorizationServiceRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
|
||||||
columnMetadataMap = new HashMap<>();
|
|
||||||
ColumnMetadata columnMetadata;
|
|
||||||
|
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "attributes", Types.BLOB);
|
@Override
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "authorization_code_value", Types.BLOB);
|
hints.resources()
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
.registerResource(new ClassPathResource(
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "authorization_code_metadata", Types.BLOB);
|
"org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql"));
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
}
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "access_token_value", Types.BLOB);
|
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "access_token_metadata", Types.BLOB);
|
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "oidc_id_token_value", Types.BLOB);
|
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "oidc_id_token_metadata", Types.BLOB);
|
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "refresh_token_value", Types.BLOB);
|
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "refresh_token_metadata", Types.BLOB);
|
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "user_code_value", Types.BLOB);
|
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "user_code_metadata", Types.BLOB);
|
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "device_code_value", Types.BLOB);
|
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
|
||||||
columnMetadata = getColumnMetadata(jdbcOperations, "device_code_metadata", Types.BLOB);
|
|
||||||
columnMetadataMap.put(columnMetadata.getColumnName(), columnMetadata);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static ColumnMetadata getColumnMetadata(JdbcOperations jdbcOperations, String columnName,
|
|
||||||
int defaultDataType) {
|
|
||||||
Integer dataType = jdbcOperations.execute((ConnectionCallback<Integer>) conn -> {
|
|
||||||
DatabaseMetaData databaseMetaData = conn.getMetaData();
|
|
||||||
ResultSet rs = databaseMetaData.getColumns(null, null, TABLE_NAME, columnName);
|
|
||||||
if (rs.next()) {
|
|
||||||
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.
|
|
||||||
// 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.
|
|
||||||
rs = databaseMetaData.getColumns(null, null, TABLE_NAME.toUpperCase(), columnName.toUpperCase());
|
|
||||||
if (rs.next()) {
|
|
||||||
return rs.getInt("DATA_TYPE");
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
});
|
|
||||||
return new ColumnMetadata(columnName, dataType != null ? dataType : defaultDataType);
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ public class OAuth2Authorization implements Serializable {
|
|||||||
public <T extends OAuth2Token> Token<T> getToken(Class<T> tokenType) {
|
public <T extends OAuth2Token> Token<T> getToken(Class<T> tokenType) {
|
||||||
Assert.notNull(tokenType, "tokenType cannot be null");
|
Assert.notNull(tokenType, "tokenType cannot be null");
|
||||||
Token<?> token = this.tokens.get(tokenType);
|
Token<?> token = this.tokens.get(tokenType);
|
||||||
return token != null ? (Token<T>) token : null;
|
return (token != null) ? (Token<T>) token : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -234,12 +234,13 @@ public class OAuth2Authorization implements Serializable {
|
|||||||
.authorizationGrantType(authorization.getAuthorizationGrantType())
|
.authorizationGrantType(authorization.getAuthorizationGrantType())
|
||||||
.authorizedScopes(authorization.getAuthorizedScopes())
|
.authorizedScopes(authorization.getAuthorizedScopes())
|
||||||
.tokens(authorization.tokens)
|
.tokens(authorization.tokens)
|
||||||
.attributes(attrs -> attrs.putAll(authorization.getAttributes()));
|
.attributes((attrs) -> attrs.putAll(authorization.getAttributes()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A holder of an OAuth 2.0 Token and it's associated metadata.
|
* A holder of an OAuth 2.0 Token and it's associated metadata.
|
||||||
*
|
*
|
||||||
|
* @param <T> the type of the {@link OAuth2Token}
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @since 0.1.0
|
* @since 0.1.0
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -15,11 +15,11 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization;
|
package org.springframework.security.oauth2.server.authorization;
|
||||||
|
|
||||||
|
import java.security.Principal;
|
||||||
|
|
||||||
import org.springframework.lang.Nullable;
|
import org.springframework.lang.Nullable;
|
||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||||
|
|
||||||
import java.security.Principal;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implementations of this interface are responsible for the management of
|
* Implementations of this interface are responsible for the management of
|
||||||
* {@link OAuth2AuthorizationConsent OAuth 2.0 Authorization Consent(s)}.
|
* {@link OAuth2AuthorizationConsent OAuth 2.0 Authorization Consent(s)}.
|
||||||
|
|||||||
@@ -52,13 +52,13 @@ public final class OAuth2AuthorizationServerMetadata extends AbstractOAuth2Autho
|
|||||||
*/
|
*/
|
||||||
public static Builder withClaims(Map<String, Object> claims) {
|
public static Builder withClaims(Map<String, Object> claims) {
|
||||||
Assert.notEmpty(claims, "claims cannot be empty");
|
Assert.notEmpty(claims, "claims cannot be empty");
|
||||||
return new Builder().claims(c -> c.putAll(claims));
|
return new Builder().claims((c) -> c.putAll(claims));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helps configure an {@link OAuth2AuthorizationServerMetadata}.
|
* Helps configure an {@link OAuth2AuthorizationServerMetadata}.
|
||||||
*/
|
*/
|
||||||
public static class Builder extends AbstractBuilder<OAuth2AuthorizationServerMetadata, Builder> {
|
public static final class Builder extends AbstractBuilder<OAuth2AuthorizationServerMetadata, Builder> {
|
||||||
|
|
||||||
private Builder() {
|
private Builder() {
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -88,13 +88,13 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
|
|||||||
*/
|
*/
|
||||||
public static Builder withClaims(Map<String, Object> claims) {
|
public static Builder withClaims(Map<String, Object> claims) {
|
||||||
Assert.notEmpty(claims, "claims cannot be empty");
|
Assert.notEmpty(claims, "claims cannot be empty");
|
||||||
return builder().claims(c -> c.putAll(claims));
|
return builder().claims((c) -> c.putAll(claims));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A builder for {@link OAuth2TokenIntrospection}.
|
* A builder for {@link OAuth2TokenIntrospection}.
|
||||||
*/
|
*/
|
||||||
public static class Builder {
|
public static final class Builder {
|
||||||
|
|
||||||
private final Map<String, Object> claims = new LinkedHashMap<>();
|
private final Map<String, Object> claims = new LinkedHashMap<>();
|
||||||
|
|
||||||
@@ -312,7 +312,7 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
|
|||||||
private void addClaimToClaimList(String name, String value) {
|
private void addClaimToClaimList(String name, String value) {
|
||||||
Assert.hasText(name, "name cannot be empty");
|
Assert.hasText(name, "name cannot be empty");
|
||||||
Assert.notNull(value, "value cannot be null");
|
Assert.notNull(value, "value cannot be null");
|
||||||
this.claims.computeIfAbsent(name, k -> new LinkedList<String>());
|
this.claims.computeIfAbsent(name, (k) -> new LinkedList<String>());
|
||||||
((List<String>) this.claims.get(name)).add(value);
|
((List<String>) this.claims.get(name)).add(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -320,7 +320,7 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
|
|||||||
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
|
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
|
||||||
Assert.hasText(name, "name cannot be empty");
|
Assert.hasText(name, "name cannot be empty");
|
||||||
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
|
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
|
||||||
this.claims.computeIfAbsent(name, k -> new LinkedList<String>());
|
this.claims.computeIfAbsent(name, (k) -> new LinkedList<String>());
|
||||||
List<String> values = (List<String>) this.claims.get(name);
|
List<String> values = (List<String>) this.claims.get(name);
|
||||||
valuesConsumer.accept(values);
|
valuesConsumer.accept(values);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,8 +32,14 @@ public final class OAuth2TokenType implements Serializable {
|
|||||||
|
|
||||||
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
|
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code access_token} token type.
|
||||||
|
*/
|
||||||
public static final OAuth2TokenType ACCESS_TOKEN = new OAuth2TokenType("access_token");
|
public static final OAuth2TokenType ACCESS_TOKEN = new OAuth2TokenType("access_token");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code refresh_token} token type.
|
||||||
|
*/
|
||||||
public static final OAuth2TokenType REFRESH_TOKEN = new OAuth2TokenType("refresh_token");
|
public static final OAuth2TokenType REFRESH_TOKEN = new OAuth2TokenType("refresh_token");
|
||||||
|
|
||||||
private final String value;
|
private final String value;
|
||||||
|
|||||||
@@ -71,10 +71,10 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis
|
|||||||
// @formatter:off
|
// @formatter:off
|
||||||
if ((beanClassName.equals("org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService") ||
|
if ((beanClassName.equals("org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService") ||
|
||||||
beanClassName.equals("org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository")) &&
|
beanClassName.equals("org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository")) &&
|
||||||
!jackson2Contributed) {
|
!this.jackson2Contributed) {
|
||||||
Jackson2ConfigurationBeanRegistrationAotContribution jackson2Contribution =
|
Jackson2ConfigurationBeanRegistrationAotContribution jackson2Contribution =
|
||||||
new Jackson2ConfigurationBeanRegistrationAotContribution();
|
new Jackson2ConfigurationBeanRegistrationAotContribution();
|
||||||
jackson2Contributed = true;
|
this.jackson2Contributed = true;
|
||||||
return jackson2Contribution;
|
return jackson2Contribution;
|
||||||
}
|
}
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
@@ -117,7 +117,7 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis
|
|||||||
TypeReference.of(AuthorizationGrantType.class),
|
TypeReference.of(AuthorizationGrantType.class),
|
||||||
TypeReference.of(OAuth2AuthorizationResponseType.class),
|
TypeReference.of(OAuth2AuthorizationResponseType.class),
|
||||||
TypeReference.of(OAuth2TokenFormat.class)),
|
TypeReference.of(OAuth2TokenFormat.class)),
|
||||||
builder -> builder.withMembers(MemberCategory.DECLARED_FIELDS,
|
(builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS,
|
||||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS));
|
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS));
|
||||||
|
|
||||||
// Jackson Modules - Spring Security and Spring Authorization Server
|
// Jackson Modules - Spring Security and Spring Authorization Server
|
||||||
@@ -126,7 +126,7 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis
|
|||||||
Arrays.asList(TypeReference.of(CoreJackson2Module.class),
|
Arrays.asList(TypeReference.of(CoreJackson2Module.class),
|
||||||
TypeReference.of(WebServletJackson2Module.class),
|
TypeReference.of(WebServletJackson2Module.class),
|
||||||
TypeReference.of(OAuth2AuthorizationServerJackson2Module.class)),
|
TypeReference.of(OAuth2AuthorizationServerJackson2Module.class)),
|
||||||
builder -> builder.withMembers(MemberCategory.DECLARED_FIELDS,
|
(builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS,
|
||||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS));
|
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS));
|
||||||
|
|
||||||
// Jackson Mixins - Spring Security and Spring Authorization Server
|
// Jackson Mixins - Spring Security and Spring Authorization Server
|
||||||
@@ -170,7 +170,7 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis
|
|||||||
.of("org.springframework.security.oauth2.client.jackson2.OAuth2ClientJackson2Module"),
|
.of("org.springframework.security.oauth2.client.jackson2.OAuth2ClientJackson2Module"),
|
||||||
TypeReference
|
TypeReference
|
||||||
.of("org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken")),
|
.of("org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken")),
|
||||||
builder -> builder.withMembers(MemberCategory.DECLARED_FIELDS,
|
(builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS,
|
||||||
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
|
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
|
||||||
MemberCategory.INVOKE_DECLARED_METHODS));
|
MemberCategory.INVOKE_DECLARED_METHODS));
|
||||||
|
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ public final class JwtClientAssertionAuthenticationProvider implements Authentic
|
|||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
ClientAuthenticationMethod clientAuthenticationMethod =
|
ClientAuthenticationMethod clientAuthenticationMethod =
|
||||||
registeredClient.getClientSettings().getTokenEndpointAuthenticationSigningAlgorithm() instanceof SignatureAlgorithm ?
|
(registeredClient.getClientSettings().getTokenEndpointAuthenticationSigningAlgorithm() instanceof SignatureAlgorithm) ?
|
||||||
ClientAuthenticationMethod.PRIVATE_KEY_JWT :
|
ClientAuthenticationMethod.PRIVATE_KEY_JWT :
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_JWT;
|
ClientAuthenticationMethod.CLIENT_SECRET_JWT;
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|||||||
@@ -62,8 +62,6 @@ import org.springframework.util.Assert;
|
|||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
import org.springframework.util.StringUtils;
|
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
|
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization Code
|
||||||
* Grant.
|
* Grant.
|
||||||
@@ -118,8 +116,8 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
|
|||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
|
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
|
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
|
||||||
authorizationCodeAuthentication);
|
.getAuthenticatedClientElseThrowInvalidClient(authorizationCodeAuthentication);
|
||||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
||||||
|
|
||||||
if (this.logger.isTraceEnabled()) {
|
if (this.logger.isTraceEnabled()) {
|
||||||
@@ -169,7 +167,7 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
|
|||||||
|
|
||||||
if (!authorizationCode.isActive()) {
|
if (!authorizationCode.isActive()) {
|
||||||
if (authorizationCode.isInvalidated()) {
|
if (authorizationCode.isInvalidated()) {
|
||||||
OAuth2Authorization.Token<? extends OAuth2Token> token = authorization.getRefreshToken() != null
|
OAuth2Authorization.Token<? extends OAuth2Token> token = (authorization.getRefreshToken() != null)
|
||||||
? authorization.getRefreshToken() : authorization.getAccessToken();
|
? authorization.getRefreshToken() : authorization.getAccessToken();
|
||||||
if (token != null) {
|
if (token != null) {
|
||||||
// Invalidate the access (and refresh) token as the client is
|
// Invalidate the access (and refresh) token as the client is
|
||||||
|
|||||||
@@ -198,12 +198,12 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
if (this.logger.isTraceEnabled()) {
|
if (this.logger.isTraceEnabled()) {
|
||||||
logger.trace("Generated authorization consent state");
|
this.logger.trace("Generated authorization consent state");
|
||||||
}
|
}
|
||||||
|
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
Set<String> currentAuthorizedScopes = currentAuthorizationConsent != null
|
Set<String> currentAuthorizedScopes = (currentAuthorizationConsent != null)
|
||||||
? currentAuthorizationConsent.getScopes() : null;
|
? currentAuthorizationConsent.getScopes() : null;
|
||||||
|
|
||||||
if (this.logger.isTraceEnabled()) {
|
if (this.logger.isTraceEnabled()) {
|
||||||
|
|||||||
@@ -81,9 +81,9 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
|
|||||||
this.principal = principal;
|
this.principal = principal;
|
||||||
this.redirectUri = redirectUri;
|
this.redirectUri = redirectUri;
|
||||||
this.state = state;
|
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(
|
this.additionalParameters = Collections.unmodifiableMap(
|
||||||
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
||||||
this.authorizationCode = null;
|
this.authorizationCode = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,7 +113,7 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
|
|||||||
this.authorizationCode = authorizationCode;
|
this.authorizationCode = authorizationCode;
|
||||||
this.redirectUri = redirectUri;
|
this.redirectUri = redirectUri;
|
||||||
this.state = state;
|
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();
|
this.additionalParameters = Collections.emptyMap();
|
||||||
setAuthenticated(true);
|
setAuthenticated(true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -154,7 +154,7 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
|
|||||||
|
|
||||||
OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService
|
OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService
|
||||||
.findById(authorization.getRegisteredClientId(), authorization.getPrincipalName());
|
.findById(authorization.getRegisteredClientId(), authorization.getPrincipalName());
|
||||||
Set<String> currentAuthorizedScopes = currentAuthorizationConsent != null
|
Set<String> currentAuthorizedScopes = (currentAuthorizationConsent != null)
|
||||||
? currentAuthorizationConsent.getScopes() : Collections.emptySet();
|
? currentAuthorizationConsent.getScopes() : Collections.emptySet();
|
||||||
|
|
||||||
if (!currentAuthorizedScopes.isEmpty()) {
|
if (!currentAuthorizedScopes.isEmpty()) {
|
||||||
@@ -242,9 +242,7 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
|
|||||||
OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
|
OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
|
||||||
.authorizedScopes(authorizedScopes)
|
.authorizedScopes(authorizedScopes)
|
||||||
.token(authorizationCode)
|
.token(authorizationCode)
|
||||||
.attributes(attrs -> {
|
.attributes((attrs) -> attrs.remove(OAuth2ParameterNames.STATE))
|
||||||
attrs.remove(OAuth2ParameterNames.STATE);
|
|
||||||
})
|
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(updatedAuthorization);
|
this.authorizationService.save(updatedAuthorization);
|
||||||
|
|
||||||
@@ -353,9 +351,9 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
|
|||||||
redirectUri = null; // Prevent redirects
|
redirectUri = null; // Prevent redirects
|
||||||
}
|
}
|
||||||
|
|
||||||
String state = authorizationRequest != null ? authorizationRequest.getState()
|
String state = (authorizationRequest != null) ? authorizationRequest.getState()
|
||||||
: authorizationConsentAuthentication.getState();
|
: authorizationConsentAuthentication.getState();
|
||||||
Set<String> requestedScopes = authorizationRequest != null ? authorizationRequest.getScopes()
|
Set<String> requestedScopes = (authorizationRequest != null) ? authorizationRequest.getScopes()
|
||||||
: authorizationConsentAuthentication.getScopes();
|
: authorizationConsentAuthentication.getScopes();
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
|
|||||||
@@ -74,9 +74,9 @@ public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthe
|
|||||||
this.clientId = clientId;
|
this.clientId = clientId;
|
||||||
this.principal = principal;
|
this.principal = principal;
|
||||||
this.state = state;
|
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(
|
this.additionalParameters = Collections.unmodifiableMap(
|
||||||
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
||||||
setAuthenticated(true);
|
setAuthenticated(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthent
|
|||||||
this.authorizationGrantType = authorizationGrantType;
|
this.authorizationGrantType = authorizationGrantType;
|
||||||
this.clientPrincipal = clientPrincipal;
|
this.clientPrincipal = clientPrincipal;
|
||||||
this.additionalParameters = Collections.unmodifiableMap(
|
this.additionalParameters = Collections.unmodifiableMap(
|
||||||
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken
|
|||||||
this.clientAuthenticationMethod = clientAuthenticationMethod;
|
this.clientAuthenticationMethod = clientAuthenticationMethod;
|
||||||
this.credentials = credentials;
|
this.credentials = credentials;
|
||||||
this.additionalParameters = Collections
|
this.additionalParameters = Collections
|
||||||
.unmodifiableMap(additionalParameters != null ? additionalParameters : Collections.emptyMap());
|
.unmodifiableMap((additionalParameters != null) ? additionalParameters : Collections.emptyMap());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -42,8 +42,6 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke
|
|||||||
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
|
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Client Credentials
|
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Client Credentials
|
||||||
* Grant.
|
* Grant.
|
||||||
@@ -93,8 +91,8 @@ public final class OAuth2ClientCredentialsAuthenticationProvider implements Auth
|
|||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication = (OAuth2ClientCredentialsAuthenticationToken) authentication;
|
OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication = (OAuth2ClientCredentialsAuthenticationToken) authentication;
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
|
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
|
||||||
clientCredentialsAuthentication);
|
.getAuthenticatedClientElseThrowInvalidClient(clientCredentialsAuthentication);
|
||||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
||||||
|
|
||||||
if (this.logger.isTraceEnabled()) {
|
if (this.logger.isTraceEnabled()) {
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ public class OAuth2ClientCredentialsAuthenticationToken extends OAuth2Authorizat
|
|||||||
public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal, @Nullable Set<String> scopes,
|
public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal, @Nullable Set<String> scopes,
|
||||||
@Nullable Map<String, Object> additionalParameters) {
|
@Nullable Map<String, Object> additionalParameters) {
|
||||||
super(AuthorizationGrantType.CLIENT_CREDENTIALS, clientPrincipal, 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());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -133,7 +133,7 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
|
|||||||
|
|
||||||
OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService
|
OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService
|
||||||
.findById(authorization.getRegisteredClientId(), principal.getName());
|
.findById(authorization.getRegisteredClientId(), principal.getName());
|
||||||
Set<String> currentAuthorizedScopes = currentAuthorizationConsent != null
|
Set<String> currentAuthorizedScopes = (currentAuthorizationConsent != null)
|
||||||
? currentAuthorizationConsent.getScopes() : Collections.emptySet();
|
? currentAuthorizationConsent.getScopes() : Collections.emptySet();
|
||||||
|
|
||||||
if (!currentAuthorizedScopes.isEmpty()) {
|
if (!currentAuthorizedScopes.isEmpty()) {
|
||||||
@@ -187,11 +187,11 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
authorization = OAuth2Authorization.from(authorization)
|
authorization = OAuth2Authorization.from(authorization)
|
||||||
.token(deviceCodeToken.getToken(),
|
.token((deviceCodeToken.getToken()),
|
||||||
metadata -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
||||||
.token(userCodeToken.getToken(),
|
.token((userCodeToken.getToken()),
|
||||||
metadata -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
||||||
.attributes(attrs -> attrs.remove(OAuth2ParameterNames.STATE))
|
.attributes((attrs) -> attrs.remove(OAuth2ParameterNames.STATE))
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
if (this.logger.isTraceEnabled()) {
|
if (this.logger.isTraceEnabled()) {
|
||||||
@@ -210,10 +210,10 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
|
|||||||
|
|
||||||
authorization = OAuth2Authorization.from(authorization)
|
authorization = OAuth2Authorization.from(authorization)
|
||||||
.authorizedScopes(authorizedScopes)
|
.authorizedScopes(authorizedScopes)
|
||||||
.token(userCodeToken.getToken(),
|
.token((userCodeToken.getToken()),
|
||||||
metadata -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
||||||
.attributes(attrs -> attrs.remove(OAuth2ParameterNames.STATE))
|
.attributes((attrs) -> attrs.remove(OAuth2ParameterNames.STATE))
|
||||||
.attributes(attrs -> attrs.remove(OAuth2ParameterNames.SCOPE))
|
.attributes((attrs) -> attrs.remove(OAuth2ParameterNames.SCOPE))
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationToken extends OAuth2A
|
|||||||
Assert.hasText(userCode, "userCode cannot be empty");
|
Assert.hasText(userCode, "userCode cannot be empty");
|
||||||
this.userCode = userCode;
|
this.userCode = userCode;
|
||||||
this.requestedScopes = Collections
|
this.requestedScopes = Collections
|
||||||
.unmodifiableSet(requestedScopes != null ? new HashSet<>(requestedScopes) : Collections.emptySet());
|
.unmodifiableSet((requestedScopes != null) ? new HashSet<>(requestedScopes) : Collections.emptySet());
|
||||||
setAuthenticated(true);
|
setAuthenticated(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -50,8 +50,6 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke
|
|||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AuthenticationProvider} implementation for the Device Authorization Request
|
* An {@link AuthenticationProvider} implementation for the Device Authorization Request
|
||||||
* used in the OAuth 2.0 Device Authorization Grant.
|
* used in the OAuth 2.0 Device Authorization Grant.
|
||||||
@@ -98,8 +96,8 @@ public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implem
|
|||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
OAuth2DeviceAuthorizationRequestAuthenticationToken deviceAuthorizationRequestAuthentication = (OAuth2DeviceAuthorizationRequestAuthenticationToken) authentication;
|
OAuth2DeviceAuthorizationRequestAuthenticationToken deviceAuthorizationRequestAuthentication = (OAuth2DeviceAuthorizationRequestAuthenticationToken) authentication;
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
|
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
|
||||||
deviceAuthorizationRequestAuthentication);
|
.getAuthenticatedClientElseThrowInvalidClient(deviceAuthorizationRequestAuthentication);
|
||||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
||||||
|
|
||||||
if (this.logger.isTraceEnabled()) {
|
if (this.logger.isTraceEnabled()) {
|
||||||
|
|||||||
@@ -70,9 +70,9 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac
|
|||||||
Assert.hasText(authorizationUri, "authorizationUri cannot be empty");
|
Assert.hasText(authorizationUri, "authorizationUri cannot be empty");
|
||||||
this.clientPrincipal = clientPrincipal;
|
this.clientPrincipal = clientPrincipal;
|
||||||
this.authorizationUri = authorizationUri;
|
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(
|
this.additionalParameters = Collections.unmodifiableMap(
|
||||||
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
||||||
this.deviceCode = null;
|
this.deviceCode = null;
|
||||||
this.userCode = null;
|
this.userCode = null;
|
||||||
}
|
}
|
||||||
@@ -92,7 +92,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac
|
|||||||
Assert.notNull(deviceCode, "deviceCode cannot be null");
|
Assert.notNull(deviceCode, "deviceCode cannot be null");
|
||||||
Assert.notNull(userCode, "userCode cannot be null");
|
Assert.notNull(userCode, "userCode cannot be null");
|
||||||
this.clientPrincipal = clientPrincipal;
|
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.deviceCode = deviceCode;
|
||||||
this.userCode = userCode;
|
this.userCode = userCode;
|
||||||
this.authorizationUri = null;
|
this.authorizationUri = null;
|
||||||
|
|||||||
@@ -44,8 +44,6 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke
|
|||||||
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
|
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AuthenticationProvider} implementation for the Device Access Token Request
|
* An {@link AuthenticationProvider} implementation for the Device Access Token Request
|
||||||
* used in the OAuth 2.0 Device Authorization Grant.
|
* used in the OAuth 2.0 Device Authorization Grant.
|
||||||
@@ -101,8 +99,8 @@ public final class OAuth2DeviceCodeAuthenticationProvider implements Authenticat
|
|||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
OAuth2DeviceCodeAuthenticationToken deviceCodeAuthentication = (OAuth2DeviceCodeAuthenticationToken) authentication;
|
OAuth2DeviceCodeAuthenticationToken deviceCodeAuthentication = (OAuth2DeviceCodeAuthenticationToken) authentication;
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
|
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
|
||||||
deviceCodeAuthentication);
|
.getAuthenticatedClientElseThrowInvalidClient(deviceCodeAuthentication);
|
||||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
||||||
|
|
||||||
if (this.logger.isTraceEnabled()) {
|
if (this.logger.isTraceEnabled()) {
|
||||||
@@ -202,7 +200,7 @@ public final class OAuth2DeviceCodeAuthenticationProvider implements Authenticat
|
|||||||
// @formatter:off
|
// @formatter:off
|
||||||
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.from(authorization)
|
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.from(authorization)
|
||||||
// Invalidate the device code as it can only be used (successfully) once
|
// Invalidate the device code as it can only be used (successfully) once
|
||||||
.token(deviceCode.getToken(), metadata ->
|
.token(deviceCode.getToken(), (metadata) ->
|
||||||
metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true));
|
metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
|
|||||||
@@ -149,7 +149,7 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut
|
|||||||
this.logger.trace("Saved authorization");
|
this.logger.trace("Saved authorization");
|
||||||
}
|
}
|
||||||
|
|
||||||
Set<String> currentAuthorizedScopes = currentAuthorizationConsent != null
|
Set<String> currentAuthorizedScopes = (currentAuthorizationConsent != null)
|
||||||
? currentAuthorizationConsent.getScopes() : null;
|
? currentAuthorizationConsent.getScopes() : null;
|
||||||
|
|
||||||
AuthorizationServerSettings authorizationServerSettings = AuthorizationServerContextHolder.getContext()
|
AuthorizationServerSettings authorizationServerSettings = AuthorizationServerContextHolder.getContext()
|
||||||
@@ -166,10 +166,10 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut
|
|||||||
authorization = OAuth2Authorization.from(authorization)
|
authorization = OAuth2Authorization.from(authorization)
|
||||||
.principalName(principal.getName())
|
.principalName(principal.getName())
|
||||||
.authorizedScopes(requestedScopes)
|
.authorizedScopes(requestedScopes)
|
||||||
.token(userCode.getToken(), metadata -> metadata
|
.token(userCode.getToken(), (metadata) -> metadata
|
||||||
.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
||||||
.attribute(Principal.class.getName(), principal)
|
.attribute(Principal.class.getName(), principal)
|
||||||
.attributes(attributes -> attributes.remove(OAuth2ParameterNames.SCOPE))
|
.attributes((attributes) -> attributes.remove(OAuth2ParameterNames.SCOPE))
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ public class OAuth2DeviceVerificationAuthenticationToken extends AbstractAuthent
|
|||||||
this.principal = principal;
|
this.principal = principal;
|
||||||
this.userCode = userCode;
|
this.userCode = userCode;
|
||||||
this.additionalParameters = Collections.unmodifiableMap(
|
this.additionalParameters = Collections.unmodifiableMap(
|
||||||
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
||||||
this.clientId = null;
|
this.clientId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -49,8 +49,6 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke
|
|||||||
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
|
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Refresh Token Grant.
|
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Refresh Token Grant.
|
||||||
*
|
*
|
||||||
@@ -100,8 +98,8 @@ public final class OAuth2RefreshTokenAuthenticationProvider implements Authentic
|
|||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
OAuth2RefreshTokenAuthenticationToken refreshTokenAuthentication = (OAuth2RefreshTokenAuthenticationToken) authentication;
|
OAuth2RefreshTokenAuthenticationToken refreshTokenAuthentication = (OAuth2RefreshTokenAuthenticationToken) authentication;
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
|
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
|
||||||
refreshTokenAuthentication);
|
.getAuthenticatedClientElseThrowInvalidClient(refreshTokenAuthentication);
|
||||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
||||||
|
|
||||||
if (this.logger.isTraceEnabled()) {
|
if (this.logger.isTraceEnabled()) {
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ public class OAuth2RefreshTokenAuthenticationToken extends OAuth2AuthorizationGr
|
|||||||
super(AuthorizationGrantType.REFRESH_TOKEN, clientPrincipal, additionalParameters);
|
super(AuthorizationGrantType.REFRESH_TOKEN, clientPrincipal, additionalParameters);
|
||||||
Assert.hasText(refreshToken, "refreshToken cannot be empty");
|
Assert.hasText(refreshToken, "refreshToken cannot be empty");
|
||||||
this.refreshToken = refreshToken;
|
this.refreshToken = refreshToken;
|
||||||
this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
|
this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -39,8 +39,6 @@ import org.springframework.security.oauth2.server.authorization.client.Registere
|
|||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AuthenticationProvider} implementation for OAuth 2.0 Token Introspection.
|
* An {@link AuthenticationProvider} implementation for OAuth 2.0 Token Introspection.
|
||||||
*
|
*
|
||||||
@@ -84,8 +82,8 @@ public final class OAuth2TokenIntrospectionAuthenticationProvider implements Aut
|
|||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
OAuth2TokenIntrospectionAuthenticationToken tokenIntrospectionAuthentication = (OAuth2TokenIntrospectionAuthenticationToken) authentication;
|
OAuth2TokenIntrospectionAuthenticationToken tokenIntrospectionAuthentication = (OAuth2TokenIntrospectionAuthenticationToken) authentication;
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
|
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
|
||||||
tokenIntrospectionAuthentication);
|
.getAuthenticatedClientElseThrowInvalidClient(tokenIntrospectionAuthentication);
|
||||||
|
|
||||||
OAuth2Authorization authorization = this.authorizationService
|
OAuth2Authorization authorization = this.authorizationService
|
||||||
.findByToken(tokenIntrospectionAuthentication.getToken(), null);
|
.findByToken(tokenIntrospectionAuthentication.getToken(), null);
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ public class OAuth2TokenIntrospectionAuthenticationToken extends AbstractAuthent
|
|||||||
this.clientPrincipal = clientPrincipal;
|
this.clientPrincipal = clientPrincipal;
|
||||||
this.tokenTypeHint = tokenTypeHint;
|
this.tokenTypeHint = tokenTypeHint;
|
||||||
this.additionalParameters = Collections.unmodifiableMap(
|
this.additionalParameters = Collections.unmodifiableMap(
|
||||||
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
|
||||||
this.tokenClaims = OAuth2TokenIntrospection.builder().build();
|
this.tokenClaims = OAuth2TokenIntrospection.builder().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,8 +29,6 @@ import org.springframework.security.oauth2.server.authorization.OAuth2Authorizat
|
|||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AuthenticationProvider} implementation for OAuth 2.0 Token Revocation.
|
* An {@link AuthenticationProvider} implementation for OAuth 2.0 Token Revocation.
|
||||||
*
|
*
|
||||||
@@ -62,8 +60,8 @@ public final class OAuth2TokenRevocationAuthenticationProvider implements Authen
|
|||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication = (OAuth2TokenRevocationAuthenticationToken) authentication;
|
OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication = (OAuth2TokenRevocationAuthenticationToken) authentication;
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
|
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
|
||||||
tokenRevocationAuthentication);
|
.getAuthenticatedClientElseThrowInvalidClient(tokenRevocationAuthentication);
|
||||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
||||||
|
|
||||||
OAuth2Authorization authorization = this.authorizationService
|
OAuth2Authorization authorization = this.authorizationService
|
||||||
|
|||||||
@@ -34,9 +34,9 @@ import org.springframework.util.StringUtils;
|
|||||||
* @author Anoop Garlapati
|
* @author Anoop Garlapati
|
||||||
* @author Ovidiu Popa
|
* @author Ovidiu Popa
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
|
* @since 0.0.1
|
||||||
* @see RegisteredClientRepository
|
* @see RegisteredClientRepository
|
||||||
* @see RegisteredClient
|
* @see RegisteredClient
|
||||||
* @since 0.0.1
|
|
||||||
*/
|
*/
|
||||||
public final class InMemoryRegisteredClientRepository implements RegisteredClientRepository {
|
public final class InMemoryRegisteredClientRepository implements RegisteredClientRepository {
|
||||||
|
|
||||||
@@ -98,7 +98,7 @@ public final class InMemoryRegisteredClientRepository implements RegisteredClien
|
|||||||
|
|
||||||
private void assertUniqueIdentifiers(RegisteredClient registeredClient,
|
private void assertUniqueIdentifiers(RegisteredClient registeredClient,
|
||||||
Map<String, RegisteredClient> registrations) {
|
Map<String, RegisteredClient> registrations) {
|
||||||
registrations.values().forEach(registration -> {
|
registrations.values().forEach((registration) -> {
|
||||||
if (registeredClient.getId().equals(registration.getId())) {
|
if (registeredClient.getId().equals(registration.getId())) {
|
||||||
throw new IllegalArgumentException("Registered client must be unique. " + "Found duplicate identifier: "
|
throw new IllegalArgumentException("Registered client must be unique. " + "Found duplicate identifier: "
|
||||||
+ registeredClient.getId());
|
+ registeredClient.getId());
|
||||||
|
|||||||
@@ -82,17 +82,6 @@ import org.springframework.util.StringUtils;
|
|||||||
@ImportRuntimeHints(JdbcRegisteredClientRepository.JdbcRegisteredClientRepositoryRuntimeHintsRegistrar.class)
|
@ImportRuntimeHints(JdbcRegisteredClientRepository.JdbcRegisteredClientRepositoryRuntimeHintsRegistrar.class)
|
||||||
public class JdbcRegisteredClientRepository implements RegisteredClientRepository {
|
public class JdbcRegisteredClientRepository implements RegisteredClientRepository {
|
||||||
|
|
||||||
static class JdbcRegisteredClientRepositoryRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
|
||||||
hints.resources()
|
|
||||||
.registerResource(new ClassPathResource(
|
|
||||||
"org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql"));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
private static final String COLUMN_NAMES = "id, "
|
private static final String COLUMN_NAMES = "id, "
|
||||||
+ "client_id, "
|
+ "client_id, "
|
||||||
@@ -279,15 +268,15 @@ public class JdbcRegisteredClientRepository implements RegisteredClientRepositor
|
|||||||
// @formatter:off
|
// @formatter:off
|
||||||
RegisteredClient.Builder builder = RegisteredClient.withId(rs.getString("id"))
|
RegisteredClient.Builder builder = RegisteredClient.withId(rs.getString("id"))
|
||||||
.clientId(rs.getString("client_id"))
|
.clientId(rs.getString("client_id"))
|
||||||
.clientIdIssuedAt(clientIdIssuedAt != null ? clientIdIssuedAt.toInstant() : null)
|
.clientIdIssuedAt((clientIdIssuedAt != null) ? clientIdIssuedAt.toInstant() : null)
|
||||||
.clientSecret(rs.getString("client_secret"))
|
.clientSecret(rs.getString("client_secret"))
|
||||||
.clientSecretExpiresAt(clientSecretExpiresAt != null ? clientSecretExpiresAt.toInstant() : null)
|
.clientSecretExpiresAt((clientSecretExpiresAt != null) ? clientSecretExpiresAt.toInstant() : null)
|
||||||
.clientName(rs.getString("client_name"))
|
.clientName(rs.getString("client_name"))
|
||||||
.clientAuthenticationMethods((authenticationMethods) ->
|
.clientAuthenticationMethods((authenticationMethods) ->
|
||||||
clientAuthenticationMethods.forEach(authenticationMethod ->
|
clientAuthenticationMethods.forEach((authenticationMethod) ->
|
||||||
authenticationMethods.add(resolveClientAuthenticationMethod(authenticationMethod))))
|
authenticationMethods.add(resolveClientAuthenticationMethod(authenticationMethod))))
|
||||||
.authorizationGrantTypes((grantTypes) ->
|
.authorizationGrantTypes((grantTypes) ->
|
||||||
authorizationGrantTypes.forEach(grantType ->
|
authorizationGrantTypes.forEach((grantType) ->
|
||||||
grantTypes.add(resolveAuthorizationGrantType(grantType))))
|
grantTypes.add(resolveAuthorizationGrantType(grantType))))
|
||||||
.redirectUris((uris) -> uris.addAll(redirectUris))
|
.redirectUris((uris) -> uris.addAll(redirectUris))
|
||||||
.postLogoutRedirectUris((uris) -> uris.addAll(postLogoutRedirectUris))
|
.postLogoutRedirectUris((uris) -> uris.addAll(postLogoutRedirectUris))
|
||||||
@@ -374,22 +363,22 @@ public class JdbcRegisteredClientRepository implements RegisteredClientRepositor
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<SqlParameterValue> apply(RegisteredClient registeredClient) {
|
public List<SqlParameterValue> apply(RegisteredClient registeredClient) {
|
||||||
Timestamp clientIdIssuedAt = registeredClient.getClientIdIssuedAt() != null
|
Timestamp clientIdIssuedAt = (registeredClient.getClientIdIssuedAt() != null)
|
||||||
? Timestamp.from(registeredClient.getClientIdIssuedAt()) : Timestamp.from(Instant.now());
|
? Timestamp.from(registeredClient.getClientIdIssuedAt()) : Timestamp.from(Instant.now());
|
||||||
|
|
||||||
Timestamp clientSecretExpiresAt = registeredClient.getClientSecretExpiresAt() != null
|
Timestamp clientSecretExpiresAt = (registeredClient.getClientSecretExpiresAt() != null)
|
||||||
? Timestamp.from(registeredClient.getClientSecretExpiresAt()) : null;
|
? Timestamp.from(registeredClient.getClientSecretExpiresAt()) : null;
|
||||||
|
|
||||||
List<String> clientAuthenticationMethods = new ArrayList<>(
|
List<String> clientAuthenticationMethods = new ArrayList<>(
|
||||||
registeredClient.getClientAuthenticationMethods().size());
|
registeredClient.getClientAuthenticationMethods().size());
|
||||||
registeredClient.getClientAuthenticationMethods()
|
registeredClient.getClientAuthenticationMethods()
|
||||||
.forEach(clientAuthenticationMethod -> clientAuthenticationMethods
|
.forEach((clientAuthenticationMethod) -> clientAuthenticationMethods
|
||||||
.add(clientAuthenticationMethod.getValue()));
|
.add(clientAuthenticationMethod.getValue()));
|
||||||
|
|
||||||
List<String> authorizationGrantTypes = new ArrayList<>(
|
List<String> authorizationGrantTypes = new ArrayList<>(
|
||||||
registeredClient.getAuthorizationGrantTypes().size());
|
registeredClient.getAuthorizationGrantTypes().size());
|
||||||
registeredClient.getAuthorizationGrantTypes()
|
registeredClient.getAuthorizationGrantTypes()
|
||||||
.forEach(authorizationGrantType -> authorizationGrantTypes.add(authorizationGrantType.getValue()));
|
.forEach((authorizationGrantType) -> authorizationGrantTypes.add(authorizationGrantType.getValue()));
|
||||||
|
|
||||||
return Arrays.asList(new SqlParameterValue(Types.VARCHAR, registeredClient.getId()),
|
return Arrays.asList(new SqlParameterValue(Types.VARCHAR, registeredClient.getId()),
|
||||||
new SqlParameterValue(Types.VARCHAR, registeredClient.getClientId()),
|
new SqlParameterValue(Types.VARCHAR, registeredClient.getClientId()),
|
||||||
@@ -431,4 +420,15 @@ public class JdbcRegisteredClientRepository implements RegisteredClientRepositor
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static class JdbcRegisteredClientRepositoryRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
||||||
|
hints.resources()
|
||||||
|
.registerResource(new ClassPathResource(
|
||||||
|
"org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,9 +40,9 @@ import org.springframework.util.StringUtils;
|
|||||||
*
|
*
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author Anoop Garlapati
|
* @author Anoop Garlapati
|
||||||
|
* @since 0.0.1
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-2">Section 2
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-2">Section 2
|
||||||
* Client Registration</a>
|
* Client Registration</a>
|
||||||
* @since 0.0.1
|
|
||||||
*/
|
*/
|
||||||
public class RegisteredClient implements Serializable {
|
public class RegisteredClient implements Serializable {
|
||||||
|
|
||||||
@@ -594,7 +594,7 @@ public class RegisteredClient implements Serializable {
|
|||||||
|
|
||||||
private static boolean validateScope(String scope) {
|
private static boolean validateScope(String scope) {
|
||||||
return scope == null || scope.chars()
|
return scope == null || scope.chars()
|
||||||
.allMatch(c -> withinTheRangeOf(c, 0x21, 0x21) || withinTheRangeOf(c, 0x23, 0x5B)
|
.allMatch((c) -> withinTheRangeOf(c, 0x21, 0x21) || withinTheRangeOf(c, 0x23, 0x5B)
|
||||||
|| withinTheRangeOf(c, 0x5D, 0x7E));
|
|| withinTheRangeOf(c, 0x5D, 0x7E));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,8 +23,8 @@ import org.springframework.lang.Nullable;
|
|||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author Anoop Garlapati
|
* @author Anoop Garlapati
|
||||||
* @author Ovidiu Popa
|
* @author Ovidiu Popa
|
||||||
* @see RegisteredClient
|
|
||||||
* @since 0.0.1
|
* @since 0.0.1
|
||||||
|
* @see RegisteredClient
|
||||||
*/
|
*/
|
||||||
public interface RegisteredClientRepository {
|
public interface RegisteredClientRepository {
|
||||||
|
|
||||||
|
|||||||
@@ -64,10 +64,10 @@ public class OAuth2AuthorizationServerConfiguration {
|
|||||||
|
|
||||||
http
|
http
|
||||||
.securityMatcher(endpointsMatcher)
|
.securityMatcher(endpointsMatcher)
|
||||||
.authorizeHttpRequests(authorize ->
|
.authorizeHttpRequests((authorize) ->
|
||||||
authorize.anyRequest().authenticated()
|
authorize.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher))
|
.csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher))
|
||||||
.apply(authorizationServerConfigurer);
|
.apply(authorizationServerConfigurer);
|
||||||
}
|
}
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|||||||
@@ -88,6 +88,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OAuth2AuthorizationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OAuth2AuthorizationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -225,7 +226,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C
|
|||||||
|
|
||||||
void addAuthorizationCodeRequestAuthenticationValidator(
|
void addAuthorizationCodeRequestAuthenticationValidator(
|
||||||
Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> authenticationValidator) {
|
Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> authenticationValidator) {
|
||||||
this.authorizationCodeRequestAuthenticationValidator = this.authorizationCodeRequestAuthenticationValidator == null
|
this.authorizationCodeRequestAuthenticationValidator = (this.authorizationCodeRequestAuthenticationValidator == null)
|
||||||
? authenticationValidator
|
? authenticationValidator
|
||||||
: this.authorizationCodeRequestAuthenticationValidator.andThen(authenticationValidator);
|
: this.authorizationCodeRequestAuthenticationValidator.andThen(authenticationValidator);
|
||||||
}
|
}
|
||||||
@@ -251,7 +252,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C
|
|||||||
}
|
}
|
||||||
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
||||||
authenticationProviders.forEach(
|
authenticationProviders.forEach(
|
||||||
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -322,7 +322,7 @@ public final class OAuth2AuthorizationServerConfigurer
|
|||||||
}
|
}
|
||||||
|
|
||||||
List<RequestMatcher> requestMatchers = new ArrayList<>();
|
List<RequestMatcher> requestMatchers = new ArrayList<>();
|
||||||
this.configurers.values().forEach(configurer -> {
|
this.configurers.values().forEach((configurer) -> {
|
||||||
configurer.init(httpSecurity);
|
configurer.init(httpSecurity);
|
||||||
requestMatchers.add(configurer.getRequestMatcher());
|
requestMatchers.add(configurer.getRequestMatcher());
|
||||||
});
|
});
|
||||||
@@ -345,7 +345,7 @@ public final class OAuth2AuthorizationServerConfigurer
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void configure(HttpSecurity httpSecurity) {
|
public void configure(HttpSecurity httpSecurity) {
|
||||||
this.configurers.values().forEach(configurer -> configurer.configure(httpSecurity));
|
this.configurers.values().forEach((configurer) -> configurer.configure(httpSecurity));
|
||||||
|
|
||||||
AuthorizationServerSettings authorizationServerSettings = OAuth2ConfigurerUtils
|
AuthorizationServerSettings authorizationServerSettings = OAuth2ConfigurerUtils
|
||||||
.getAuthorizationServerSettings(httpSecurity);
|
.getAuthorizationServerSettings(httpSecurity);
|
||||||
@@ -401,7 +401,7 @@ public final class OAuth2AuthorizationServerConfigurer
|
|||||||
|
|
||||||
private <T extends AbstractOAuth2Configurer> RequestMatcher getRequestMatcher(Class<T> configurerType) {
|
private <T extends AbstractOAuth2Configurer> RequestMatcher getRequestMatcher(Class<T> configurerType) {
|
||||||
T configurer = getConfigurer(configurerType);
|
T configurer = getConfigurer(configurerType);
|
||||||
return configurer != null ? configurer.getRequestMatcher() : null;
|
return (configurer != null) ? configurer.getRequestMatcher() : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void validateAuthorizationServerSettings(AuthorizationServerSettings authorizationServerSettings) {
|
private static void validateAuthorizationServerSettings(AuthorizationServerSettings authorizationServerSettings) {
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OAuth2AuthorizationServerMetadataEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OAuth2AuthorizationServerMetadataEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -67,7 +68,7 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A
|
|||||||
|
|
||||||
void addDefaultAuthorizationServerMetadataCustomizer(
|
void addDefaultAuthorizationServerMetadataCustomizer(
|
||||||
Consumer<OAuth2AuthorizationServerMetadata.Builder> defaultAuthorizationServerMetadataCustomizer) {
|
Consumer<OAuth2AuthorizationServerMetadata.Builder> defaultAuthorizationServerMetadataCustomizer) {
|
||||||
this.defaultAuthorizationServerMetadataCustomizer = this.defaultAuthorizationServerMetadataCustomizer == null
|
this.defaultAuthorizationServerMetadataCustomizer = (this.defaultAuthorizationServerMetadataCustomizer == null)
|
||||||
? defaultAuthorizationServerMetadataCustomizer : this.defaultAuthorizationServerMetadataCustomizer
|
? defaultAuthorizationServerMetadataCustomizer : this.defaultAuthorizationServerMetadataCustomizer
|
||||||
.andThen(defaultAuthorizationServerMetadataCustomizer);
|
.andThen(defaultAuthorizationServerMetadataCustomizer);
|
||||||
}
|
}
|
||||||
@@ -101,9 +102,9 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A
|
|||||||
authorizationServerMetadataCustomizer = this.defaultAuthorizationServerMetadataCustomizer;
|
authorizationServerMetadataCustomizer = this.defaultAuthorizationServerMetadataCustomizer;
|
||||||
}
|
}
|
||||||
if (this.authorizationServerMetadataCustomizer != null) {
|
if (this.authorizationServerMetadataCustomizer != null) {
|
||||||
authorizationServerMetadataCustomizer = authorizationServerMetadataCustomizer == null
|
authorizationServerMetadataCustomizer = (authorizationServerMetadataCustomizer != null)
|
||||||
? this.authorizationServerMetadataCustomizer
|
? authorizationServerMetadataCustomizer.andThen(this.authorizationServerMetadataCustomizer)
|
||||||
: authorizationServerMetadataCustomizer.andThen(this.authorizationServerMetadataCustomizer);
|
: this.authorizationServerMetadataCustomizer;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return authorizationServerMetadataCustomizer;
|
return authorizationServerMetadataCustomizer;
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ public final class OAuth2ClientAuthenticationConfigurer extends AbstractOAuth2Co
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OAuth2ClientAuthenticationConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OAuth2ClientAuthenticationConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -204,7 +205,7 @@ public final class OAuth2ClientAuthenticationConfigurer extends AbstractOAuth2Co
|
|||||||
}
|
}
|
||||||
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
||||||
authenticationProviders.forEach(
|
authenticationProviders.forEach(
|
||||||
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -240,7 +240,7 @@ final class OAuth2ConfigurerUtils {
|
|||||||
if (names.length > 1) {
|
if (names.length > 1) {
|
||||||
throw new NoUniqueBeanDefinitionException(type, names);
|
throw new NoUniqueBeanDefinitionException(type, names);
|
||||||
}
|
}
|
||||||
return names.length == 1 ? (T) context.getBean(names[0]) : null;
|
return (names.length == 1) ? (T) context.getBean(names[0]) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ public final class OAuth2DeviceAuthorizationEndpointConfigurer extends AbstractO
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OAuth2DeviceAuthorizationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OAuth2DeviceAuthorizationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -210,7 +211,7 @@ public final class OAuth2DeviceAuthorizationEndpointConfigurer extends AbstractO
|
|||||||
}
|
}
|
||||||
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
||||||
authenticationProviders
|
authenticationProviders
|
||||||
.forEach(authenticationProvider -> builder.authenticationProvider(postProcess(authenticationProvider)));
|
.forEach((authenticationProvider) -> builder.authenticationProvider(postProcess(authenticationProvider)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ public final class OAuth2DeviceVerificationEndpointConfigurer extends AbstractOA
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OAuth2DeviceVerificationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OAuth2DeviceVerificationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -247,7 +248,7 @@ public final class OAuth2DeviceVerificationEndpointConfigurer extends AbstractOA
|
|||||||
}
|
}
|
||||||
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
||||||
authenticationProviders
|
authenticationProviders
|
||||||
.forEach(authenticationProvider -> builder.authenticationProvider(postProcess(authenticationProvider)));
|
.forEach((authenticationProvider) -> builder.authenticationProvider(postProcess(authenticationProvider)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ public final class OAuth2TokenEndpointConfigurer extends AbstractOAuth2Configure
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OAuth2TokenEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OAuth2TokenEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -198,7 +199,7 @@ public final class OAuth2TokenEndpointConfigurer extends AbstractOAuth2Configure
|
|||||||
}
|
}
|
||||||
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
||||||
authenticationProviders.forEach(
|
authenticationProviders.forEach(
|
||||||
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ public final class OAuth2TokenIntrospectionEndpointConfigurer extends AbstractOA
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OAuth2TokenIntrospectionEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OAuth2TokenIntrospectionEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -193,7 +194,7 @@ public final class OAuth2TokenIntrospectionEndpointConfigurer extends AbstractOA
|
|||||||
}
|
}
|
||||||
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
||||||
authenticationProviders.forEach(
|
authenticationProviders.forEach(
|
||||||
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ public final class OAuth2TokenRevocationEndpointConfigurer extends AbstractOAuth
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OAuth2TokenRevocationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OAuth2TokenRevocationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -192,7 +193,7 @@ public final class OAuth2TokenRevocationEndpointConfigurer extends AbstractOAuth
|
|||||||
}
|
}
|
||||||
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
||||||
authenticationProviders.forEach(
|
authenticationProviders.forEach(
|
||||||
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ public final class OidcClientRegistrationEndpointConfigurer extends AbstractOAut
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OidcClientRegistrationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OidcClientRegistrationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -205,7 +206,7 @@ public final class OidcClientRegistrationEndpointConfigurer extends AbstractOAut
|
|||||||
}
|
}
|
||||||
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
||||||
authenticationProviders.forEach(
|
authenticationProviders.forEach(
|
||||||
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OidcConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OidcConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -117,7 +118,7 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer {
|
|||||||
@Override
|
@Override
|
||||||
void init(HttpSecurity httpSecurity) {
|
void init(HttpSecurity httpSecurity) {
|
||||||
List<RequestMatcher> requestMatchers = new ArrayList<>();
|
List<RequestMatcher> requestMatchers = new ArrayList<>();
|
||||||
this.configurers.values().forEach(configurer -> {
|
this.configurers.values().forEach((configurer) -> {
|
||||||
configurer.init(httpSecurity);
|
configurer.init(httpSecurity);
|
||||||
requestMatchers.add(configurer.getRequestMatcher());
|
requestMatchers.add(configurer.getRequestMatcher());
|
||||||
});
|
});
|
||||||
@@ -147,7 +148,7 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
this.configurers.values().forEach(configurer -> configurer.configure(httpSecurity));
|
this.configurers.values().forEach((configurer) -> configurer.configure(httpSecurity));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ public final class OidcLogoutEndpointConfigurer extends AbstractOAuth2Configurer
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OidcLogoutEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OidcLogoutEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -179,7 +180,7 @@ public final class OidcLogoutEndpointConfigurer extends AbstractOAuth2Configurer
|
|||||||
}
|
}
|
||||||
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
||||||
authenticationProviders.forEach(
|
authenticationProviders.forEach(
|
||||||
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OidcProviderConfigurationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OidcProviderConfigurationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -67,7 +68,7 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO
|
|||||||
|
|
||||||
void addDefaultProviderConfigurationCustomizer(
|
void addDefaultProviderConfigurationCustomizer(
|
||||||
Consumer<OidcProviderConfiguration.Builder> defaultProviderConfigurationCustomizer) {
|
Consumer<OidcProviderConfiguration.Builder> defaultProviderConfigurationCustomizer) {
|
||||||
this.defaultProviderConfigurationCustomizer = this.defaultProviderConfigurationCustomizer == null
|
this.defaultProviderConfigurationCustomizer = (this.defaultProviderConfigurationCustomizer == null)
|
||||||
? defaultProviderConfigurationCustomizer
|
? defaultProviderConfigurationCustomizer
|
||||||
: this.defaultProviderConfigurationCustomizer.andThen(defaultProviderConfigurationCustomizer);
|
: this.defaultProviderConfigurationCustomizer.andThen(defaultProviderConfigurationCustomizer);
|
||||||
}
|
}
|
||||||
@@ -99,9 +100,9 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO
|
|||||||
providerConfigurationCustomizer = this.defaultProviderConfigurationCustomizer;
|
providerConfigurationCustomizer = this.defaultProviderConfigurationCustomizer;
|
||||||
}
|
}
|
||||||
if (this.providerConfigurationCustomizer != null) {
|
if (this.providerConfigurationCustomizer != null) {
|
||||||
providerConfigurationCustomizer = providerConfigurationCustomizer == null
|
providerConfigurationCustomizer = (providerConfigurationCustomizer != null)
|
||||||
? this.providerConfigurationCustomizer
|
? providerConfigurationCustomizer.andThen(this.providerConfigurationCustomizer)
|
||||||
: providerConfigurationCustomizer.andThen(this.providerConfigurationCustomizer);
|
: this.providerConfigurationCustomizer;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return providerConfigurationCustomizer;
|
return providerConfigurationCustomizer;
|
||||||
|
|||||||
@@ -82,6 +82,7 @@ public final class OidcUserInfoEndpointConfigurer extends AbstractOAuth2Configur
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict for internal use only.
|
* Restrict for internal use only.
|
||||||
|
* @param objectPostProcessor an {@code ObjectPostProcessor}
|
||||||
*/
|
*/
|
||||||
OidcUserInfoEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
OidcUserInfoEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
|
||||||
super(objectPostProcessor);
|
super(objectPostProcessor);
|
||||||
@@ -223,7 +224,7 @@ public final class OidcUserInfoEndpointConfigurer extends AbstractOAuth2Configur
|
|||||||
}
|
}
|
||||||
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
this.authenticationProvidersConsumer.accept(authenticationProviders);
|
||||||
authenticationProviders.forEach(
|
authenticationProviders.forEach(
|
||||||
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import org.springframework.util.ClassUtils;
|
|||||||
* Utility methods for {@link HttpMessageConverter}'s.
|
* Utility methods for {@link HttpMessageConverter}'s.
|
||||||
*
|
*
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author luamas
|
* @author l uamas
|
||||||
* @since 0.1.1
|
* @since 0.1.1
|
||||||
*/
|
*/
|
||||||
final class HttpMessageConverters {
|
final class HttpMessageConverters {
|
||||||
|
|||||||
@@ -85,16 +85,17 @@ public final class OidcClientRegistration implements OidcClientMetadataClaimAcce
|
|||||||
/**
|
/**
|
||||||
* Constructs a new {@link Builder} with the provided claims.
|
* Constructs a new {@link Builder} with the provided claims.
|
||||||
* @param claims the claims to initialize the builder
|
* @param claims the claims to initialize the builder
|
||||||
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public static Builder withClaims(Map<String, Object> claims) {
|
public static Builder withClaims(Map<String, Object> claims) {
|
||||||
Assert.notEmpty(claims, "claims cannot be empty");
|
Assert.notEmpty(claims, "claims cannot be empty");
|
||||||
return new Builder().claims(c -> c.putAll(claims));
|
return new Builder().claims((c) -> c.putAll(claims));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helps configure an {@link OidcClientRegistration}.
|
* Helps configure an {@link OidcClientRegistration}.
|
||||||
*/
|
*/
|
||||||
public static class Builder {
|
public static final class Builder {
|
||||||
|
|
||||||
private final Map<String, Object> claims = new LinkedHashMap<>();
|
private final Map<String, Object> claims = new LinkedHashMap<>();
|
||||||
|
|
||||||
@@ -434,7 +435,7 @@ public final class OidcClientRegistration implements OidcClientMetadataClaimAcce
|
|||||||
private void addClaimToClaimList(String name, String value) {
|
private void addClaimToClaimList(String name, String value) {
|
||||||
Assert.hasText(name, "name cannot be empty");
|
Assert.hasText(name, "name cannot be empty");
|
||||||
Assert.notNull(value, "value cannot be null");
|
Assert.notNull(value, "value cannot be null");
|
||||||
this.claims.computeIfAbsent(name, k -> new LinkedList<String>());
|
this.claims.computeIfAbsent(name, (k) -> new LinkedList<String>());
|
||||||
((List<String>) this.claims.get(name)).add(value);
|
((List<String>) this.claims.get(name)).add(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -442,7 +443,7 @@ public final class OidcClientRegistration implements OidcClientMetadataClaimAcce
|
|||||||
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
|
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
|
||||||
Assert.hasText(name, "name cannot be empty");
|
Assert.hasText(name, "name cannot be empty");
|
||||||
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
|
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
|
||||||
this.claims.computeIfAbsent(name, k -> new LinkedList<String>());
|
this.claims.computeIfAbsent(name, (k) -> new LinkedList<String>());
|
||||||
List<String> values = (List<String>) this.claims.get(name);
|
List<String> values = (List<String>) this.claims.get(name);
|
||||||
valuesConsumer.accept(values);
|
valuesConsumer.accept(values);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,16 +58,17 @@ public final class OidcProviderConfiguration extends AbstractOAuth2Authorization
|
|||||||
/**
|
/**
|
||||||
* Constructs a new {@link Builder} with the provided claims.
|
* Constructs a new {@link Builder} with the provided claims.
|
||||||
* @param claims the claims to initialize the builder
|
* @param claims the claims to initialize the builder
|
||||||
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public static Builder withClaims(Map<String, Object> claims) {
|
public static Builder withClaims(Map<String, Object> claims) {
|
||||||
Assert.notEmpty(claims, "claims cannot be empty");
|
Assert.notEmpty(claims, "claims cannot be empty");
|
||||||
return new Builder().claims(c -> c.putAll(claims));
|
return new Builder().claims((c) -> c.putAll(claims));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helps configure an {@link OidcProviderConfiguration}.
|
* Helps configure an {@link OidcProviderConfiguration}.
|
||||||
*/
|
*/
|
||||||
public static class Builder extends AbstractBuilder<OidcProviderConfiguration, Builder> {
|
public static final class Builder extends AbstractBuilder<OidcProviderConfiguration, Builder> {
|
||||||
|
|
||||||
private Builder() {
|
private Builder() {
|
||||||
}
|
}
|
||||||
@@ -191,7 +192,7 @@ public final class OidcProviderConfiguration extends AbstractOAuth2Authorization
|
|||||||
private void addClaimToClaimList(String name, String value) {
|
private void addClaimToClaimList(String name, String value) {
|
||||||
Assert.hasText(name, "name cannot be empty");
|
Assert.hasText(name, "name cannot be empty");
|
||||||
Assert.notNull(value, "value cannot be null");
|
Assert.notNull(value, "value cannot be null");
|
||||||
getClaims().computeIfAbsent(name, k -> new LinkedList<String>());
|
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
|
||||||
((List<String>) getClaims().get(name)).add(value);
|
((List<String>) getClaims().get(name)).add(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,7 +200,7 @@ public final class OidcProviderConfiguration extends AbstractOAuth2Authorization
|
|||||||
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
|
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
|
||||||
Assert.hasText(name, "name cannot be empty");
|
Assert.hasText(name, "name cannot be empty");
|
||||||
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
|
Assert.notNull(valuesConsumer, "valuesConsumer cannot be null");
|
||||||
getClaims().computeIfAbsent(name, k -> new LinkedList<String>());
|
getClaims().computeIfAbsent(name, (k) -> new LinkedList<String>());
|
||||||
List<String> values = (List<String>) getClaims().get(name);
|
List<String> values = (List<String>) getClaims().get(name);
|
||||||
valuesConsumer.accept(values);
|
valuesConsumer.accept(values);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -217,7 +217,7 @@ public final class OidcUserInfoAuthenticationProvider implements AuthenticationP
|
|||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Object> requestedClaims = new HashMap<>(claims);
|
Map<String, Object> requestedClaims = new HashMap<>(claims);
|
||||||
requestedClaims.keySet().removeIf(claimName -> !scopeRequestedClaimNames.contains(claimName));
|
requestedClaims.keySet().removeIf((claimName) -> !scopeRequestedClaimNames.contains(claimName));
|
||||||
|
|
||||||
return requestedClaims;
|
return requestedClaims;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,31 +62,35 @@ public final class OidcClientRegistrationRegisteredClientConverter
|
|||||||
builder
|
builder
|
||||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
|
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
|
||||||
.clientSecret(CLIENT_SECRET_GENERATOR.generateKey());
|
.clientSecret(CLIENT_SECRET_GENERATOR.generateKey());
|
||||||
} else if (ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
|
}
|
||||||
|
else if (ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
|
||||||
builder
|
builder
|
||||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
|
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
|
||||||
.clientSecret(CLIENT_SECRET_GENERATOR.generateKey());
|
.clientSecret(CLIENT_SECRET_GENERATOR.generateKey());
|
||||||
} else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
|
}
|
||||||
|
else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
|
||||||
builder.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT);
|
builder.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT);
|
||||||
} else {
|
}
|
||||||
|
else {
|
||||||
builder
|
builder
|
||||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
|
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
|
||||||
.clientSecret(CLIENT_SECRET_GENERATOR.generateKey());
|
.clientSecret(CLIENT_SECRET_GENERATOR.generateKey());
|
||||||
}
|
}
|
||||||
|
|
||||||
builder.redirectUris(redirectUris ->
|
builder.redirectUris((redirectUris) ->
|
||||||
redirectUris.addAll(clientRegistration.getRedirectUris()));
|
redirectUris.addAll(clientRegistration.getRedirectUris()));
|
||||||
|
|
||||||
if (!CollectionUtils.isEmpty(clientRegistration.getPostLogoutRedirectUris())) {
|
if (!CollectionUtils.isEmpty(clientRegistration.getPostLogoutRedirectUris())) {
|
||||||
builder.postLogoutRedirectUris(postLogoutRedirectUris ->
|
builder.postLogoutRedirectUris((postLogoutRedirectUris) ->
|
||||||
postLogoutRedirectUris.addAll(clientRegistration.getPostLogoutRedirectUris()));
|
postLogoutRedirectUris.addAll(clientRegistration.getPostLogoutRedirectUris()));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!CollectionUtils.isEmpty(clientRegistration.getGrantTypes())) {
|
if (!CollectionUtils.isEmpty(clientRegistration.getGrantTypes())) {
|
||||||
builder.authorizationGrantTypes(authorizationGrantTypes ->
|
builder.authorizationGrantTypes((authorizationGrantTypes) ->
|
||||||
clientRegistration.getGrantTypes().forEach(grantType ->
|
clientRegistration.getGrantTypes().forEach((grantType) ->
|
||||||
authorizationGrantTypes.add(new AuthorizationGrantType(grantType))));
|
authorizationGrantTypes.add(new AuthorizationGrantType(grantType))));
|
||||||
} else {
|
}
|
||||||
|
else {
|
||||||
builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
|
builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
|
||||||
}
|
}
|
||||||
if (CollectionUtils.isEmpty(clientRegistration.getResponseTypes()) ||
|
if (CollectionUtils.isEmpty(clientRegistration.getResponseTypes()) ||
|
||||||
@@ -95,7 +99,7 @@ public final class OidcClientRegistrationRegisteredClientConverter
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
|
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
|
||||||
builder.scopes(scopes ->
|
builder.scopes((scopes) ->
|
||||||
scopes.addAll(clientRegistration.getScopes()));
|
scopes.addAll(clientRegistration.getScopes()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,7 +113,8 @@ public final class OidcClientRegistrationRegisteredClientConverter
|
|||||||
macAlgorithm = MacAlgorithm.HS256;
|
macAlgorithm = MacAlgorithm.HS256;
|
||||||
}
|
}
|
||||||
clientSettingsBuilder.tokenEndpointAuthenticationSigningAlgorithm(macAlgorithm);
|
clientSettingsBuilder.tokenEndpointAuthenticationSigningAlgorithm(macAlgorithm);
|
||||||
} else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
|
}
|
||||||
|
else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) {
|
||||||
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.from(clientRegistration.getTokenEndpointAuthenticationSigningAlgorithm());
|
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.from(clientRegistration.getTokenEndpointAuthenticationSigningAlgorithm());
|
||||||
if (signatureAlgorithm == null) {
|
if (signatureAlgorithm == null) {
|
||||||
signatureAlgorithm = SignatureAlgorithm.RS256;
|
signatureAlgorithm = SignatureAlgorithm.RS256;
|
||||||
|
|||||||
@@ -49,16 +49,16 @@ public final class RegisteredClientOidcClientRegistrationConverter
|
|||||||
builder.clientSecret(registeredClient.getClientSecret());
|
builder.clientSecret(registeredClient.getClientSecret());
|
||||||
}
|
}
|
||||||
|
|
||||||
builder.redirectUris(redirectUris ->
|
builder.redirectUris((redirectUris) ->
|
||||||
redirectUris.addAll(registeredClient.getRedirectUris()));
|
redirectUris.addAll(registeredClient.getRedirectUris()));
|
||||||
|
|
||||||
if (!CollectionUtils.isEmpty(registeredClient.getPostLogoutRedirectUris())) {
|
if (!CollectionUtils.isEmpty(registeredClient.getPostLogoutRedirectUris())) {
|
||||||
builder.postLogoutRedirectUris(postLogoutRedirectUris ->
|
builder.postLogoutRedirectUris((postLogoutRedirectUris) ->
|
||||||
postLogoutRedirectUris.addAll(registeredClient.getPostLogoutRedirectUris()));
|
postLogoutRedirectUris.addAll(registeredClient.getPostLogoutRedirectUris()));
|
||||||
}
|
}
|
||||||
|
|
||||||
builder.grantTypes(grantTypes ->
|
builder.grantTypes((grantTypes) ->
|
||||||
registeredClient.getAuthorizationGrantTypes().forEach(authorizationGrantType ->
|
registeredClient.getAuthorizationGrantTypes().forEach((authorizationGrantType) ->
|
||||||
grantTypes.add(authorizationGrantType.getValue())));
|
grantTypes.add(authorizationGrantType.getValue())));
|
||||||
|
|
||||||
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.AUTHORIZATION_CODE)) {
|
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.AUTHORIZATION_CODE)) {
|
||||||
@@ -66,7 +66,7 @@ public final class RegisteredClientOidcClientRegistrationConverter
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!CollectionUtils.isEmpty(registeredClient.getScopes())) {
|
if (!CollectionUtils.isEmpty(registeredClient.getScopes())) {
|
||||||
builder.scopes(scopes ->
|
builder.scopes((scopes) ->
|
||||||
scopes.addAll(registeredClient.getScopes()));
|
scopes.addAll(registeredClient.getScopes()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import org.springframework.util.ClassUtils;
|
|||||||
* Utility methods for {@link HttpMessageConverter}'s.
|
* Utility methods for {@link HttpMessageConverter}'s.
|
||||||
*
|
*
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author luamas
|
* @author l uamas
|
||||||
* @since 0.1.0
|
* @since 0.1.0
|
||||||
*/
|
*/
|
||||||
final class HttpMessageConverters {
|
final class HttpMessageConverters {
|
||||||
|
|||||||
@@ -184,7 +184,7 @@ public class OidcClientRegistrationHttpMessageConverter extends AbstractHttpMess
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
|
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
|
||||||
return source -> CLAIM_CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
|
return (source) -> CLAIM_CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Instant convertClientSecretExpiresAt(Object clientSecretExpiresAt) {
|
private static Instant convertClientSecretExpiresAt(Object clientSecretExpiresAt) {
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ public final class OidcClientRegistrationEndpointFilter extends OncePerRequestFi
|
|||||||
RequestMatcher clientConfigurationGetMatcher = new AntPathRequestMatcher(clientRegistrationEndpointUri,
|
RequestMatcher clientConfigurationGetMatcher = new AntPathRequestMatcher(clientRegistrationEndpointUri,
|
||||||
HttpMethod.GET.name());
|
HttpMethod.GET.name());
|
||||||
|
|
||||||
RequestMatcher clientIdMatcher = request -> {
|
RequestMatcher clientIdMatcher = (request) -> {
|
||||||
String clientId = request.getParameter(OAuth2ParameterNames.CLIENT_ID);
|
String clientId = request.getParameter(OAuth2ParameterNames.CLIENT_ID);
|
||||||
return StringUtils.hasText(clientId);
|
return StringUtils.hasText(clientId);
|
||||||
};
|
};
|
||||||
@@ -190,7 +190,7 @@ public final class OidcClientRegistrationEndpointFilter extends OncePerRequestFi
|
|||||||
* {@link OidcClientRegistration Client Registration Response}.
|
* {@link OidcClientRegistration Client Registration Response}.
|
||||||
* @param authenticationSuccessHandler the {@link AuthenticationSuccessHandler} used
|
* @param authenticationSuccessHandler the {@link AuthenticationSuccessHandler} used
|
||||||
* for handling an {@link OidcClientRegistrationAuthenticationToken}
|
* for handling an {@link OidcClientRegistrationAuthenticationToken}
|
||||||
* @see 0.4.0
|
* @since 0.4.0
|
||||||
*/
|
*/
|
||||||
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) {
|
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) {
|
||||||
Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null");
|
Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null");
|
||||||
|
|||||||
@@ -86,8 +86,11 @@ public abstract class AbstractSettings implements Serializable {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A builder for subclasses of {@link AbstractSettings}.
|
* A builder for subclasses of {@link AbstractSettings}.
|
||||||
|
*
|
||||||
|
* @param <T> the type of object
|
||||||
|
* @param <B> the type of the builder
|
||||||
*/
|
*/
|
||||||
protected static abstract class AbstractBuilder<T extends AbstractSettings, B extends AbstractBuilder<T, B>> {
|
protected abstract static class AbstractBuilder<T extends AbstractSettings, B extends AbstractBuilder<T, B>> {
|
||||||
|
|
||||||
private final Map<String, Object> settings = new HashMap<>();
|
private final Map<String, Object> settings = new HashMap<>();
|
||||||
|
|
||||||
|
|||||||
@@ -178,13 +178,13 @@ public final class AuthorizationServerSettings extends AbstractSettings {
|
|||||||
*/
|
*/
|
||||||
public static Builder withSettings(Map<String, Object> settings) {
|
public static Builder withSettings(Map<String, Object> settings) {
|
||||||
Assert.notEmpty(settings, "settings cannot be empty");
|
Assert.notEmpty(settings, "settings cannot be empty");
|
||||||
return new Builder().settings(s -> s.putAll(settings));
|
return new Builder().settings((s) -> s.putAll(settings));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A builder for {@link AuthorizationServerSettings}.
|
* A builder for {@link AuthorizationServerSettings}.
|
||||||
*/
|
*/
|
||||||
public final static class Builder extends AbstractBuilder<AuthorizationServerSettings, Builder> {
|
public static final class Builder extends AbstractBuilder<AuthorizationServerSettings, Builder> {
|
||||||
|
|
||||||
private Builder() {
|
private Builder() {
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,13 +107,13 @@ public final class ClientSettings extends AbstractSettings {
|
|||||||
*/
|
*/
|
||||||
public static Builder withSettings(Map<String, Object> settings) {
|
public static Builder withSettings(Map<String, Object> settings) {
|
||||||
Assert.notEmpty(settings, "settings cannot be empty");
|
Assert.notEmpty(settings, "settings cannot be empty");
|
||||||
return new Builder().settings(s -> s.putAll(settings));
|
return new Builder().settings((s) -> s.putAll(settings));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A builder for {@link ClientSettings}.
|
* A builder for {@link ClientSettings}.
|
||||||
*/
|
*/
|
||||||
public final static class Builder extends AbstractBuilder<ClientSettings, Builder> {
|
public static final class Builder extends AbstractBuilder<ClientSettings, Builder> {
|
||||||
|
|
||||||
private Builder() {
|
private Builder() {
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,6 +76,8 @@ public final class TokenSettings extends AbstractSettings {
|
|||||||
* Returns {@code true} if refresh tokens are reused when returning the access token
|
* Returns {@code true} if refresh tokens are reused when returning the access token
|
||||||
* response, or {@code false} if a new refresh token is issued. The default is
|
* response, or {@code false} if a new refresh token is issued. The default is
|
||||||
* {@code true}.
|
* {@code true}.
|
||||||
|
* @return {@code true} if refresh tokens are reused when returning the access token
|
||||||
|
* response, {@code false} otherwise
|
||||||
*/
|
*/
|
||||||
public boolean isReuseRefreshTokens() {
|
public boolean isReuseRefreshTokens() {
|
||||||
return getSetting(ConfigurationSettingNames.Token.REUSE_REFRESH_TOKENS);
|
return getSetting(ConfigurationSettingNames.Token.REUSE_REFRESH_TOKENS);
|
||||||
@@ -135,13 +137,13 @@ public final class TokenSettings extends AbstractSettings {
|
|||||||
*/
|
*/
|
||||||
public static Builder withSettings(Map<String, Object> settings) {
|
public static Builder withSettings(Map<String, Object> settings) {
|
||||||
Assert.notEmpty(settings, "settings cannot be empty");
|
Assert.notEmpty(settings, "settings cannot be empty");
|
||||||
return new Builder().settings(s -> s.putAll(settings));
|
return new Builder().settings((s) -> s.putAll(settings));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A builder for {@link TokenSettings}.
|
* A builder for {@link TokenSettings}.
|
||||||
*/
|
*/
|
||||||
public final static class Builder extends AbstractBuilder<TokenSettings, Builder> {
|
public static final class Builder extends AbstractBuilder<TokenSettings, Builder> {
|
||||||
|
|
||||||
private Builder() {
|
private Builder() {
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -124,7 +124,8 @@ public final class JwtGenerator implements OAuth2TokenGenerator<Jwt> {
|
|||||||
if (!CollectionUtils.isEmpty(context.getAuthorizedScopes())) {
|
if (!CollectionUtils.isEmpty(context.getAuthorizedScopes())) {
|
||||||
claimsBuilder.claim(OAuth2ParameterNames.SCOPE, context.getAuthorizedScopes());
|
claimsBuilder.claim(OAuth2ParameterNames.SCOPE, context.getAuthorizedScopes());
|
||||||
}
|
}
|
||||||
} else if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
|
}
|
||||||
|
else if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
|
||||||
claimsBuilder.claim(IdTokenClaimNames.AZP, registeredClient.getClientId());
|
claimsBuilder.claim(IdTokenClaimNames.AZP, registeredClient.getClientId());
|
||||||
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(context.getAuthorizationGrantType())) {
|
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(context.getAuthorizationGrantType())) {
|
||||||
OAuth2AuthorizationRequest authorizationRequest = context.getAuthorization().getAttribute(
|
OAuth2AuthorizationRequest authorizationRequest = context.getAuthorization().getAttribute(
|
||||||
@@ -138,7 +139,8 @@ public final class JwtGenerator implements OAuth2TokenGenerator<Jwt> {
|
|||||||
claimsBuilder.claim("sid", sessionInformation.getSessionId());
|
claimsBuilder.claim("sid", sessionInformation.getSessionId());
|
||||||
claimsBuilder.claim(IdTokenClaimNames.AUTH_TIME, sessionInformation.getLastRequest());
|
claimsBuilder.claim(IdTokenClaimNames.AUTH_TIME, sessionInformation.getLastRequest());
|
||||||
}
|
}
|
||||||
} else if (AuthorizationGrantType.REFRESH_TOKEN.equals(context.getAuthorizationGrantType())) {
|
}
|
||||||
|
else if (AuthorizationGrantType.REFRESH_TOKEN.equals(context.getAuthorizationGrantType())) {
|
||||||
OidcIdToken currentIdToken = context.getAuthorization().getToken(OidcIdToken.class).getToken();
|
OidcIdToken currentIdToken = context.getAuthorization().getToken(OidcIdToken.class).getToken();
|
||||||
if (currentIdToken.hasClaim("sid")) {
|
if (currentIdToken.hasClaim("sid")) {
|
||||||
claimsBuilder.claim("sid", currentIdToken.getClaim("sid"));
|
claimsBuilder.claim("sid", currentIdToken.getClaim("sid"));
|
||||||
|
|||||||
@@ -156,6 +156,7 @@ public final class OAuth2TokenClaimsSet implements OAuth2TokenClaimAccessor {
|
|||||||
* A {@code Consumer} to be provided access to the claims allowing the ability to
|
* A {@code Consumer} to be provided access to the claims allowing the ability to
|
||||||
* add, replace, or remove.
|
* add, replace, or remove.
|
||||||
* @param claimsConsumer a {@code Consumer} of the claims
|
* @param claimsConsumer a {@code Consumer} of the claims
|
||||||
|
* @return the {@link Builder}
|
||||||
*/
|
*/
|
||||||
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
|
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
|
||||||
claimsConsumer.accept(this.claims);
|
claimsConsumer.accept(this.claims);
|
||||||
|
|||||||
@@ -19,10 +19,10 @@ package org.springframework.security.oauth2.server.authorization.token;
|
|||||||
* Implementations of this interface are responsible for customizing the OAuth 2.0 Token
|
* Implementations of this interface are responsible for customizing the OAuth 2.0 Token
|
||||||
* attributes contained within the {@link OAuth2TokenContext}.
|
* attributes contained within the {@link OAuth2TokenContext}.
|
||||||
*
|
*
|
||||||
|
* @param <T> the type of the context containing the OAuth 2.0 Token attributes
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @since 0.1.0
|
* @since 0.1.0
|
||||||
* @see OAuth2TokenContext
|
* @see OAuth2TokenContext
|
||||||
* @param <T> the type of the context containing the OAuth 2.0 Token attributes
|
|
||||||
*/
|
*/
|
||||||
@FunctionalInterface
|
@FunctionalInterface
|
||||||
public interface OAuth2TokenCustomizer<T extends OAuth2TokenContext> {
|
public interface OAuth2TokenCustomizer<T extends OAuth2TokenContext> {
|
||||||
|
|||||||
@@ -24,13 +24,13 @@ import org.springframework.security.oauth2.server.authorization.OAuth2Authorizat
|
|||||||
* Implementations of this interface are responsible for generating an {@link OAuth2Token}
|
* Implementations of this interface are responsible for generating an {@link OAuth2Token}
|
||||||
* using the attributes contained in the {@link OAuth2TokenContext}.
|
* using the attributes contained in the {@link OAuth2TokenContext}.
|
||||||
*
|
*
|
||||||
|
* @param <T> the type of the OAuth 2.0 Token
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @since 0.2.3
|
* @since 0.2.3
|
||||||
* @see OAuth2Token
|
* @see OAuth2Token
|
||||||
* @see OAuth2TokenContext
|
* @see OAuth2TokenContext
|
||||||
* @see OAuth2TokenClaimsSet
|
* @see OAuth2TokenClaimsSet
|
||||||
* @see ClaimAccessor
|
* @see ClaimAccessor
|
||||||
* @param <T> the type of the OAuth 2.0 Token
|
|
||||||
*/
|
*/
|
||||||
@FunctionalInterface
|
@FunctionalInterface
|
||||||
public interface OAuth2TokenGenerator<T extends OAuth2Token> {
|
public interface OAuth2TokenGenerator<T extends OAuth2Token> {
|
||||||
|
|||||||
@@ -31,8 +31,10 @@ import org.springframework.security.oauth2.core.oidc.OidcScopes;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* For internal use only.
|
* For internal use only.
|
||||||
|
*
|
||||||
|
* @author Joe Grandja
|
||||||
*/
|
*/
|
||||||
class DefaultConsentPage {
|
final class DefaultConsentPage {
|
||||||
|
|
||||||
private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8);
|
private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
|||||||
@@ -18,16 +18,15 @@ package org.springframework.security.oauth2.server.authorization.web;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.Writer;
|
import java.io.Writer;
|
||||||
|
|
||||||
import jakarta.servlet.FilterChain;
|
|
||||||
import jakarta.servlet.ServletException;
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import com.nimbusds.jose.jwk.JWKMatcher;
|
import com.nimbusds.jose.jwk.JWKMatcher;
|
||||||
import com.nimbusds.jose.jwk.JWKSelector;
|
import com.nimbusds.jose.jwk.JWKSelector;
|
||||||
import com.nimbusds.jose.jwk.JWKSet;
|
import com.nimbusds.jose.jwk.JWKSet;
|
||||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||||
import com.nimbusds.jose.proc.SecurityContext;
|
import com.nimbusds.jose.proc.SecurityContext;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
|
|||||||
@@ -151,12 +151,12 @@ public final class OAuth2AuthorizationEndpointFilter extends OncePerRequestFilte
|
|||||||
HttpMethod.GET.name());
|
HttpMethod.GET.name());
|
||||||
RequestMatcher authorizationRequestPostMatcher = new AntPathRequestMatcher(authorizationEndpointUri,
|
RequestMatcher authorizationRequestPostMatcher = new AntPathRequestMatcher(authorizationEndpointUri,
|
||||||
HttpMethod.POST.name());
|
HttpMethod.POST.name());
|
||||||
RequestMatcher openidScopeMatcher = request -> {
|
RequestMatcher openidScopeMatcher = (request) -> {
|
||||||
String scope = request.getParameter(OAuth2ParameterNames.SCOPE);
|
String scope = request.getParameter(OAuth2ParameterNames.SCOPE);
|
||||||
return StringUtils.hasText(scope) && scope.contains(OidcScopes.OPENID);
|
return StringUtils.hasText(scope) && scope.contains(OidcScopes.OPENID);
|
||||||
};
|
};
|
||||||
RequestMatcher responseTypeParameterMatcher = request -> request
|
RequestMatcher responseTypeParameterMatcher = (
|
||||||
.getParameter(OAuth2ParameterNames.RESPONSE_TYPE) != null;
|
request) -> request.getParameter(OAuth2ParameterNames.RESPONSE_TYPE) != null;
|
||||||
|
|
||||||
RequestMatcher authorizationRequestMatcher = new OrRequestMatcher(authorizationRequestGetMatcher,
|
RequestMatcher authorizationRequestMatcher = new OrRequestMatcher(authorizationRequestGetMatcher,
|
||||||
new AndRequestMatcher(authorizationRequestPostMatcher, responseTypeParameterMatcher,
|
new AndRequestMatcher(authorizationRequestPostMatcher, responseTypeParameterMatcher,
|
||||||
|
|||||||
@@ -136,8 +136,8 @@ public final class OAuth2DeviceVerificationEndpointFilter extends OncePerRequest
|
|||||||
HttpMethod.GET.name());
|
HttpMethod.GET.name());
|
||||||
RequestMatcher verificationRequestPostMatcher = new AntPathRequestMatcher(deviceVerificationEndpointUri,
|
RequestMatcher verificationRequestPostMatcher = new AntPathRequestMatcher(deviceVerificationEndpointUri,
|
||||||
HttpMethod.POST.name());
|
HttpMethod.POST.name());
|
||||||
RequestMatcher userCodeParameterMatcher = request -> request
|
RequestMatcher userCodeParameterMatcher = (
|
||||||
.getParameter(OAuth2ParameterNames.USER_CODE) != null;
|
request) -> request.getParameter(OAuth2ParameterNames.USER_CODE) != null;
|
||||||
|
|
||||||
return new AndRequestMatcher(
|
return new AndRequestMatcher(
|
||||||
new OrRequestMatcher(verificationRequestGetMatcher, verificationRequestPostMatcher),
|
new OrRequestMatcher(verificationRequestGetMatcher, verificationRequestPostMatcher),
|
||||||
|
|||||||
@@ -51,12 +51,12 @@ import org.springframework.web.filter.OncePerRequestFilter;
|
|||||||
* @author Gerardo Roza
|
* @author Gerardo Roza
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author Gaurav Tiwari
|
* @author Gaurav Tiwari
|
||||||
|
* @since 0.1.1
|
||||||
* @see OAuth2TokenIntrospectionAuthenticationProvider
|
* @see OAuth2TokenIntrospectionAuthenticationProvider
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7662#section-2">Section 2
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7662#section-2">Section 2
|
||||||
* Introspection Endpoint</a>
|
* Introspection Endpoint</a>
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7662#section-2.1">Section
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7662#section-2.1">Section
|
||||||
* 2.1 Introspection Request</a>
|
* 2.1 Introspection Request</a>
|
||||||
* @since 0.1.1
|
|
||||||
*/
|
*/
|
||||||
public final class OAuth2TokenIntrospectionEndpointFilter extends OncePerRequestFilter {
|
public final class OAuth2TokenIntrospectionEndpointFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
|||||||
@@ -48,12 +48,12 @@ import org.springframework.web.filter.OncePerRequestFilter;
|
|||||||
* @author Vivek Babu
|
* @author Vivek Babu
|
||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author Arfat Chaus
|
* @author Arfat Chaus
|
||||||
|
* @since 0.0.3
|
||||||
* @see OAuth2TokenRevocationAuthenticationProvider
|
* @see OAuth2TokenRevocationAuthenticationProvider
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7009#section-2">Section 2
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7009#section-2">Section 2
|
||||||
* Token Revocation</a>
|
* Token Revocation</a>
|
||||||
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7009#section-2.1">Section
|
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7009#section-2.1">Section
|
||||||
* 2.1 Revocation Request</a>
|
* 2.1 Revocation Request</a>
|
||||||
* @since 0.0.3
|
|
||||||
*/
|
*/
|
||||||
public final class OAuth2TokenRevocationEndpointFilter extends OncePerRequestFilter {
|
public final class OAuth2TokenRevocationEndpointFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
|||||||
@@ -145,10 +145,10 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationConverter impleme
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static RequestMatcher createOidcRequestMatcher() {
|
private static RequestMatcher createOidcRequestMatcher() {
|
||||||
RequestMatcher postMethodMatcher = request -> "POST".equals(request.getMethod());
|
RequestMatcher postMethodMatcher = (request) -> "POST".equals(request.getMethod());
|
||||||
RequestMatcher responseTypeParameterMatcher = request -> request
|
RequestMatcher responseTypeParameterMatcher = (
|
||||||
.getParameter(OAuth2ParameterNames.RESPONSE_TYPE) != null;
|
request) -> request.getParameter(OAuth2ParameterNames.RESPONSE_TYPE) != null;
|
||||||
RequestMatcher openidScopeMatcher = request -> {
|
RequestMatcher openidScopeMatcher = (request) -> {
|
||||||
String scope = request.getParameter(OAuth2ParameterNames.SCOPE);
|
String scope = request.getParameter(OAuth2ParameterNames.SCOPE);
|
||||||
return StringUtils.hasText(scope) && scope.contains(OidcScopes.OPENID);
|
return StringUtils.hasText(scope) && scope.contains(OidcScopes.OPENID);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ import java.io.IOException;
|
|||||||
import jakarta.servlet.ServletException;
|
import jakarta.servlet.ServletException;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
import org.apache.commons.logging.Log;
|
import org.apache.commons.logging.Log;
|
||||||
import org.apache.commons.logging.LogFactory;
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
|
||||||
@@ -40,9 +39,9 @@ import org.springframework.util.Assert;
|
|||||||
* Error Response}.
|
* Error Response}.
|
||||||
*
|
*
|
||||||
* @author Dmitriy Dubson
|
* @author Dmitriy Dubson
|
||||||
|
* @since 1.2
|
||||||
* @see AuthenticationFailureHandler
|
* @see AuthenticationFailureHandler
|
||||||
* @see OAuth2ErrorHttpMessageConverter
|
* @see OAuth2ErrorHttpMessageConverter
|
||||||
* @since 1.2
|
|
||||||
*/
|
*/
|
||||||
public final class OAuth2ErrorAuthenticationFailureHandler implements AuthenticationFailureHandler {
|
public final class OAuth2ErrorAuthenticationFailureHandler implements AuthenticationFailureHandler {
|
||||||
|
|
||||||
|
|||||||
@@ -45,10 +45,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
|||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyInt;
|
import static org.mockito.ArgumentMatchers.anyInt;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.spy;
|
import static org.mockito.Mockito.spy;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link JdbcOAuth2AuthorizationConsentService}.
|
* Tests for {@link JdbcOAuth2AuthorizationConsentService}.
|
||||||
@@ -150,7 +150,8 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
|
|||||||
|
|
||||||
RegisteredClient newRegisteredClient = TestRegisteredClients.registeredClient().id("new-client").build();
|
RegisteredClient newRegisteredClient = TestRegisteredClients.registeredClient().id("new-client").build();
|
||||||
|
|
||||||
when(this.registeredClientRepository.findById(eq(newRegisteredClient.getId()))).thenReturn(newRegisteredClient);
|
given(this.registeredClientRepository.findById(eq(newRegisteredClient.getId())))
|
||||||
|
.willReturn(newRegisteredClient);
|
||||||
|
|
||||||
this.authorizationConsentService.save(expectedAuthorizationConsent);
|
this.authorizationConsentService.save(expectedAuthorizationConsent);
|
||||||
|
|
||||||
@@ -164,7 +165,7 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
|
|||||||
OAuth2AuthorizationConsent expectedAuthorizationConsent = OAuth2AuthorizationConsent.from(AUTHORIZATION_CONSENT)
|
OAuth2AuthorizationConsent expectedAuthorizationConsent = OAuth2AuthorizationConsent.from(AUTHORIZATION_CONSENT)
|
||||||
.authority(new SimpleGrantedAuthority("new.authority"))
|
.authority(new SimpleGrantedAuthority("new.authority"))
|
||||||
.build();
|
.build();
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).thenReturn(REGISTERED_CLIENT);
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
|
|
||||||
this.authorizationConsentService.save(expectedAuthorizationConsent);
|
this.authorizationConsentService.save(expectedAuthorizationConsent);
|
||||||
|
|
||||||
@@ -176,8 +177,7 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void saveLoadAuthorizationConsentWhenCustomStrategiesSetThenCalled() throws Exception {
|
public void saveLoadAuthorizationConsentWhenCustomStrategiesSetThenCalled() throws Exception {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
|
|
||||||
JdbcOAuth2AuthorizationConsentService.OAuth2AuthorizationConsentRowMapper authorizationConsentRowMapper = spy(
|
JdbcOAuth2AuthorizationConsentService.OAuth2AuthorizationConsentRowMapper authorizationConsentRowMapper = spy(
|
||||||
new JdbcOAuth2AuthorizationConsentService.OAuth2AuthorizationConsentRowMapper(
|
new JdbcOAuth2AuthorizationConsentService.OAuth2AuthorizationConsentRowMapper(
|
||||||
@@ -188,8 +188,8 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
|
|||||||
this.authorizationConsentService.setAuthorizationConsentParametersMapper(authorizationConsentParametersMapper);
|
this.authorizationConsentService.setAuthorizationConsentParametersMapper(authorizationConsentParametersMapper);
|
||||||
|
|
||||||
this.authorizationConsentService.save(AUTHORIZATION_CONSENT);
|
this.authorizationConsentService.save(AUTHORIZATION_CONSENT);
|
||||||
OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService.findById(
|
OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService
|
||||||
AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
|
.findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
|
||||||
assertThat(authorizationConsent).isEqualTo(AUTHORIZATION_CONSENT);
|
assertThat(authorizationConsent).isEqualTo(AUTHORIZATION_CONSENT);
|
||||||
verify(authorizationConsentRowMapper).mapRow(any(), anyInt());
|
verify(authorizationConsentRowMapper).mapRow(any(), anyInt());
|
||||||
verify(authorizationConsentParametersMapper).apply(any());
|
verify(authorizationConsentParametersMapper).apply(any());
|
||||||
@@ -225,12 +225,11 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void findByIdWhenAuthorizationConsentExistsThenFound() {
|
public void findByIdWhenAuthorizationConsentExistsThenFound() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
|
|
||||||
this.authorizationConsentService.save(AUTHORIZATION_CONSENT);
|
this.authorizationConsentService.save(AUTHORIZATION_CONSENT);
|
||||||
OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService.findById(
|
OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService
|
||||||
AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
|
.findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
|
||||||
assertThat(authorizationConsent).isNotNull();
|
assertThat(authorizationConsent).isNotNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,19 +242,18 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void tableDefinitionWhenCustomThenAbleToOverride() {
|
public void tableDefinitionWhenCustomThenAbleToOverride() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
|
|
||||||
EmbeddedDatabase db = createDb(CUSTOM_OAUTH2_AUTHORIZATION_CONSENT_SCHEMA_SQL_RESOURCE);
|
EmbeddedDatabase db = createDb(CUSTOM_OAUTH2_AUTHORIZATION_CONSENT_SCHEMA_SQL_RESOURCE);
|
||||||
OAuth2AuthorizationConsentService authorizationConsentService =
|
OAuth2AuthorizationConsentService authorizationConsentService = new CustomJdbcOAuth2AuthorizationConsentService(
|
||||||
new CustomJdbcOAuth2AuthorizationConsentService(new JdbcTemplate(db), this.registeredClientRepository);
|
new JdbcTemplate(db), this.registeredClientRepository);
|
||||||
authorizationConsentService.save(AUTHORIZATION_CONSENT);
|
authorizationConsentService.save(AUTHORIZATION_CONSENT);
|
||||||
OAuth2AuthorizationConsent foundAuthorizationConsent1 = authorizationConsentService.findById(
|
OAuth2AuthorizationConsent foundAuthorizationConsent1 = authorizationConsentService
|
||||||
AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
|
.findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
|
||||||
assertThat(foundAuthorizationConsent1).isEqualTo(AUTHORIZATION_CONSENT);
|
assertThat(foundAuthorizationConsent1).isEqualTo(AUTHORIZATION_CONSENT);
|
||||||
authorizationConsentService.remove(AUTHORIZATION_CONSENT);
|
authorizationConsentService.remove(AUTHORIZATION_CONSENT);
|
||||||
OAuth2AuthorizationConsent foundAuthorizationConsent2 = authorizationConsentService.findById(
|
OAuth2AuthorizationConsent foundAuthorizationConsent2 = authorizationConsentService
|
||||||
AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
|
.findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
|
||||||
assertThat(foundAuthorizationConsent2).isNull();
|
assertThat(foundAuthorizationConsent2).isNull();
|
||||||
db.shutdown();
|
db.shutdown();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,10 +63,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
|||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyInt;
|
import static org.mockito.ArgumentMatchers.anyInt;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.spy;
|
import static org.mockito.Mockito.spy;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link JdbcOAuth2AuthorizationService}.
|
* Tests for {@link JdbcOAuth2AuthorizationService}.
|
||||||
@@ -182,14 +182,13 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void saveWhenAuthorizationNewThenSaved() {
|
public void saveWhenAuthorizationNewThenSaved() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
OAuth2Authorization expectedAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization expectedAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.token(AUTHORIZATION_CODE)
|
.token(AUTHORIZATION_CODE)
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(expectedAuthorization);
|
this.authorizationService.save(expectedAuthorization);
|
||||||
|
|
||||||
OAuth2Authorization authorization = this.authorizationService.findById(ID);
|
OAuth2Authorization authorization = this.authorizationService.findById(ID);
|
||||||
@@ -198,53 +197,47 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void saveWhenAuthorizationExistsThenUpdated() {
|
public void saveWhenAuthorizationExistsThenUpdated() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.token(AUTHORIZATION_CODE)
|
.token(AUTHORIZATION_CODE)
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(originalAuthorization);
|
this.authorizationService.save(originalAuthorization);
|
||||||
|
|
||||||
OAuth2Authorization authorization = this.authorizationService.findById(
|
OAuth2Authorization authorization = this.authorizationService.findById(originalAuthorization.getId());
|
||||||
originalAuthorization.getId());
|
|
||||||
assertThat(authorization).isEqualTo(originalAuthorization);
|
assertThat(authorization).isEqualTo(originalAuthorization);
|
||||||
|
|
||||||
OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
|
OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
|
||||||
.attribute("custom-name-1", "custom-value-1")
|
.attribute("custom-name-1", "custom-value-1")
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(updatedAuthorization);
|
this.authorizationService.save(updatedAuthorization);
|
||||||
|
|
||||||
authorization = this.authorizationService.findById(
|
authorization = this.authorizationService.findById(updatedAuthorization.getId());
|
||||||
updatedAuthorization.getId());
|
|
||||||
assertThat(authorization).isEqualTo(updatedAuthorization);
|
assertThat(authorization).isEqualTo(updatedAuthorization);
|
||||||
assertThat(authorization).isNotEqualTo(originalAuthorization);
|
assertThat(authorization).isNotEqualTo(originalAuthorization);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void saveLoadAuthorizationWhenCustomStrategiesSetThenCalled() throws Exception {
|
public void saveLoadAuthorizationWhenCustomStrategiesSetThenCalled() throws Exception {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.token(AUTHORIZATION_CODE)
|
.token(AUTHORIZATION_CODE)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
RowMapper<OAuth2Authorization> authorizationRowMapper = spy(
|
RowMapper<OAuth2Authorization> authorizationRowMapper = spy(
|
||||||
new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper(
|
new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper(this.registeredClientRepository));
|
||||||
this.registeredClientRepository));
|
|
||||||
this.authorizationService.setAuthorizationRowMapper(authorizationRowMapper);
|
this.authorizationService.setAuthorizationRowMapper(authorizationRowMapper);
|
||||||
Function<OAuth2Authorization, List<SqlParameterValue>> authorizationParametersMapper = spy(
|
Function<OAuth2Authorization, List<SqlParameterValue>> authorizationParametersMapper = spy(
|
||||||
new JdbcOAuth2AuthorizationService.OAuth2AuthorizationParametersMapper());
|
new JdbcOAuth2AuthorizationService.OAuth2AuthorizationParametersMapper());
|
||||||
this.authorizationService.setAuthorizationParametersMapper(authorizationParametersMapper);
|
this.authorizationService.setAuthorizationParametersMapper(authorizationParametersMapper);
|
||||||
|
|
||||||
this.authorizationService.save(originalAuthorization);
|
this.authorizationService.save(originalAuthorization);
|
||||||
OAuth2Authorization authorization = this.authorizationService.findById(
|
OAuth2Authorization authorization = this.authorizationService.findById(originalAuthorization.getId());
|
||||||
originalAuthorization.getId());
|
|
||||||
assertThat(authorization).isEqualTo(originalAuthorization);
|
assertThat(authorization).isEqualTo(originalAuthorization);
|
||||||
verify(authorizationRowMapper).mapRow(any(), anyInt());
|
verify(authorizationRowMapper).mapRow(any(), anyInt());
|
||||||
verify(authorizationParametersMapper).apply(any());
|
verify(authorizationParametersMapper).apply(any());
|
||||||
@@ -261,23 +254,22 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void removeWhenAuthorizationProvidedThenRemoved() {
|
public void removeWhenAuthorizationProvidedThenRemoved() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
OAuth2Authorization expectedAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization expectedAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.token(AUTHORIZATION_CODE)
|
.token(AUTHORIZATION_CODE)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
this.authorizationService.save(expectedAuthorization);
|
this.authorizationService.save(expectedAuthorization);
|
||||||
OAuth2Authorization authorization = this.authorizationService.findByToken(
|
OAuth2Authorization authorization = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(),
|
||||||
AUTHORIZATION_CODE.getTokenValue(), AUTHORIZATION_CODE_TOKEN_TYPE);
|
AUTHORIZATION_CODE_TOKEN_TYPE);
|
||||||
assertThat(authorization).isEqualTo(expectedAuthorization);
|
assertThat(authorization).isEqualTo(expectedAuthorization);
|
||||||
|
|
||||||
this.authorizationService.remove(authorization);
|
this.authorizationService.remove(authorization);
|
||||||
authorization = this.authorizationService.findByToken(
|
authorization = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(),
|
||||||
AUTHORIZATION_CODE.getTokenValue(), AUTHORIZATION_CODE_TOKEN_TYPE);
|
AUTHORIZATION_CODE_TOKEN_TYPE);
|
||||||
assertThat(authorization).isNull();
|
assertThat(authorization).isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,19 +302,17 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void findByTokenWhenStateExistsThenFound() {
|
public void findByTokenWhenStateExistsThenFound() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
String state = "state";
|
String state = "state";
|
||||||
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.attribute(OAuth2ParameterNames.STATE, state)
|
.attribute(OAuth2ParameterNames.STATE, state)
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
OAuth2Authorization result = this.authorizationService.findByToken(
|
OAuth2Authorization result = this.authorizationService.findByToken(state, STATE_TOKEN_TYPE);
|
||||||
state, STATE_TOKEN_TYPE);
|
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
result = this.authorizationService.findByToken(state, null);
|
result = this.authorizationService.findByToken(state, null);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
@@ -330,18 +320,17 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void findByTokenWhenAuthorizationCodeExistsThenFound() {
|
public void findByTokenWhenAuthorizationCodeExistsThenFound() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.token(AUTHORIZATION_CODE)
|
.token(AUTHORIZATION_CODE)
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
OAuth2Authorization result = this.authorizationService.findByToken(
|
OAuth2Authorization result = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(),
|
||||||
AUTHORIZATION_CODE.getTokenValue(), AUTHORIZATION_CODE_TOKEN_TYPE);
|
AUTHORIZATION_CODE_TOKEN_TYPE);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
result = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(), null);
|
result = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(), null);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
@@ -349,21 +338,21 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void findByTokenWhenAccessTokenExistsThenFound() {
|
public void findByTokenWhenAccessTokenExistsThenFound() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token",
|
||||||
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
|
Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS),
|
||||||
"access-token", Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS), Instant.now().truncatedTo(ChronoUnit.MILLIS));
|
Instant.now().truncatedTo(ChronoUnit.MILLIS));
|
||||||
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.token(AUTHORIZATION_CODE)
|
.token(AUTHORIZATION_CODE)
|
||||||
.accessToken(accessToken)
|
.accessToken(accessToken)
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
OAuth2Authorization result = this.authorizationService.findByToken(
|
OAuth2Authorization result = this.authorizationService.findByToken(accessToken.getTokenValue(),
|
||||||
accessToken.getTokenValue(), OAuth2TokenType.ACCESS_TOKEN);
|
OAuth2TokenType.ACCESS_TOKEN);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
result = this.authorizationService.findByToken(accessToken.getTokenValue(), null);
|
result = this.authorizationService.findByToken(accessToken.getTokenValue(), null);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
@@ -371,25 +360,24 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void findByTokenWhenIdTokenExistsThenFound() {
|
public void findByTokenWhenIdTokenExistsThenFound() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
OidcIdToken idToken = OidcIdToken.withTokenValue("id-token")
|
||||||
OidcIdToken idToken = OidcIdToken.withTokenValue("id-token")
|
.issuer("https://provider.com")
|
||||||
.issuer("https://provider.com")
|
.subject("subject")
|
||||||
.subject("subject")
|
.issuedAt(Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS))
|
||||||
.issuedAt(Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS))
|
.expiresAt(Instant.now().truncatedTo(ChronoUnit.MILLIS))
|
||||||
.expiresAt(Instant.now().truncatedTo(ChronoUnit.MILLIS))
|
.build();
|
||||||
.build();
|
|
||||||
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.token(idToken, (metadata) ->
|
.token(idToken,
|
||||||
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()))
|
(metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()))
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
OAuth2Authorization result = this.authorizationService.findByToken(
|
OAuth2Authorization result = this.authorizationService.findByToken(idToken.getTokenValue(),
|
||||||
idToken.getTokenValue(), ID_TOKEN_TOKEN_TYPE);
|
ID_TOKEN_TOKEN_TYPE);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
result = this.authorizationService.findByToken(idToken.getTokenValue(), null);
|
result = this.authorizationService.findByToken(idToken.getTokenValue(), null);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
@@ -397,21 +385,20 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void findByTokenWhenRefreshTokenExistsThenFound() {
|
public void findByTokenWhenRefreshTokenExistsThenFound() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token",
|
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token",
|
||||||
Instant.now().truncatedTo(ChronoUnit.MILLIS),
|
Instant.now().truncatedTo(ChronoUnit.MILLIS),
|
||||||
Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS));
|
Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS));
|
||||||
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.refreshToken(refreshToken)
|
.refreshToken(refreshToken)
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
OAuth2Authorization result = this.authorizationService.findByToken(
|
OAuth2Authorization result = this.authorizationService.findByToken(refreshToken.getTokenValue(),
|
||||||
refreshToken.getTokenValue(), OAuth2TokenType.REFRESH_TOKEN);
|
OAuth2TokenType.REFRESH_TOKEN);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
result = this.authorizationService.findByToken(refreshToken.getTokenValue(), null);
|
result = this.authorizationService.findByToken(refreshToken.getTokenValue(), null);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
@@ -419,21 +406,19 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void findByTokenWhenDeviceCodeExistsThenFound() {
|
public void findByTokenWhenDeviceCodeExistsThenFound() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
OAuth2DeviceCode deviceCode = new OAuth2DeviceCode("device-code", Instant.now().truncatedTo(ChronoUnit.MILLIS),
|
||||||
OAuth2DeviceCode deviceCode = new OAuth2DeviceCode("device-code",
|
|
||||||
Instant.now().truncatedTo(ChronoUnit.MILLIS),
|
|
||||||
Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS));
|
Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS));
|
||||||
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.token(deviceCode)
|
.token(deviceCode)
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
OAuth2Authorization result = this.authorizationService.findByToken(
|
OAuth2Authorization result = this.authorizationService.findByToken(deviceCode.getTokenValue(),
|
||||||
deviceCode.getTokenValue(), DEVICE_CODE_TOKEN_TYPE);
|
DEVICE_CODE_TOKEN_TYPE);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
result = this.authorizationService.findByToken(deviceCode.getTokenValue(), null);
|
result = this.authorizationService.findByToken(deviceCode.getTokenValue(), null);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
@@ -441,21 +426,19 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void findByTokenWhenUserCodeExistsThenFound() {
|
public void findByTokenWhenUserCodeExistsThenFound() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
OAuth2UserCode userCode = new OAuth2UserCode("user-code", Instant.now().truncatedTo(ChronoUnit.MILLIS),
|
||||||
OAuth2UserCode userCode = new OAuth2UserCode("user-code",
|
|
||||||
Instant.now().truncatedTo(ChronoUnit.MILLIS),
|
|
||||||
Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS));
|
Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS));
|
||||||
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.token(userCode)
|
.token(userCode)
|
||||||
.build();
|
.build();
|
||||||
this.authorizationService.save(authorization);
|
this.authorizationService.save(authorization);
|
||||||
|
|
||||||
OAuth2Authorization result = this.authorizationService.findByToken(
|
OAuth2Authorization result = this.authorizationService.findByToken(userCode.getTokenValue(),
|
||||||
userCode.getTokenValue(), USER_CODE_TOKEN_TYPE);
|
USER_CODE_TOKEN_TYPE);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
result = this.authorizationService.findByToken(userCode.getTokenValue(), null);
|
result = this.authorizationService.findByToken(userCode.getTokenValue(), null);
|
||||||
assertThat(authorization).isEqualTo(result);
|
assertThat(authorization).isEqualTo(result);
|
||||||
@@ -487,20 +470,19 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void tableDefinitionWhenCustomThenAbleToOverride() {
|
public void tableDefinitionWhenCustomThenAbleToOverride() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
|
|
||||||
EmbeddedDatabase db = createDb(CUSTOM_OAUTH2_AUTHORIZATION_SCHEMA_SQL_RESOURCE);
|
EmbeddedDatabase db = createDb(CUSTOM_OAUTH2_AUTHORIZATION_SCHEMA_SQL_RESOURCE);
|
||||||
OAuth2AuthorizationService authorizationService =
|
OAuth2AuthorizationService authorizationService = new CustomJdbcOAuth2AuthorizationService(new JdbcTemplate(db),
|
||||||
new CustomJdbcOAuth2AuthorizationService(new JdbcTemplate(db), this.registeredClientRepository);
|
this.registeredClientRepository);
|
||||||
String state = "state";
|
String state = "state";
|
||||||
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.attribute(OAuth2ParameterNames.STATE, state)
|
.attribute(OAuth2ParameterNames.STATE, state)
|
||||||
.token(AUTHORIZATION_CODE)
|
.token(AUTHORIZATION_CODE)
|
||||||
.build();
|
.build();
|
||||||
authorizationService.save(originalAuthorization);
|
authorizationService.save(originalAuthorization);
|
||||||
OAuth2Authorization foundAuthorization1 = authorizationService.findById(originalAuthorization.getId());
|
OAuth2Authorization foundAuthorization1 = authorizationService.findById(originalAuthorization.getId());
|
||||||
assertThat(foundAuthorization1).isEqualTo(originalAuthorization);
|
assertThat(foundAuthorization1).isEqualTo(originalAuthorization);
|
||||||
@@ -511,31 +493,28 @@ public class JdbcOAuth2AuthorizationServiceTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void tableDefinitionWhenClobSqlTypeThenAuthorizationUpdated() {
|
public void tableDefinitionWhenClobSqlTypeThenAuthorizationUpdated() {
|
||||||
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
|
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
|
||||||
.thenReturn(REGISTERED_CLIENT);
|
|
||||||
|
|
||||||
EmbeddedDatabase db = createDb(OAUTH2_AUTHORIZATION_SCHEMA_CLOB_DATA_TYPE_SQL_RESOURCE);
|
EmbeddedDatabase db = createDb(OAUTH2_AUTHORIZATION_SCHEMA_CLOB_DATA_TYPE_SQL_RESOURCE);
|
||||||
OAuth2AuthorizationService authorizationService =
|
OAuth2AuthorizationService authorizationService = new JdbcOAuth2AuthorizationService(new JdbcTemplate(db),
|
||||||
new JdbcOAuth2AuthorizationService(new JdbcTemplate(db), this.registeredClientRepository);
|
this.registeredClientRepository);
|
||||||
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
|
||||||
.id(ID)
|
.id(ID)
|
||||||
.principalName(PRINCIPAL_NAME)
|
.principalName(PRINCIPAL_NAME)
|
||||||
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
|
||||||
.token(AUTHORIZATION_CODE)
|
.token(AUTHORIZATION_CODE)
|
||||||
.build();
|
.build();
|
||||||
authorizationService.save(originalAuthorization);
|
authorizationService.save(originalAuthorization);
|
||||||
|
|
||||||
OAuth2Authorization authorization = authorizationService.findById(
|
OAuth2Authorization authorization = authorizationService.findById(originalAuthorization.getId());
|
||||||
originalAuthorization.getId());
|
|
||||||
assertThat(authorization).isEqualTo(originalAuthorization);
|
assertThat(authorization).isEqualTo(originalAuthorization);
|
||||||
|
|
||||||
OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
|
OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
|
||||||
.attribute("custom-name-1", "custom-value-1")
|
.attribute("custom-name-1", "custom-value-1")
|
||||||
.build();
|
.build();
|
||||||
authorizationService.save(updatedAuthorization);
|
authorizationService.save(updatedAuthorization);
|
||||||
|
|
||||||
authorization = authorizationService.findById(
|
authorization = authorizationService.findById(updatedAuthorization.getId());
|
||||||
updatedAuthorization.getId());
|
|
||||||
assertThat(authorization).isEqualTo(updatedAuthorization);
|
assertThat(authorization).isEqualTo(updatedAuthorization);
|
||||||
assertThat(authorization).isNotEqualTo(originalAuthorization);
|
assertThat(authorization).isNotEqualTo(originalAuthorization);
|
||||||
db.shutdown();
|
db.shutdown();
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ public class OAuth2AuthorizationConsentTests {
|
|||||||
public void authoritiesThenCustomizesAuthorities() {
|
public void authoritiesThenCustomizesAuthorities() {
|
||||||
OAuth2AuthorizationConsent authorizationConsent = OAuth2AuthorizationConsent.withId("some-client", "some-user")
|
OAuth2AuthorizationConsent authorizationConsent = OAuth2AuthorizationConsent.withId("some-client", "some-user")
|
||||||
.authority(new SimpleGrantedAuthority("some.authority"))
|
.authority(new SimpleGrantedAuthority("some.authority"))
|
||||||
.authorities(authorities -> {
|
.authorities((authorities) -> {
|
||||||
authorities.clear();
|
authorities.clear();
|
||||||
authorities.add(new SimpleGrantedAuthority("other.authority"));
|
authorities.add(new SimpleGrantedAuthority("other.authority"));
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -296,7 +296,7 @@ public class OAuth2AuthorizationServerMetadataTests {
|
|||||||
public void buildWhenTokenEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() {
|
public void buildWhenTokenEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() {
|
||||||
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
||||||
.tokenEndpointAuthenticationMethod("should-be-removed")
|
.tokenEndpointAuthenticationMethod("should-be-removed")
|
||||||
.tokenEndpointAuthenticationMethods(authMethods -> {
|
.tokenEndpointAuthenticationMethods((authMethods) -> {
|
||||||
authMethods.clear();
|
authMethods.clear();
|
||||||
authMethods.add("some-authentication-method");
|
authMethods.add("some-authentication-method");
|
||||||
})
|
})
|
||||||
@@ -334,7 +334,7 @@ public class OAuth2AuthorizationServerMetadataTests {
|
|||||||
@Test
|
@Test
|
||||||
public void buildWhenScopesAddingOrRemovingThenCorrectValues() {
|
public void buildWhenScopesAddingOrRemovingThenCorrectValues() {
|
||||||
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder.scope("should-be-removed")
|
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder.scope("should-be-removed")
|
||||||
.scopes(scopes -> {
|
.scopes((scopes) -> {
|
||||||
scopes.clear();
|
scopes.clear();
|
||||||
scopes.add("some-scope");
|
scopes.add("some-scope");
|
||||||
})
|
})
|
||||||
@@ -372,7 +372,7 @@ public class OAuth2AuthorizationServerMetadataTests {
|
|||||||
public void buildWhenResponseTypesAddingOrRemovingThenCorrectValues() {
|
public void buildWhenResponseTypesAddingOrRemovingThenCorrectValues() {
|
||||||
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
||||||
.responseType("should-be-removed")
|
.responseType("should-be-removed")
|
||||||
.responseTypes(responseTypes -> {
|
.responseTypes((responseTypes) -> {
|
||||||
responseTypes.clear();
|
responseTypes.clear();
|
||||||
responseTypes.add("some-response-type");
|
responseTypes.add("some-response-type");
|
||||||
})
|
})
|
||||||
@@ -384,8 +384,8 @@ public class OAuth2AuthorizationServerMetadataTests {
|
|||||||
@Test
|
@Test
|
||||||
public void buildWhenResponseTypesNotPresentAndAddingThenCorrectValues() {
|
public void buildWhenResponseTypesNotPresentAndAddingThenCorrectValues() {
|
||||||
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
||||||
.claims(claims -> claims.remove(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED))
|
.claims((claims) -> claims.remove(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED))
|
||||||
.responseTypes(responseTypes -> responseTypes.add("some-response-type"))
|
.responseTypes((responseTypes) -> responseTypes.add("some-response-type"))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
assertThat(authorizationServerMetadata.getResponseTypes()).containsExactly("some-response-type");
|
assertThat(authorizationServerMetadata.getResponseTypes()).containsExactly("some-response-type");
|
||||||
@@ -412,7 +412,7 @@ public class OAuth2AuthorizationServerMetadataTests {
|
|||||||
public void buildWhenGrantTypesAddingOrRemovingThenCorrectValues() {
|
public void buildWhenGrantTypesAddingOrRemovingThenCorrectValues() {
|
||||||
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
||||||
.grantType("should-be-removed")
|
.grantType("should-be-removed")
|
||||||
.grantTypes(grantTypes -> {
|
.grantTypes((grantTypes) -> {
|
||||||
grantTypes.clear();
|
grantTypes.clear();
|
||||||
grantTypes.add("some-grant-type");
|
grantTypes.add("some-grant-type");
|
||||||
})
|
})
|
||||||
@@ -452,7 +452,7 @@ public class OAuth2AuthorizationServerMetadataTests {
|
|||||||
public void buildWhenTokenRevocationEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() {
|
public void buildWhenTokenRevocationEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() {
|
||||||
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
||||||
.tokenRevocationEndpointAuthenticationMethod("should-be-removed")
|
.tokenRevocationEndpointAuthenticationMethod("should-be-removed")
|
||||||
.tokenRevocationEndpointAuthenticationMethods(authMethods -> {
|
.tokenRevocationEndpointAuthenticationMethods((authMethods) -> {
|
||||||
authMethods.clear();
|
authMethods.clear();
|
||||||
authMethods.add("some-authentication-method");
|
authMethods.add("some-authentication-method");
|
||||||
})
|
})
|
||||||
@@ -494,7 +494,7 @@ public class OAuth2AuthorizationServerMetadataTests {
|
|||||||
public void buildWhenTokenIntrospectionEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() {
|
public void buildWhenTokenIntrospectionEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() {
|
||||||
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
||||||
.tokenIntrospectionEndpointAuthenticationMethod("should-be-removed")
|
.tokenIntrospectionEndpointAuthenticationMethod("should-be-removed")
|
||||||
.tokenIntrospectionEndpointAuthenticationMethods(authMethods -> {
|
.tokenIntrospectionEndpointAuthenticationMethods((authMethods) -> {
|
||||||
authMethods.clear();
|
authMethods.clear();
|
||||||
authMethods.add("some-authentication-method");
|
authMethods.add("some-authentication-method");
|
||||||
})
|
})
|
||||||
@@ -527,7 +527,7 @@ public class OAuth2AuthorizationServerMetadataTests {
|
|||||||
public void buildWhenCodeChallengeMethodsAddingOrRemovingThenCorrectValues() {
|
public void buildWhenCodeChallengeMethodsAddingOrRemovingThenCorrectValues() {
|
||||||
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
|
||||||
.codeChallengeMethod("should-be-removed")
|
.codeChallengeMethod("should-be-removed")
|
||||||
.codeChallengeMethods(codeChallengeMethods -> {
|
.codeChallengeMethods((codeChallengeMethods) -> {
|
||||||
codeChallengeMethods.clear();
|
codeChallengeMethods.clear();
|
||||||
codeChallengeMethods.add("some-authentication-method");
|
codeChallengeMethods.add("some-authentication-method");
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -37,7 +37,10 @@ import org.springframework.util.CollectionUtils;
|
|||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
* @author Daniel Garnier-Moiroux
|
* @author Daniel Garnier-Moiroux
|
||||||
*/
|
*/
|
||||||
public class TestOAuth2Authorizations {
|
public final class TestOAuth2Authorizations {
|
||||||
|
|
||||||
|
private TestOAuth2Authorizations() {
|
||||||
|
}
|
||||||
|
|
||||||
public static OAuth2Authorization.Builder authorization() {
|
public static OAuth2Authorization.Builder authorization() {
|
||||||
return authorization(TestRegisteredClients.registeredClient().build());
|
return authorization(TestRegisteredClients.registeredClient().build());
|
||||||
|
|||||||
@@ -43,10 +43,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.spy;
|
import static org.mockito.Mockito.spy;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link ClientSecretAuthenticationProvider}.
|
* Tests for {@link ClientSecretAuthenticationProvider}.
|
||||||
@@ -129,16 +129,16 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenInvalidClientIdThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenInvalidClientIdThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId() + "-invalid", ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
registeredClient.getClientId() + "-invalid", ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
||||||
registeredClient.getClientSecret(), null);
|
registeredClient.getClientSecret(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID);
|
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID);
|
||||||
});
|
});
|
||||||
@@ -147,16 +147,16 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenUnsupportedClientAuthenticationMethodThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenUnsupportedClientAuthenticationMethodThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_POST,
|
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_POST,
|
||||||
registeredClient.getClientSecret(), null);
|
registeredClient.getClientSecret(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).contains("authentication_method");
|
assertThat(error.getDescription()).contains("authentication_method");
|
||||||
});
|
});
|
||||||
@@ -165,15 +165,15 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenClientSecretNotProvidedThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenClientSecretNotProvidedThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null, null);
|
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null, null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).contains("credentials");
|
assertThat(error.getDescription()).contains("credentials");
|
||||||
});
|
});
|
||||||
@@ -182,16 +182,16 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenInvalidClientSecretThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenInvalidClientSecretThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
||||||
registeredClient.getClientSecret() + "-invalid", null);
|
registeredClient.getClientSecret() + "-invalid", null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_SECRET);
|
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_SECRET);
|
||||||
});
|
});
|
||||||
@@ -203,16 +203,16 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
.clientSecretExpiresAt(Instant.now().minus(1, ChronoUnit.HOURS).truncatedTo(ChronoUnit.SECONDS))
|
.clientSecretExpiresAt(Instant.now().minus(1, ChronoUnit.HOURS).truncatedTo(ChronoUnit.SECONDS))
|
||||||
.build();
|
.build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
||||||
registeredClient.getClientSecret(), null);
|
registeredClient.getClientSecret(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).contains("client_secret_expires_at");
|
assertThat(error.getDescription()).contains("client_secret_expires_at");
|
||||||
});
|
});
|
||||||
@@ -222,8 +222,8 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenValidCredentialsThenAuthenticated() {
|
public void authenticateWhenValidCredentialsThenAuthenticated() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
||||||
@@ -241,8 +241,8 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenValidCredentialsAndRequiresUpgradingThenClientSecretUpgraded() {
|
public void authenticateWhenValidCredentialsAndRequiresUpgradingThenClientSecretUpgraded() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
||||||
@@ -263,11 +263,11 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenAuthorizationCodeGrantAndValidCredentialsThenAuthenticated() {
|
public void authenticateWhenAuthorizationCodeGrantAndValidCredentialsThenAuthenticated() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(TestOAuth2Authorizations.authorization().build());
|
.willReturn(TestOAuth2Authorizations.authorization().build());
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
|
||||||
registeredClient.getClientSecret(), createAuthorizationCodeTokenParameters());
|
registeredClient.getClientSecret(), createAuthorizationCodeTokenParameters());
|
||||||
@@ -285,14 +285,14 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenPkceAndInvalidCodeThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenPkceAndInvalidCodeThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations
|
OAuth2Authorization authorization = TestOAuth2Authorizations
|
||||||
.authorization(registeredClient, createPkceAuthorizationParametersS256())
|
.authorization(registeredClient, createPkceAuthorizationParametersS256())
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER);
|
Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER);
|
||||||
parameters.put(OAuth2ParameterNames.CODE, "invalid-code");
|
parameters.put(OAuth2ParameterNames.CODE, "invalid-code");
|
||||||
@@ -303,8 +303,8 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
||||||
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CODE);
|
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CODE);
|
||||||
});
|
});
|
||||||
@@ -313,14 +313,14 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenPkceAndMissingCodeVerifierThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenPkceAndMissingCodeVerifierThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations
|
OAuth2Authorization authorization = TestOAuth2Authorizations
|
||||||
.authorization(registeredClient, createPkceAuthorizationParametersS256())
|
.authorization(registeredClient, createPkceAuthorizationParametersS256())
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
Map<String, Object> parameters = createAuthorizationCodeTokenParameters();
|
Map<String, Object> parameters = createAuthorizationCodeTokenParameters();
|
||||||
|
|
||||||
@@ -330,8 +330,8 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
||||||
assertThat(error.getDescription()).contains(PkceParameterNames.CODE_VERIFIER);
|
assertThat(error.getDescription()).contains(PkceParameterNames.CODE_VERIFIER);
|
||||||
});
|
});
|
||||||
@@ -340,14 +340,14 @@ public class ClientSecretAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenPkceAndValidCodeVerifierThenAuthenticated() {
|
public void authenticateWhenPkceAndValidCodeVerifierThenAuthenticated() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations
|
OAuth2Authorization authorization = TestOAuth2Authorizations
|
||||||
.authorization(registeredClient, createPkceAuthorizationParametersS256())
|
.authorization(registeredClient, createPkceAuthorizationParametersS256())
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER);
|
Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER);
|
||||||
|
|
||||||
|
|||||||
@@ -65,9 +65,9 @@ import org.springframework.web.util.UriComponentsBuilder;
|
|||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link JwtClientAssertionAuthenticationProvider}.
|
* Tests for {@link JwtClientAssertionAuthenticationProvider}.
|
||||||
@@ -144,16 +144,16 @@ public class JwtClientAssertionAuthenticationProviderTests {
|
|||||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
|
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId() + "-invalid", JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD,
|
registeredClient.getClientId() + "-invalid", JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD,
|
||||||
"jwt-assertion", null);
|
"jwt-assertion", null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID);
|
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID);
|
||||||
});
|
});
|
||||||
@@ -162,15 +162,15 @@ public class JwtClientAssertionAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenUnsupportedClientAuthenticationMethodThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenUnsupportedClientAuthenticationMethodThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "jwt-assertion", null);
|
registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "jwt-assertion", null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).contains("authentication_method");
|
assertThat(error.getDescription()).contains("authentication_method");
|
||||||
});
|
});
|
||||||
@@ -183,15 +183,15 @@ public class JwtClientAssertionAuthenticationProviderTests {
|
|||||||
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
|
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, null, null);
|
registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, null, null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).contains("credentials");
|
assertThat(error.getDescription()).contains("credentials");
|
||||||
});
|
});
|
||||||
@@ -210,8 +210,8 @@ public class JwtClientAssertionAuthenticationProviderTests {
|
|||||||
)
|
)
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
|
||||||
registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "invalid-jwt-assertion",
|
registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "invalid-jwt-assertion",
|
||||||
@@ -219,8 +219,8 @@ public class JwtClientAssertionAuthenticationProviderTests {
|
|||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.hasCauseInstanceOf(BadJwtException.class)
|
.hasCauseInstanceOf(BadJwtException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ASSERTION);
|
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ASSERTION);
|
||||||
});
|
});
|
||||||
@@ -239,8 +239,8 @@ public class JwtClientAssertionAuthenticationProviderTests {
|
|||||||
)
|
)
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
JwsHeader jwsHeader = JwsHeader.with(MacAlgorithm.HS256)
|
JwsHeader jwsHeader = JwsHeader.with(MacAlgorithm.HS256)
|
||||||
@@ -261,8 +261,8 @@ public class JwtClientAssertionAuthenticationProviderTests {
|
|||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.hasCauseInstanceOf(JwtValidationException.class)
|
.hasCauseInstanceOf(JwtValidationException.class)
|
||||||
.extracting(ex -> (OAuth2AuthenticationException) ex)
|
.extracting((ex) -> (OAuth2AuthenticationException) ex)
|
||||||
.satisfies(ex -> {
|
.satisfies((ex) -> {
|
||||||
assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(ex.getError().getDescription()).contains(OAuth2ParameterNames.CLIENT_ASSERTION);
|
assertThat(ex.getError().getDescription()).contains(OAuth2ParameterNames.CLIENT_ASSERTION);
|
||||||
JwtValidationException jwtValidationException = (JwtValidationException) ex.getCause();
|
JwtValidationException jwtValidationException = (JwtValidationException) ex.getCause();
|
||||||
@@ -284,8 +284,8 @@ public class JwtClientAssertionAuthenticationProviderTests {
|
|||||||
)
|
)
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
JwsHeader jwsHeader = JwsHeader.with(MacAlgorithm.HS256)
|
JwsHeader jwsHeader = JwsHeader.with(MacAlgorithm.HS256)
|
||||||
@@ -324,14 +324,14 @@ public class JwtClientAssertionAuthenticationProviderTests {
|
|||||||
)
|
)
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations
|
OAuth2Authorization authorization = TestOAuth2Authorizations
|
||||||
.authorization(registeredClient, createPkceAuthorizationParametersS256())
|
.authorization(registeredClient, createPkceAuthorizationParametersS256())
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER);
|
Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER);
|
||||||
|
|
||||||
|
|||||||
@@ -60,8 +60,8 @@ public class JwtClientAssertionDecoderFactoryTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient))
|
assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).isEqualTo("Failed to find a Signature Verifier for Client: '"
|
assertThat(error.getDescription()).isEqualTo("Failed to find a Signature Verifier for Client: '"
|
||||||
+ registeredClient.getId() + "'. Check to ensure you have configured the JWK Set URL.");
|
+ registeredClient.getId() + "'. Check to ensure you have configured the JWK Set URL.");
|
||||||
@@ -84,8 +84,8 @@ public class JwtClientAssertionDecoderFactoryTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient))
|
assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription()).isEqualTo("Failed to find a Signature Verifier for Client: '"
|
assertThat(error.getDescription()).isEqualTo("Failed to find a Signature Verifier for Client: '"
|
||||||
+ registeredClient.getId() + "'. Check to ensure you have configured the client secret.");
|
+ registeredClient.getId() + "'. Check to ensure you have configured the client secret.");
|
||||||
@@ -102,8 +102,8 @@ public class JwtClientAssertionDecoderFactoryTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient))
|
assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
assertThat(error.getDescription())
|
assertThat(error.getDescription())
|
||||||
.isEqualTo("Failed to find a Signature Verifier for Client: '" + registeredClient.getId()
|
.isEqualTo("Failed to find a Signature Verifier for Client: '" + registeredClient.getId()
|
||||||
|
|||||||
@@ -15,6 +15,11 @@
|
|||||||
*/
|
*/
|
||||||
package org.springframework.security.oauth2.server.authorization.authentication;
|
package org.springframework.security.oauth2.server.authorization.authentication;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
|
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
|
||||||
@@ -23,11 +28,6 @@ import org.springframework.security.oauth2.core.OAuth2RefreshToken;
|
|||||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||||
import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients;
|
import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients;
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.temporal.ChronoUnit;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
|||||||
@@ -84,13 +84,13 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
|||||||
import static org.assertj.core.api.Assertions.entry;
|
import static org.assertj.core.api.Assertions.entry;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.doAnswer;
|
import static org.mockito.BDDMockito.given;
|
||||||
|
import static org.mockito.BDDMockito.willAnswer;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.spy;
|
import static org.mockito.Mockito.spy;
|
||||||
import static org.mockito.Mockito.times;
|
import static org.mockito.Mockito.times;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link OAuth2AuthorizationCodeAuthenticationProvider}.
|
* Tests for {@link OAuth2AuthorizationCodeAuthenticationProvider}.
|
||||||
@@ -188,7 +188,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
AUTHORIZATION_CODE, clientPrincipal, null, null);
|
AUTHORIZATION_CODE, clientPrincipal, null, null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
}
|
}
|
||||||
@@ -203,7 +203,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
AUTHORIZATION_CODE, clientPrincipal, null, null);
|
AUTHORIZATION_CODE, clientPrincipal, null, null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
}
|
}
|
||||||
@@ -217,7 +217,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
AUTHORIZATION_CODE, clientPrincipal, null, null);
|
AUTHORIZATION_CODE, clientPrincipal, null, null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
||||||
}
|
}
|
||||||
@@ -225,8 +225,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenCodeIssuedToAnotherClientThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenCodeIssuedToAnotherClientThenThrowOAuth2AuthenticationException() {
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization().build();
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization().build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
@@ -235,7 +235,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
AUTHORIZATION_CODE, clientPrincipal, null, null);
|
AUTHORIZATION_CODE, clientPrincipal, null, null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
||||||
|
|
||||||
@@ -251,8 +251,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
public void authenticateWhenInvalidRedirectUriThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenInvalidRedirectUriThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -262,7 +262,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri() + "-invalid", null);
|
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri() + "-invalid", null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
||||||
}
|
}
|
||||||
@@ -276,8 +276,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
.token(authorizationCode,
|
.token(authorizationCode,
|
||||||
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -288,7 +288,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
||||||
|
|
||||||
@@ -309,8 +309,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
.token(authorizationCode,
|
.token(authorizationCode,
|
||||||
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -321,7 +321,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
||||||
|
|
||||||
@@ -337,8 +337,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
||||||
.token(authorizationCode)
|
.token(authorizationCode)
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -349,7 +349,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
||||||
}
|
}
|
||||||
@@ -358,8 +358,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
public void authenticateWhenAccessTokenNotGeneratedThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenAccessTokenNotGeneratedThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -368,7 +368,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
||||||
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
||||||
|
|
||||||
doAnswer(answer -> {
|
willAnswer((answer) -> {
|
||||||
OAuth2TokenContext context = answer.getArgument(0);
|
OAuth2TokenContext context = answer.getArgument(0);
|
||||||
if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
|
if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
|
||||||
return null;
|
return null;
|
||||||
@@ -376,12 +376,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
else {
|
else {
|
||||||
return answer.callRealMethod();
|
return answer.callRealMethod();
|
||||||
}
|
}
|
||||||
}).when(this.tokenGenerator).generate(any());
|
}).given(this.tokenGenerator).generate(any());
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
||||||
assertThat(error.getDescription()).contains("The token generator failed to generate the access token.");
|
assertThat(error.getDescription()).contains("The token generator failed to generate the access token.");
|
||||||
});
|
});
|
||||||
@@ -391,8 +391,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
public void authenticateWhenInvalidRefreshTokenGeneratedThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenInvalidRefreshTokenGeneratedThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -401,9 +401,9 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
||||||
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
||||||
|
|
||||||
when(this.jwtEncoder.encode(any())).thenReturn(createJwt());
|
given(this.jwtEncoder.encode(any())).willReturn(createJwt());
|
||||||
|
|
||||||
doAnswer(answer -> {
|
willAnswer((answer) -> {
|
||||||
OAuth2TokenContext context = answer.getArgument(0);
|
OAuth2TokenContext context = answer.getArgument(0);
|
||||||
if (OAuth2TokenType.REFRESH_TOKEN.equals(context.getTokenType())) {
|
if (OAuth2TokenType.REFRESH_TOKEN.equals(context.getTokenType())) {
|
||||||
return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", Instant.now(),
|
return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", Instant.now(),
|
||||||
@@ -412,12 +412,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
else {
|
else {
|
||||||
return answer.callRealMethod();
|
return answer.callRealMethod();
|
||||||
}
|
}
|
||||||
}).when(this.tokenGenerator).generate(any());
|
}).given(this.tokenGenerator).generate(any());
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
||||||
assertThat(error.getDescription())
|
assertThat(error.getDescription())
|
||||||
.contains("The token generator failed to generate a valid refresh token.");
|
.contains("The token generator failed to generate a valid refresh token.");
|
||||||
@@ -428,8 +428,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
public void authenticateWhenIdTokenNotGeneratedThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenIdTokenNotGeneratedThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build();
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -438,9 +438,9 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
||||||
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
||||||
|
|
||||||
when(this.jwtEncoder.encode(any())).thenReturn(createJwt());
|
given(this.jwtEncoder.encode(any())).willReturn(createJwt());
|
||||||
|
|
||||||
doAnswer(answer -> {
|
willAnswer((answer) -> {
|
||||||
OAuth2TokenContext context = answer.getArgument(0);
|
OAuth2TokenContext context = answer.getArgument(0);
|
||||||
if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
|
if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
|
||||||
return null;
|
return null;
|
||||||
@@ -448,12 +448,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
else {
|
else {
|
||||||
return answer.callRealMethod();
|
return answer.callRealMethod();
|
||||||
}
|
}
|
||||||
}).when(this.tokenGenerator).generate(any());
|
}).given(this.tokenGenerator).generate(any());
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
||||||
assertThat(error.getDescription()).contains("The token generator failed to generate the ID token.");
|
assertThat(error.getDescription()).contains("The token generator failed to generate the ID token.");
|
||||||
});
|
});
|
||||||
@@ -463,8 +463,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
public void authenticateWhenValidCodeThenReturnAccessToken() {
|
public void authenticateWhenValidCodeThenReturnAccessToken() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -473,7 +473,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
||||||
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
||||||
|
|
||||||
when(this.jwtEncoder.encode(any())).thenReturn(createJwt());
|
given(this.jwtEncoder.encode(any())).willReturn(createJwt());
|
||||||
|
|
||||||
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -528,8 +528,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
Instant.now().plusSeconds(120));
|
Instant.now().plusSeconds(120));
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient, authorizationCode)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient, authorizationCode)
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -538,7 +538,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
||||||
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
||||||
|
|
||||||
when(this.jwtEncoder.encode(any())).thenReturn(createJwt());
|
given(this.jwtEncoder.encode(any())).willReturn(createJwt());
|
||||||
|
|
||||||
Authentication principal = authorization.getAttribute(Principal.class.getName());
|
Authentication principal = authorization.getAttribute(Principal.class.getName());
|
||||||
|
|
||||||
@@ -549,7 +549,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
sessions.add(new SessionInformation(principal.getPrincipal(), "session1",
|
sessions.add(new SessionInformation(principal.getPrincipal(), "session1",
|
||||||
Date.from(Instant.now().minus(2, ChronoUnit.HOURS))));
|
Date.from(Instant.now().minus(2, ChronoUnit.HOURS))));
|
||||||
SessionInformation expectedSession = sessions.get(0); // Most recent
|
SessionInformation expectedSession = sessions.get(0); // Most recent
|
||||||
when(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(false))).thenReturn(sessions);
|
given(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(false))).willReturn(sessions);
|
||||||
|
|
||||||
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -622,8 +622,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
|
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
|
||||||
.build();
|
.build();
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.NONE, null);
|
ClientAuthenticationMethod.NONE, null);
|
||||||
@@ -632,7 +632,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
||||||
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
||||||
|
|
||||||
when(this.jwtEncoder.encode(any())).thenReturn(createJwt());
|
given(this.jwtEncoder.encode(any())).willReturn(createJwt());
|
||||||
|
|
||||||
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -690,8 +690,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -702,7 +702,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
|
|
||||||
Instant accessTokenIssuedAt = Instant.now();
|
Instant accessTokenIssuedAt = Instant.now();
|
||||||
Instant accessTokenExpiresAt = accessTokenIssuedAt.plus(accessTokenTTL);
|
Instant accessTokenExpiresAt = accessTokenIssuedAt.plus(accessTokenTTL);
|
||||||
when(this.jwtEncoder.encode(any())).thenReturn(createJwt(accessTokenIssuedAt, accessTokenExpiresAt));
|
given(this.jwtEncoder.encode(any())).willReturn(createJwt(accessTokenIssuedAt, accessTokenExpiresAt));
|
||||||
|
|
||||||
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -731,12 +731,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenRefreshTokenGrantNotConfiguredThenRefreshTokenNotIssued() {
|
public void authenticateWhenRefreshTokenGrantNotConfiguredThenRefreshTokenNotIssued() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
.authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.REFRESH_TOKEN))
|
.authorizationGrantTypes((grantTypes) -> grantTypes.remove(AuthorizationGrantType.REFRESH_TOKEN))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -745,7 +745,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
|
||||||
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
|
||||||
|
|
||||||
when(this.jwtEncoder.encode(any())).thenReturn(createJwt());
|
given(this.jwtEncoder.encode(any())).willReturn(createJwt());
|
||||||
|
|
||||||
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -763,8 +763,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
|
|||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
|
||||||
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
|
|||||||
@@ -55,9 +55,9 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link OAuth2AuthorizationCodeRequestAuthenticationProvider}.
|
* Tests for {@link OAuth2AuthorizationCodeRequestAuthenticationProvider}.
|
||||||
@@ -155,11 +155,11 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,14 +167,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenInvalidRedirectUriHostThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenInvalidRedirectUriHostThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https:///invalid", STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https:///invalid", STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,28 +182,28 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenInvalidRedirectUriFragmentThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenInvalidRedirectUriFragmentThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https://example.com#fragment", STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https://example.com#fragment",
|
||||||
registeredClient.getScopes(), null);
|
STATE, registeredClient.getScopes(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void authenticateWhenUnregisteredRedirectUriThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenUnregisteredRedirectUriThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https://invalid-example.com", STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https://invalid-example.com", STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,10 +213,10 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
.redirectUri("https://127.0.0.1:8080")
|
.redirectUri("https://127.0.0.1:8080")
|
||||||
.build();
|
.build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https://127.0.0.1:5000", STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https://127.0.0.1:5000", STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
||||||
@@ -232,10 +232,10 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
.redirectUri("https://[::1]:8080")
|
.redirectUri("https://[::1]:8080")
|
||||||
.build();
|
.build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https://[::1]:5000", STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https://[::1]:5000", STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
||||||
@@ -250,14 +250,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
.redirectUri("https://example2.com")
|
.redirectUri("https://example2.com")
|
||||||
.build();
|
.build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, null, STATE, registeredClient.getScopes(),
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, null, STATE,
|
||||||
null);
|
registeredClient.getScopes(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -265,14 +265,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
public void authenticateWhenAuthenticationRequestMissingRedirectUriThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenAuthenticationRequestMissingRedirectUriThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
// redirect_uri is REQUIRED for OpenID Connect requests
|
// redirect_uri is REQUIRED for OpenID Connect requests
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, null, STATE, registeredClient.getScopes(),
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, null, STATE,
|
||||||
null);
|
registeredClient.getScopes(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,15 +282,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
.authorizationGrantTypes(Set::clear)
|
.authorizationGrantTypes(Set::clear)
|
||||||
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
|
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
|
||||||
.build();
|
.build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.UNAUTHORIZED_CLIENT, OAuth2ParameterNames.CLIENT_ID,
|
OAuth2ErrorCodes.UNAUTHORIZED_CLIENT, OAuth2ParameterNames.CLIENT_ID,
|
||||||
authentication.getRedirectUri()));
|
authentication.getRedirectUri()));
|
||||||
}
|
}
|
||||||
@@ -298,15 +298,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenInvalidScopeThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenInvalidScopeThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
Collections.singleton("invalid-scope"), null);
|
Collections.singleton("invalid-scope"), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE, authentication.getRedirectUri()));
|
OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE, authentication.getRedirectUri()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,15 +315,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
.clientSettings(ClientSettings.builder().requireProofKey(true).build())
|
.clientSettings(ClientSettings.builder().requireProofKey(true).build())
|
||||||
.build();
|
.build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE,
|
OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE,
|
||||||
authentication.getRedirectUri()));
|
authentication.getRedirectUri()));
|
||||||
}
|
}
|
||||||
@@ -331,18 +331,18 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenPkceUnsupportedCodeChallengeMethodThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenPkceUnsupportedCodeChallengeMethodThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0];
|
||||||
Map<String, Object> additionalParameters = new HashMap<>();
|
Map<String, Object> additionalParameters = new HashMap<>();
|
||||||
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge");
|
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge");
|
||||||
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "unsupported");
|
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "unsupported");
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), additionalParameters);
|
registeredClient.getScopes(), additionalParameters);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD,
|
OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD,
|
||||||
authentication.getRedirectUri()));
|
authentication.getRedirectUri()));
|
||||||
}
|
}
|
||||||
@@ -351,17 +351,17 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenPkceMissingCodeChallengeMethodThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenPkceMissingCodeChallengeMethodThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
|
||||||
Map<String, Object> additionalParameters = new HashMap<>();
|
Map<String, Object> additionalParameters = new HashMap<>();
|
||||||
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge");
|
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge");
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), additionalParameters);
|
registeredClient.getScopes(), additionalParameters);
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD,
|
OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD,
|
||||||
authentication.getRedirectUri()));
|
authentication.getRedirectUri()));
|
||||||
}
|
}
|
||||||
@@ -369,13 +369,13 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenPrincipalNotAuthenticatedThenReturnAuthorizationCodeRequest() {
|
public void authenticateWhenPrincipalNotAuthenticatedThenReturnAuthorizationCodeRequest() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
this.principal.setAuthenticated(false);
|
this.principal.setAuthenticated(false);
|
||||||
|
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
||||||
@@ -390,12 +390,12 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
|
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
|
||||||
.build();
|
.build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0];
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
|
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authenticationResult = (OAuth2AuthorizationConsentAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationConsentAuthenticationToken authenticationResult = (OAuth2AuthorizationConsentAuthenticationToken) this.authenticationProvider
|
||||||
@@ -436,17 +436,17 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
public void authenticateWhenRequireAuthorizationConsentAndOnlyOpenidScopeRequestedThenAuthorizationConsentNotRequired() {
|
public void authenticateWhenRequireAuthorizationConsentAndOnlyOpenidScopeRequestedThenAuthorizationConsentNotRequired() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
|
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
|
||||||
.scopes(scopes -> {
|
.scopes((scopes) -> {
|
||||||
scopes.clear();
|
scopes.clear();
|
||||||
scopes.add(OidcScopes.OPENID);
|
scopes.add(OidcScopes.OPENID);
|
||||||
})
|
})
|
||||||
.build();
|
.build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
||||||
@@ -461,19 +461,19 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
|
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
|
||||||
.build();
|
.build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
OAuth2AuthorizationConsent.Builder builder = OAuth2AuthorizationConsent.withId(registeredClient.getId(),
|
OAuth2AuthorizationConsent.Builder builder = OAuth2AuthorizationConsent.withId(registeredClient.getId(),
|
||||||
this.principal.getName());
|
this.principal.getName());
|
||||||
registeredClient.getScopes().forEach(builder::scope);
|
registeredClient.getScopes().forEach(builder::scope);
|
||||||
OAuth2AuthorizationConsent previousAuthorizationConsent = builder.build();
|
OAuth2AuthorizationConsent previousAuthorizationConsent = builder.build();
|
||||||
when(this.authorizationConsentService.findById(eq(registeredClient.getId()), eq(this.principal.getName())))
|
given(this.authorizationConsentService.findById(eq(registeredClient.getId()), eq(this.principal.getName())))
|
||||||
.thenReturn(previousAuthorizationConsent);
|
.willReturn(previousAuthorizationConsent);
|
||||||
|
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
||||||
@@ -511,15 +511,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenAuthorizationCodeRequestValidThenReturnAuthorizationCode() {
|
public void authenticateWhenAuthorizationCodeRequestValidThenReturnAuthorizationCode() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0];
|
||||||
Map<String, Object> additionalParameters = new HashMap<>();
|
Map<String, Object> additionalParameters = new HashMap<>();
|
||||||
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge");
|
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge");
|
||||||
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256");
|
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256");
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), additionalParameters);
|
registeredClient.getScopes(), additionalParameters);
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
||||||
@@ -532,8 +532,8 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenAuthorizationCodeNotGeneratedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenAuthorizationCodeNotGeneratedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
OAuth2TokenGenerator<OAuth2AuthorizationCode> authorizationCodeGenerator = mock(OAuth2TokenGenerator.class);
|
OAuth2TokenGenerator<OAuth2AuthorizationCode> authorizationCodeGenerator = mock(OAuth2TokenGenerator.class);
|
||||||
@@ -541,13 +541,13 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
|
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthorizationCodeRequestAuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthorizationCodeRequestAuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
||||||
assertThat(error.getDescription())
|
assertThat(error.getDescription())
|
||||||
.contains("The token generator failed to generate the authorization code.");
|
.contains("The token generator failed to generate the authorization code.");
|
||||||
@@ -557,8 +557,8 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenCustomAuthenticationValidatorThenUsed() {
|
public void authenticateWhenCustomAuthenticationValidatorThenUsed() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> authenticationValidator = mock(Consumer.class);
|
Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> authenticationValidator = mock(Consumer.class);
|
||||||
@@ -566,7 +566,7 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
|
|||||||
|
|
||||||
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
|
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
|
||||||
registeredClient.getScopes(), null);
|
registeredClient.getScopes(), null);
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
||||||
|
|||||||
@@ -107,7 +107,7 @@ public class OAuth2AuthorizationConsentAuthenticationContextTests {
|
|||||||
.authorization(this.authorization)
|
.authorization(this.authorization)
|
||||||
.authorizationRequest(this.authorizationRequest)
|
.authorizationRequest(this.authorizationRequest)
|
||||||
.put("custom-key-1", "custom-value-1")
|
.put("custom-key-1", "custom-value-1")
|
||||||
.context(ctx -> ctx.put("custom-key-2", "custom-value-2"))
|
.context((ctx) -> ctx.put("custom-key-2", "custom-value-2"))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
assertThat(context.<Authentication>getAuthentication()).isEqualTo(this.authorizationConsentAuthentication);
|
assertThat(context.<Authentication>getAuthentication()).isEqualTo(this.authorizationConsentAuthentication);
|
||||||
|
|||||||
@@ -49,10 +49,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link OAuth2AuthorizationConsentAuthenticationProvider}.
|
* Tests for {@link OAuth2AuthorizationConsentAuthenticationProvider}.
|
||||||
@@ -141,14 +141,14 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
public void authenticateWhenInvalidStateThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenInvalidStateThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(),
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(),
|
||||||
null);
|
null);
|
||||||
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
||||||
.thenReturn(null);
|
.willReturn(null);
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,15 +159,15 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
.principalName(this.principal.getName())
|
.principalName(this.principal.getName())
|
||||||
.build();
|
.build();
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(),
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(),
|
||||||
null);
|
null);
|
||||||
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
this.principal.setAuthenticated(false);
|
this.principal.setAuthenticated(false);
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,14 +178,14 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
.principalName(this.principal.getName().concat("-other"))
|
.principalName(this.principal.getName().concat("-other"))
|
||||||
.build();
|
.build();
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(),
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(),
|
||||||
null);
|
null);
|
||||||
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,43 +195,43 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
||||||
.principalName(this.principal.getName())
|
.principalName(this.principal.getName())
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(eq("state"), eq(STATE_TOKEN_TYPE))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(eq("state"), eq(STATE_TOKEN_TYPE))).willReturn(authorization);
|
||||||
RegisteredClient otherRegisteredClient = TestRegisteredClients.registeredClient2().build();
|
RegisteredClient otherRegisteredClient = TestRegisteredClients.registeredClient2().build();
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, otherRegisteredClient.getClientId(), principal, STATE, registeredClient.getScopes(),
|
AUTHORIZATION_URI, otherRegisteredClient.getClientId(), this.principal, STATE,
|
||||||
null);
|
registeredClient.getScopes(), null);
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void authenticateWhenDoesNotMatchClientThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenDoesNotMatchClientThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
RegisteredClient otherRegisteredClient = TestRegisteredClients.registeredClient2().build();
|
RegisteredClient otherRegisteredClient = TestRegisteredClients.registeredClient2().build();
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(otherRegisteredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(otherRegisteredClient)
|
||||||
.principalName(this.principal.getName())
|
.principalName(this.principal.getName())
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(eq("state"), eq(STATE_TOKEN_TYPE))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(eq("state"), eq(STATE_TOKEN_TYPE))).willReturn(authorization);
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(),
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(),
|
||||||
null);
|
null);
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null));
|
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void authenticateWhenScopeNotRequestedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenScopeNotRequestedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
||||||
.principalName(this.principal.getName())
|
.principalName(this.principal.getName())
|
||||||
.build();
|
.build();
|
||||||
@@ -240,37 +240,37 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
Set<String> authorizedScopes = new HashSet<>(authorizationRequest.getScopes());
|
Set<String> authorizedScopes = new HashSet<>(authorizationRequest.getScopes());
|
||||||
authorizedScopes.add("scope-not-requested");
|
authorizedScopes.add("scope-not-requested");
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, authorizedScopes, null);
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, authorizedScopes, null);
|
||||||
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE, authorizationRequest.getRedirectUri()));
|
OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE, authorizationRequest.getRedirectUri()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void authenticateWhenNotApprovedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
public void authenticateWhenNotApprovedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
||||||
.principalName(this.principal.getName())
|
.principalName(this.principal.getName())
|
||||||
.build();
|
.build();
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); // No
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); // No
|
||||||
// scopes
|
// scopes
|
||||||
// approved
|
// approved
|
||||||
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2AuthorizationRequest authorizationRequest = authorization
|
OAuth2AuthorizationRequest authorizationRequest = authorization
|
||||||
.getAttribute(OAuth2AuthorizationRequest.class.getName());
|
.getAttribute(OAuth2AuthorizationRequest.class.getName());
|
||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ParameterNames.CLIENT_ID,
|
OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ParameterNames.CLIENT_ID,
|
||||||
authorizationRequest.getRedirectUri()));
|
authorizationRequest.getRedirectUri()));
|
||||||
|
|
||||||
@@ -280,8 +280,8 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenApproveAllThenReturnAuthorizationCode() {
|
public void authenticateWhenApproveAllThenReturnAuthorizationCode() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
||||||
.principalName(this.principal.getName())
|
.principalName(this.principal.getName())
|
||||||
.build();
|
.build();
|
||||||
@@ -289,11 +289,11 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
.getAttribute(OAuth2AuthorizationRequest.class.getName());
|
.getAttribute(OAuth2AuthorizationRequest.class.getName());
|
||||||
Set<String> authorizedScopes = authorizationRequest.getScopes();
|
Set<String> authorizedScopes = authorizationRequest.getScopes();
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, authorizedScopes, null); // Approve
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, authorizedScopes, null); // Approve
|
||||||
// all
|
// all
|
||||||
// scopes
|
// scopes
|
||||||
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -305,8 +305,8 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenCustomAuthorizationConsentCustomizerThenUsed() {
|
public void authenticateWhenCustomAuthorizationConsentCustomizerThenUsed() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
||||||
.principalName(this.principal.getName())
|
.principalName(this.principal.getName())
|
||||||
.build();
|
.build();
|
||||||
@@ -314,11 +314,11 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
.getAttribute(OAuth2AuthorizationRequest.class.getName());
|
.getAttribute(OAuth2AuthorizationRequest.class.getName());
|
||||||
Set<String> authorizedScopes = authorizationRequest.getScopes();
|
Set<String> authorizedScopes = authorizationRequest.getScopes();
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, authorizedScopes, null); // Approve
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, authorizedScopes, null); // Approve
|
||||||
// all
|
// all
|
||||||
// scopes
|
// scopes
|
||||||
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
Consumer<OAuth2AuthorizationConsentAuthenticationContext> authorizationConsentCustomizer = mock(Consumer.class);
|
Consumer<OAuth2AuthorizationConsentAuthenticationContext> authorizationConsentCustomizer = mock(Consumer.class);
|
||||||
@@ -391,31 +391,31 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
public void authenticateWhenApproveNoneAndRevokePreviouslyApprovedThenAuthorizationConsentRemoved() {
|
public void authenticateWhenApproveNoneAndRevokePreviouslyApprovedThenAuthorizationConsentRemoved() {
|
||||||
String previouslyApprovedScope = "message.read";
|
String previouslyApprovedScope = "message.read";
|
||||||
String requestedScope = "message.write";
|
String requestedScope = "message.write";
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> {
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> {
|
||||||
scopes.clear();
|
scopes.clear();
|
||||||
scopes.add(previouslyApprovedScope);
|
scopes.add(previouslyApprovedScope);
|
||||||
scopes.add(requestedScope);
|
scopes.add(requestedScope);
|
||||||
}).build();
|
}).build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
||||||
.principalName(this.principal.getName())
|
.principalName(this.principal.getName())
|
||||||
.build();
|
.build();
|
||||||
OAuth2AuthorizationRequest authorizationRequest = authorization
|
OAuth2AuthorizationRequest authorizationRequest = authorization
|
||||||
.getAttribute(OAuth2AuthorizationRequest.class.getName());
|
.getAttribute(OAuth2AuthorizationRequest.class.getName());
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); // No
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); // No
|
||||||
// scopes
|
// scopes
|
||||||
// approved
|
// approved
|
||||||
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent
|
OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent
|
||||||
.withId(authorization.getRegisteredClientId(), authorization.getPrincipalName())
|
.withId(authorization.getRegisteredClientId(), authorization.getPrincipalName())
|
||||||
.scope(previouslyApprovedScope)
|
.scope(previouslyApprovedScope)
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
|
given(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
|
||||||
eq(authorization.getPrincipalName())))
|
eq(authorization.getPrincipalName())))
|
||||||
.thenReturn(previousAuthorizationConsent);
|
.willReturn(previousAuthorizationConsent);
|
||||||
|
|
||||||
// Revoke all (including previously approved)
|
// Revoke all (including previously approved)
|
||||||
this.authenticationProvider.setAuthorizationConsentCustomizer(
|
this.authenticationProvider.setAuthorizationConsentCustomizer(
|
||||||
@@ -424,7 +424,7 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
|
||||||
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
|
||||||
OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ParameterNames.CLIENT_ID,
|
OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ParameterNames.CLIENT_ID,
|
||||||
authorizationRequest.getRedirectUri()));
|
authorizationRequest.getRedirectUri()));
|
||||||
|
|
||||||
@@ -437,13 +437,13 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
String previouslyApprovedScope = "message.read";
|
String previouslyApprovedScope = "message.read";
|
||||||
String requestedScope = "message.write";
|
String requestedScope = "message.write";
|
||||||
String otherPreviouslyApprovedScope = "other.scope";
|
String otherPreviouslyApprovedScope = "other.scope";
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> {
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> {
|
||||||
scopes.clear();
|
scopes.clear();
|
||||||
scopes.add(previouslyApprovedScope);
|
scopes.add(previouslyApprovedScope);
|
||||||
scopes.add(requestedScope);
|
scopes.add(requestedScope);
|
||||||
}).build();
|
}).build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
||||||
.principalName(this.principal.getName())
|
.principalName(this.principal.getName())
|
||||||
.build();
|
.build();
|
||||||
@@ -451,17 +451,17 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
.getAttribute(OAuth2AuthorizationRequest.class.getName());
|
.getAttribute(OAuth2AuthorizationRequest.class.getName());
|
||||||
Set<String> requestedScopes = authorizationRequest.getScopes();
|
Set<String> requestedScopes = authorizationRequest.getScopes();
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, requestedScopes, null);
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, requestedScopes, null);
|
||||||
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent
|
OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent
|
||||||
.withId(authorization.getRegisteredClientId(), authorization.getPrincipalName())
|
.withId(authorization.getRegisteredClientId(), authorization.getPrincipalName())
|
||||||
.scope(previouslyApprovedScope)
|
.scope(previouslyApprovedScope)
|
||||||
.scope(otherPreviouslyApprovedScope)
|
.scope(otherPreviouslyApprovedScope)
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
|
given(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
|
||||||
eq(authorization.getPrincipalName())))
|
eq(authorization.getPrincipalName())))
|
||||||
.thenReturn(previousAuthorizationConsent);
|
.willReturn(previousAuthorizationConsent);
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -489,29 +489,29 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
|
|||||||
public void authenticateWhenApproveNoneAndPreviouslyApprovedThenAuthorizationConsentNotUpdated() {
|
public void authenticateWhenApproveNoneAndPreviouslyApprovedThenAuthorizationConsentNotUpdated() {
|
||||||
String previouslyApprovedScope = "message.read";
|
String previouslyApprovedScope = "message.read";
|
||||||
String requestedScope = "message.write";
|
String requestedScope = "message.write";
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> {
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> {
|
||||||
scopes.clear();
|
scopes.clear();
|
||||||
scopes.add(previouslyApprovedScope);
|
scopes.add(previouslyApprovedScope);
|
||||||
scopes.add(requestedScope);
|
scopes.add(requestedScope);
|
||||||
}).build();
|
}).build();
|
||||||
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
|
||||||
.thenReturn(registeredClient);
|
.willReturn(registeredClient);
|
||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
||||||
.principalName(this.principal.getName())
|
.principalName(this.principal.getName())
|
||||||
.build();
|
.build();
|
||||||
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
|
||||||
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); // No
|
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); // No
|
||||||
// scopes
|
// scopes
|
||||||
// approved
|
// approved
|
||||||
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
|
||||||
.thenReturn(authorization);
|
.willReturn(authorization);
|
||||||
OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent
|
OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent
|
||||||
.withId(authorization.getRegisteredClientId(), authorization.getPrincipalName())
|
.withId(authorization.getRegisteredClientId(), authorization.getPrincipalName())
|
||||||
.scope(previouslyApprovedScope)
|
.scope(previouslyApprovedScope)
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
|
given(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
|
||||||
eq(authorization.getPrincipalName())))
|
eq(authorization.getPrincipalName())))
|
||||||
.thenReturn(previousAuthorizationConsent);
|
.willReturn(previousAuthorizationConsent);
|
||||||
|
|
||||||
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
|
|||||||
@@ -60,11 +60,11 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke
|
|||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.doReturn;
|
import static org.mockito.Mockito.doReturn;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.spy;
|
import static org.mockito.Mockito.spy;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link OAuth2ClientCredentialsAuthenticationProvider}.
|
* Tests for {@link OAuth2ClientCredentialsAuthenticationProvider}.
|
||||||
@@ -159,7 +159,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
}
|
}
|
||||||
@@ -175,7 +175,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||||
}
|
}
|
||||||
@@ -183,7 +183,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
|
|||||||
@Test
|
@Test
|
||||||
public void authenticateWhenClientNotAuthorizedToRequestTokenThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenClientNotAuthorizedToRequestTokenThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2()
|
||||||
.authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.CLIENT_CREDENTIALS))
|
.authorizationGrantTypes((grantTypes) -> grantTypes.remove(AuthorizationGrantType.CLIENT_CREDENTIALS))
|
||||||
.build();
|
.build();
|
||||||
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
|
||||||
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
|
||||||
@@ -192,7 +192,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
|
.isEqualTo(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
|
||||||
}
|
}
|
||||||
@@ -207,7 +207,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.extracting("errorCode")
|
.extracting("errorCode")
|
||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_SCOPE);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_SCOPE);
|
||||||
}
|
}
|
||||||
@@ -221,7 +221,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
|
|||||||
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
|
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
|
||||||
clientPrincipal, requestedScope, null);
|
clientPrincipal, requestedScope, null);
|
||||||
|
|
||||||
when(this.jwtEncoder.encode(any())).thenReturn(createJwt(Collections.singleton("mapped-scoped")));
|
given(this.jwtEncoder.encode(any())).willReturn(createJwt(Collections.singleton("mapped-scoped")));
|
||||||
|
|
||||||
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -236,7 +236,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
|
|||||||
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
|
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
|
||||||
clientPrincipal, null, null);
|
clientPrincipal, null, null);
|
||||||
|
|
||||||
when(this.jwtEncoder.encode(any())).thenReturn(createJwt(Collections.singleton("mapped-scoped")));
|
given(this.jwtEncoder.encode(any())).willReturn(createJwt(Collections.singleton("mapped-scoped")));
|
||||||
|
|
||||||
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -255,8 +255,8 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
|
|||||||
|
|
||||||
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.isInstanceOf(OAuth2AuthenticationException.class)
|
.isInstanceOf(OAuth2AuthenticationException.class)
|
||||||
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
|
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
|
||||||
.satisfies(error -> {
|
.satisfies((error) -> {
|
||||||
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
||||||
assertThat(error.getDescription()).contains("The token generator failed to generate the access token.");
|
assertThat(error.getDescription()).contains("The token generator failed to generate the access token.");
|
||||||
});
|
});
|
||||||
@@ -270,7 +270,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
|
|||||||
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
|
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
|
||||||
clientPrincipal, null, null);
|
clientPrincipal, null, null);
|
||||||
|
|
||||||
when(this.jwtEncoder.encode(any())).thenReturn(createJwt(registeredClient.getScopes()));
|
given(this.jwtEncoder.encode(any())).willReturn(createJwt(registeredClient.getScopes()));
|
||||||
|
|
||||||
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
|
|||||||
@@ -52,12 +52,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
|||||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.verifyNoInteractions;
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link OAuth2DeviceAuthorizationConsentAuthenticationProvider}.
|
* Tests for {@link OAuth2DeviceAuthorizationConsentAuthenticationProvider}.
|
||||||
@@ -149,7 +148,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(STATE,
|
||||||
|
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
|
||||||
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
|
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,7 +157,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
public void authenticateWhenPrincipalIsNotAuthenticatedThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenPrincipalIsNotAuthenticatedThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
TestingAuthenticationToken principal = new TestingAuthenticationToken(authorization.getPrincipalName(), null);
|
TestingAuthenticationToken principal = new TestingAuthenticationToken(authorization.getPrincipalName(), null);
|
||||||
Authentication authentication = new OAuth2DeviceAuthorizationConsentAuthenticationToken(AUTHORIZATION_URI,
|
Authentication authentication = new OAuth2DeviceAuthorizationConsentAuthenticationToken(AUTHORIZATION_URI,
|
||||||
registeredClient.getClientId(), principal, USER_CODE, STATE, null, Collections.emptyMap());
|
registeredClient.getClientId(), principal, USER_CODE, STATE, null, Collections.emptyMap());
|
||||||
@@ -170,7 +170,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(STATE,
|
||||||
|
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
|
||||||
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
|
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,7 +179,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
public void authenticateWhenPrincipalNameDoesNotMatchThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenPrincipalNameDoesNotMatchThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
TestingAuthenticationToken principal = new TestingAuthenticationToken("invalid", null, Collections.emptyList());
|
TestingAuthenticationToken principal = new TestingAuthenticationToken("invalid", null, Collections.emptyList());
|
||||||
Authentication authentication = new OAuth2DeviceAuthorizationConsentAuthenticationToken(AUTHORIZATION_URI,
|
Authentication authentication = new OAuth2DeviceAuthorizationConsentAuthenticationToken(AUTHORIZATION_URI,
|
||||||
registeredClient.getClientId(), principal, USER_CODE, STATE, null, Collections.emptyMap());
|
registeredClient.getClientId(), principal, USER_CODE, STATE, null, Collections.emptyMap());
|
||||||
@@ -191,7 +192,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(STATE,
|
||||||
|
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
|
||||||
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
|
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,7 +201,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
public void authenticateWhenRegisteredClientNotFoundThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenRegisteredClientNotFoundThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
Authentication authentication = createAuthentication(registeredClient);
|
Authentication authentication = createAuthentication(registeredClient);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
@@ -211,7 +213,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
||||||
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(STATE,
|
||||||
|
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
|
||||||
verifyNoMoreInteractions(this.registeredClientRepository, this.authorizationService);
|
verifyNoMoreInteractions(this.registeredClientRepository, this.authorizationService);
|
||||||
verifyNoInteractions(this.authorizationConsentService);
|
verifyNoInteractions(this.authorizationConsentService);
|
||||||
}
|
}
|
||||||
@@ -221,8 +224,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
RegisteredClient registeredClient2 = TestRegisteredClients.registeredClient2().build();
|
RegisteredClient registeredClient2 = TestRegisteredClients.registeredClient2().build();
|
||||||
OAuth2Authorization authorization = createAuthorization(registeredClient2);
|
OAuth2Authorization authorization = createAuthorization(registeredClient2);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
|
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
|
||||||
Authentication authentication = createAuthentication(registeredClient);
|
Authentication authentication = createAuthentication(registeredClient);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
@@ -234,7 +237,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
||||||
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(STATE,
|
||||||
|
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
|
||||||
verifyNoMoreInteractions(this.registeredClientRepository, this.authorizationService);
|
verifyNoMoreInteractions(this.registeredClientRepository, this.authorizationService);
|
||||||
verifyNoInteractions(this.authorizationConsentService);
|
verifyNoInteractions(this.authorizationConsentService);
|
||||||
}
|
}
|
||||||
@@ -247,8 +251,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
.scope("invalid")
|
.scope("invalid")
|
||||||
.build();
|
.build();
|
||||||
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
|
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
|
||||||
Authentication authentication = createAuthentication(registeredClient2);
|
Authentication authentication = createAuthentication(registeredClient2);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
@@ -260,7 +264,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
||||||
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(STATE,
|
||||||
|
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
|
||||||
verifyNoMoreInteractions(this.registeredClientRepository, this.authorizationService);
|
verifyNoMoreInteractions(this.registeredClientRepository, this.authorizationService);
|
||||||
verifyNoInteractions(this.authorizationConsentService);
|
verifyNoInteractions(this.authorizationConsentService);
|
||||||
}
|
}
|
||||||
@@ -271,8 +276,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient2 = TestRegisteredClients.registeredClient().scopes(Set::clear).build();
|
RegisteredClient registeredClient2 = TestRegisteredClients.registeredClient().scopes(Set::clear).build();
|
||||||
OAuth2Authorization authorization = createAuthorization(registeredClient2);
|
OAuth2Authorization authorization = createAuthorization(registeredClient2);
|
||||||
Authentication authentication = createAuthentication(registeredClient2);
|
Authentication authentication = createAuthentication(registeredClient2);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
|
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
@@ -282,7 +287,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
||||||
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(STATE,
|
||||||
|
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
|
||||||
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
||||||
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
||||||
verify(this.authorizationService).save(authorizationCaptor.capture());
|
verify(this.authorizationService).save(authorizationCaptor.capture());
|
||||||
@@ -305,8 +311,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
public void authenticateWhenAuthoritiesIsNotEmptyThenAuthorizationConsentSaved() {
|
public void authenticateWhenAuthoritiesIsNotEmptyThenAuthorizationConsentSaved() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
|
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
|
||||||
|
|
||||||
Authentication authentication = createAuthentication(registeredClient);
|
Authentication authentication = createAuthentication(registeredClient);
|
||||||
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
|
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
|
||||||
@@ -317,7 +323,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
assertThat(authenticationResult.getUserCode()).isEqualTo(USER_CODE);
|
assertThat(authenticationResult.getUserCode()).isEqualTo(USER_CODE);
|
||||||
|
|
||||||
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
||||||
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(STATE,
|
||||||
|
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
|
||||||
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
||||||
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
||||||
verify(this.authorizationConsentService).save(any(OAuth2AuthorizationConsent.class));
|
verify(this.authorizationConsentService).save(any(OAuth2AuthorizationConsent.class));
|
||||||
@@ -354,9 +361,9 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
OAuth2AuthorizationConsent.withId(registeredClient.getId(), authentication.getName())
|
OAuth2AuthorizationConsent.withId(registeredClient.getId(), authentication.getName())
|
||||||
.scope("scope1").build();
|
.scope("scope1").build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
|
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
|
||||||
when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(authorizationConsent);
|
given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(authorizationConsent);
|
||||||
|
|
||||||
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
|
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -367,7 +374,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
|
|
||||||
ArgumentCaptor<OAuth2AuthorizationConsent> authorizationConsentCaptor = ArgumentCaptor
|
ArgumentCaptor<OAuth2AuthorizationConsent> authorizationConsentCaptor = ArgumentCaptor
|
||||||
.forClass(OAuth2AuthorizationConsent.class);
|
.forClass(OAuth2AuthorizationConsent.class);
|
||||||
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(STATE,
|
||||||
|
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
|
||||||
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
||||||
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
||||||
verify(this.authorizationConsentService).save(authorizationConsentCaptor.capture());
|
verify(this.authorizationConsentService).save(authorizationConsentCaptor.capture());
|
||||||
@@ -390,9 +398,9 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(Set::clear).build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(Set::clear).build();
|
||||||
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
OAuth2Authorization authorization = createAuthorization(registeredClient);
|
||||||
Authentication authentication = createAuthentication(registeredClient);
|
Authentication authentication = createAuthentication(registeredClient);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
|
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
|
||||||
when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(null);
|
given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(null);
|
||||||
|
|
||||||
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
|
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -403,7 +411,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
|
|||||||
|
|
||||||
ArgumentCaptor<OAuth2AuthorizationConsent> authorizationConsentCaptor = ArgumentCaptor
|
ArgumentCaptor<OAuth2AuthorizationConsent> authorizationConsentCaptor = ArgumentCaptor
|
||||||
.forClass(OAuth2AuthorizationConsent.class);
|
.forClass(OAuth2AuthorizationConsent.class);
|
||||||
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(STATE,
|
||||||
|
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
|
||||||
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId());
|
||||||
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
||||||
verify(this.authorizationConsentService).save(authorizationConsentCaptor.capture());
|
verify(this.authorizationConsentService).save(authorizationConsentCaptor.capture());
|
||||||
|
|||||||
@@ -48,13 +48,11 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.verifyNoInteractions;
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceAuthorizationRequestAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE;
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceAuthorizationRequestAuthenticationProvider.USER_CODE_TOKEN_TYPE;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link OAuth2DeviceAuthorizationRequestAuthenticationProvider}.
|
* Tests for {@link OAuth2DeviceAuthorizationRequestAuthenticationProvider}.
|
||||||
@@ -171,7 +169,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests {
|
|||||||
public void authenticateWhenDeviceCodeIsNullThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenDeviceCodeIsNullThenThrowOAuth2AuthenticationException() {
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
OAuth2TokenGenerator<OAuth2DeviceCode> deviceCodeGenerator = mock(OAuth2TokenGenerator.class);
|
OAuth2TokenGenerator<OAuth2DeviceCode> deviceCodeGenerator = mock(OAuth2TokenGenerator.class);
|
||||||
when(deviceCodeGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(null);
|
given(deviceCodeGenerator.generate(any(OAuth2TokenContext.class))).willReturn(null);
|
||||||
this.authenticationProvider.setDeviceCodeGenerator(deviceCodeGenerator);
|
this.authenticationProvider.setDeviceCodeGenerator(deviceCodeGenerator);
|
||||||
|
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
@@ -196,7 +194,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests {
|
|||||||
public void authenticateWhenUserCodeIsNullThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenUserCodeIsNullThenThrowOAuth2AuthenticationException() {
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
OAuth2TokenGenerator<OAuth2UserCode> userCodeGenerator = mock(OAuth2TokenGenerator.class);
|
OAuth2TokenGenerator<OAuth2UserCode> userCodeGenerator = mock(OAuth2TokenGenerator.class);
|
||||||
when(userCodeGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(null);
|
given(userCodeGenerator.generate(any(OAuth2TokenContext.class))).willReturn(null);
|
||||||
this.authenticationProvider.setUserCodeGenerator(userCodeGenerator);
|
this.authenticationProvider.setUserCodeGenerator(userCodeGenerator);
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
.authorizationGrantType(AuthorizationGrantType.DEVICE_CODE)
|
.authorizationGrantType(AuthorizationGrantType.DEVICE_CODE)
|
||||||
@@ -277,7 +275,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests {
|
|||||||
public void authenticateWhenDeviceCodeGeneratorSetThenUsed() {
|
public void authenticateWhenDeviceCodeGeneratorSetThenUsed() {
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
OAuth2TokenGenerator<OAuth2DeviceCode> deviceCodeGenerator = mock(OAuth2TokenGenerator.class);
|
OAuth2TokenGenerator<OAuth2DeviceCode> deviceCodeGenerator = mock(OAuth2TokenGenerator.class);
|
||||||
when(deviceCodeGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(createDeviceCode());
|
given(deviceCodeGenerator.generate(any(OAuth2TokenContext.class))).willReturn(createDeviceCode());
|
||||||
this.authenticationProvider.setDeviceCodeGenerator(deviceCodeGenerator);
|
this.authenticationProvider.setDeviceCodeGenerator(deviceCodeGenerator);
|
||||||
|
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
@@ -303,14 +301,15 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests {
|
|||||||
assertThat(tokenContext.getAuthorizationServerContext()).isNotNull();
|
assertThat(tokenContext.getAuthorizationServerContext()).isNotNull();
|
||||||
assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.DEVICE_CODE);
|
assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.DEVICE_CODE);
|
||||||
assertThat(tokenContext.<Authentication>getAuthorizationGrant()).isEqualTo(authentication);
|
assertThat(tokenContext.<Authentication>getAuthorizationGrant()).isEqualTo(authentication);
|
||||||
assertThat(tokenContext.getTokenType()).isEqualTo(DEVICE_CODE_TOKEN_TYPE);
|
assertThat(tokenContext.getTokenType())
|
||||||
|
.isEqualTo(OAuth2DeviceAuthorizationRequestAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void authenticateWhenUserCodeGeneratorSetThenUsed() {
|
public void authenticateWhenUserCodeGeneratorSetThenUsed() {
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
OAuth2TokenGenerator<OAuth2UserCode> userCodeGenerator = mock(OAuth2TokenGenerator.class);
|
OAuth2TokenGenerator<OAuth2UserCode> userCodeGenerator = mock(OAuth2TokenGenerator.class);
|
||||||
when(userCodeGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(createUserCode());
|
given(userCodeGenerator.generate(any(OAuth2TokenContext.class))).willReturn(createUserCode());
|
||||||
this.authenticationProvider.setUserCodeGenerator(userCodeGenerator);
|
this.authenticationProvider.setUserCodeGenerator(userCodeGenerator);
|
||||||
|
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
|
||||||
@@ -335,7 +334,8 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests {
|
|||||||
assertThat(tokenContext.getAuthorizationServerContext()).isNotNull();
|
assertThat(tokenContext.getAuthorizationServerContext()).isNotNull();
|
||||||
assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.DEVICE_CODE);
|
assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.DEVICE_CODE);
|
||||||
assertThat(tokenContext.<Authentication>getAuthorizationGrant()).isEqualTo(authentication);
|
assertThat(tokenContext.<Authentication>getAuthorizationGrant()).isEqualTo(authentication);
|
||||||
assertThat(tokenContext.getTokenType()).isEqualTo(USER_CODE_TOKEN_TYPE);
|
assertThat(tokenContext.getTokenType())
|
||||||
|
.isEqualTo(OAuth2DeviceAuthorizationRequestAuthenticationProvider.USER_CODE_TOKEN_TYPE);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void mockAuthorizationServerContext() {
|
private static void mockAuthorizationServerContext() {
|
||||||
|
|||||||
@@ -55,15 +55,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
|||||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.times;
|
import static org.mockito.Mockito.times;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.verifyNoInteractions;
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceCodeAuthenticationProvider.AUTHORIZATION_PENDING;
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE;
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceCodeAuthenticationProvider.EXPIRED_TOKEN;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link OAuth2DeviceCodeAuthenticationProvider}.
|
* Tests for {@link OAuth2DeviceCodeAuthenticationProvider}.
|
||||||
@@ -142,7 +139,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
public void authenticateWhenAuthorizationNotFoundThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenAuthorizationNotFoundThenThrowOAuth2AuthenticationException() {
|
||||||
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
|
||||||
Authentication authentication = createAuthentication(registeredClient);
|
Authentication authentication = createAuthentication(registeredClient);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(null);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(null);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
@@ -151,7 +148,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(DEVICE_CODE,
|
||||||
|
OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
|
||||||
verifyNoMoreInteractions(this.authorizationService);
|
verifyNoMoreInteractions(this.authorizationService);
|
||||||
verifyNoInteractions(this.tokenGenerator);
|
verifyNoInteractions(this.tokenGenerator);
|
||||||
}
|
}
|
||||||
@@ -164,7 +162,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient2)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient2)
|
||||||
.token(createDeviceCode())
|
.token(createDeviceCode())
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
@@ -174,7 +172,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
||||||
verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(DEVICE_CODE,
|
||||||
|
OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
|
||||||
verify(this.authorizationService).save(authorizationCaptor.capture());
|
verify(this.authorizationService).save(authorizationCaptor.capture());
|
||||||
verifyNoMoreInteractions(this.authorizationService);
|
verifyNoMoreInteractions(this.authorizationService);
|
||||||
verifyNoInteractions(this.tokenGenerator);
|
verifyNoInteractions(this.tokenGenerator);
|
||||||
@@ -194,16 +193,17 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
|
||||||
.token(createUserCode())
|
.token(createUserCode())
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.extracting(OAuth2AuthenticationException::getError)
|
.extracting(OAuth2AuthenticationException::getError)
|
||||||
.extracting(OAuth2Error::getErrorCode)
|
.extracting(OAuth2Error::getErrorCode)
|
||||||
.isEqualTo(AUTHORIZATION_PENDING);
|
.isEqualTo(OAuth2DeviceCodeAuthenticationProvider.AUTHORIZATION_PENDING);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(DEVICE_CODE,
|
||||||
|
OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
|
||||||
verifyNoMoreInteractions(this.authorizationService);
|
verifyNoMoreInteractions(this.authorizationService);
|
||||||
verifyNoInteractions(this.tokenGenerator);
|
verifyNoInteractions(this.tokenGenerator);
|
||||||
}
|
}
|
||||||
@@ -216,7 +216,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.token(createDeviceCode(), withInvalidated())
|
.token(createDeviceCode(), withInvalidated())
|
||||||
.token(createUserCode(), withInvalidated())
|
.token(createUserCode(), withInvalidated())
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
@@ -225,7 +225,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.isEqualTo(OAuth2ErrorCodes.ACCESS_DENIED);
|
.isEqualTo(OAuth2ErrorCodes.ACCESS_DENIED);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(DEVICE_CODE,
|
||||||
|
OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
|
||||||
verifyNoMoreInteractions(this.authorizationService);
|
verifyNoMoreInteractions(this.authorizationService);
|
||||||
verifyNoInteractions(this.tokenGenerator);
|
verifyNoInteractions(this.tokenGenerator);
|
||||||
}
|
}
|
||||||
@@ -238,17 +239,18 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.token(createExpiredDeviceCode())
|
.token(createExpiredDeviceCode())
|
||||||
.token(createUserCode(), withInvalidated())
|
.token(createUserCode(), withInvalidated())
|
||||||
.build();
|
.build();
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
.extracting(OAuth2AuthenticationException::getError)
|
.extracting(OAuth2AuthenticationException::getError)
|
||||||
.extracting(OAuth2Error::getErrorCode)
|
.extracting(OAuth2Error::getErrorCode)
|
||||||
.isEqualTo(EXPIRED_TOKEN);
|
.isEqualTo(OAuth2DeviceCodeAuthenticationProvider.EXPIRED_TOKEN);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
||||||
verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(DEVICE_CODE,
|
||||||
|
OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
|
||||||
verify(this.authorizationService).save(authorizationCaptor.capture());
|
verify(this.authorizationService).save(authorizationCaptor.capture());
|
||||||
verifyNoMoreInteractions(this.authorizationService);
|
verifyNoMoreInteractions(this.authorizationService);
|
||||||
verifyNoInteractions(this.tokenGenerator);
|
verifyNoInteractions(this.tokenGenerator);
|
||||||
@@ -272,8 +274,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.attribute(Principal.class.getName(), authentication.getPrincipal())
|
.attribute(Principal.class.getName(), authentication.getPrincipal())
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(null);
|
given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(null);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
@@ -283,7 +285,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
.isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(DEVICE_CODE,
|
||||||
|
OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
|
||||||
verify(this.tokenGenerator).generate(any(OAuth2TokenContext.class));
|
verify(this.tokenGenerator).generate(any(OAuth2TokenContext.class));
|
||||||
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
|
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
|
||||||
}
|
}
|
||||||
@@ -299,8 +302,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.attribute(Principal.class.getName(), authentication.getPrincipal())
|
.attribute(Principal.class.getName(), authentication.getPrincipal())
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(createAccessToken(),
|
given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(createAccessToken(),
|
||||||
(OAuth2RefreshToken) null);
|
(OAuth2RefreshToken) null);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
@@ -311,7 +314,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
.isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(DEVICE_CODE,
|
||||||
|
OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
|
||||||
verify(this.tokenGenerator, times(2)).generate(any(OAuth2TokenContext.class));
|
verify(this.tokenGenerator, times(2)).generate(any(OAuth2TokenContext.class));
|
||||||
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
|
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
|
||||||
}
|
}
|
||||||
@@ -327,9 +331,9 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.attribute(Principal.class.getName(), authentication.getPrincipal())
|
.attribute(Principal.class.getName(), authentication.getPrincipal())
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
OAuth2AccessToken accessToken = createAccessToken();
|
OAuth2AccessToken accessToken = createAccessToken();
|
||||||
when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(accessToken, accessToken);
|
given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(accessToken, accessToken);
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
|
||||||
@@ -339,7 +343,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
.isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(DEVICE_CODE,
|
||||||
|
OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
|
||||||
verify(this.tokenGenerator, times(2)).generate(any(OAuth2TokenContext.class));
|
verify(this.tokenGenerator, times(2)).generate(any(OAuth2TokenContext.class));
|
||||||
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
|
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
|
||||||
}
|
}
|
||||||
@@ -355,10 +360,10 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
.attribute(Principal.class.getName(), authentication.getPrincipal())
|
.attribute(Principal.class.getName(), authentication.getPrincipal())
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
OAuth2AccessToken accessToken = createAccessToken();
|
OAuth2AccessToken accessToken = createAccessToken();
|
||||||
OAuth2RefreshToken refreshToken = createRefreshToken();
|
OAuth2RefreshToken refreshToken = createRefreshToken();
|
||||||
when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(accessToken, refreshToken);
|
given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(accessToken, refreshToken);
|
||||||
OAuth2AccessTokenAuthenticationToken authenticationResult = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
OAuth2AccessTokenAuthenticationToken authenticationResult = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
assertThat(authenticationResult.getRegisteredClient()).isEqualTo(registeredClient);
|
assertThat(authenticationResult.getRegisteredClient()).isEqualTo(registeredClient);
|
||||||
@@ -368,7 +373,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
|
|||||||
|
|
||||||
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
||||||
ArgumentCaptor<OAuth2TokenContext> tokenContextCaptor = ArgumentCaptor.forClass(OAuth2TokenContext.class);
|
ArgumentCaptor<OAuth2TokenContext> tokenContextCaptor = ArgumentCaptor.forClass(OAuth2TokenContext.class);
|
||||||
verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(DEVICE_CODE,
|
||||||
|
OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
|
||||||
verify(this.authorizationService).save(authorizationCaptor.capture());
|
verify(this.authorizationService).save(authorizationCaptor.capture());
|
||||||
verify(this.tokenGenerator, times(2)).generate(tokenContextCaptor.capture());
|
verify(this.tokenGenerator, times(2)).generate(tokenContextCaptor.capture());
|
||||||
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
|
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
|
||||||
|
|||||||
@@ -55,12 +55,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
|||||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.BDDMockito.given;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.verifyNoInteractions;
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests for {@link OAuth2DeviceVerificationAuthenticationProvider}.
|
* Tests for {@link OAuth2DeviceVerificationAuthenticationProvider}.
|
||||||
@@ -130,7 +129,7 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void authenticateWhenAuthorizationNotFoundThenThrowOAuth2AuthenticationException() {
|
public void authenticateWhenAuthorizationNotFoundThenThrowOAuth2AuthenticationException() {
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(null);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(null);
|
||||||
Authentication authentication = createAuthentication();
|
Authentication authentication = createAuthentication();
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
assertThatExceptionOfType(OAuth2AuthenticationException.class)
|
||||||
@@ -140,7 +139,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
|
|||||||
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(USER_CODE, USER_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(USER_CODE,
|
||||||
|
OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE);
|
||||||
verifyNoMoreInteractions(this.authorizationService);
|
verifyNoMoreInteractions(this.authorizationService);
|
||||||
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
|
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
|
||||||
}
|
}
|
||||||
@@ -152,14 +152,15 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
|
|||||||
TestingAuthenticationToken principal = new TestingAuthenticationToken("user", null);
|
TestingAuthenticationToken principal = new TestingAuthenticationToken("user", null);
|
||||||
Authentication authentication = new OAuth2DeviceVerificationAuthenticationToken(principal, USER_CODE,
|
Authentication authentication = new OAuth2DeviceVerificationAuthenticationToken(principal, USER_CODE,
|
||||||
Collections.emptyMap());
|
Collections.emptyMap());
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
|
|
||||||
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
|
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
assertThat(authenticationResult).isEqualTo(authentication);
|
assertThat(authenticationResult).isEqualTo(authentication);
|
||||||
assertThat(authenticationResult.isAuthenticated()).isFalse();
|
assertThat(authenticationResult.isAuthenticated()).isFalse();
|
||||||
|
|
||||||
verify(this.authorizationService).findByToken(USER_CODE, USER_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(USER_CODE,
|
||||||
|
OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE);
|
||||||
verifyNoMoreInteractions(this.authorizationService);
|
verifyNoMoreInteractions(this.authorizationService);
|
||||||
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
|
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
|
||||||
}
|
}
|
||||||
@@ -175,9 +176,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
|
|||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
Authentication authentication = createAuthentication();
|
Authentication authentication = createAuthentication();
|
||||||
when(this.registeredClientRepository.findById(anyString())).thenReturn(registeredClient);
|
given(this.registeredClientRepository.findById(anyString())).willReturn(registeredClient);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(null);
|
given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(null);
|
||||||
|
|
||||||
OAuth2DeviceAuthorizationConsentAuthenticationToken authenticationResult = (OAuth2DeviceAuthorizationConsentAuthenticationToken) this.authenticationProvider
|
OAuth2DeviceAuthorizationConsentAuthenticationToken authenticationResult = (OAuth2DeviceAuthorizationConsentAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -191,7 +192,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
|
|||||||
assertThat(authenticationResult.getScopes()).isEmpty();
|
assertThat(authenticationResult.getScopes()).isEmpty();
|
||||||
|
|
||||||
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
||||||
verify(this.authorizationService).findByToken(USER_CODE, USER_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(USER_CODE,
|
||||||
|
OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE);
|
||||||
verify(this.registeredClientRepository).findById(authorization.getRegisteredClientId());
|
verify(this.registeredClientRepository).findById(authorization.getRegisteredClientId());
|
||||||
verify(this.authorizationService).save(authorizationCaptor.capture());
|
verify(this.authorizationService).save(authorizationCaptor.capture());
|
||||||
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
||||||
@@ -222,9 +224,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
|
|||||||
.scope(registeredClient.getScopes().iterator().next())
|
.scope(registeredClient.getScopes().iterator().next())
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.registeredClientRepository.findById(anyString())).thenReturn(registeredClient);
|
given(this.registeredClientRepository.findById(anyString())).willReturn(registeredClient);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(authorizationConsent);
|
given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(authorizationConsent);
|
||||||
|
|
||||||
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
|
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -234,7 +236,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
|
|||||||
assertThat(authenticationResult.getUserCode()).isEqualTo(USER_CODE);
|
assertThat(authenticationResult.getUserCode()).isEqualTo(USER_CODE);
|
||||||
|
|
||||||
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
||||||
verify(this.authorizationService).findByToken(USER_CODE, USER_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(USER_CODE,
|
||||||
|
OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE);
|
||||||
verify(this.registeredClientRepository).findById(authorization.getRegisteredClientId());
|
verify(this.registeredClientRepository).findById(authorization.getRegisteredClientId());
|
||||||
verify(this.authorizationService).save(authorizationCaptor.capture());
|
verify(this.authorizationService).save(authorizationCaptor.capture());
|
||||||
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
||||||
@@ -276,9 +279,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
|
|||||||
.scope("previous")
|
.scope("previous")
|
||||||
.build();
|
.build();
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
when(this.registeredClientRepository.findById(anyString())).thenReturn(registeredClient);
|
given(this.registeredClientRepository.findById(anyString())).willReturn(registeredClient);
|
||||||
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
|
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
|
||||||
when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(authorizationConsent);
|
given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(authorizationConsent);
|
||||||
|
|
||||||
OAuth2DeviceAuthorizationConsentAuthenticationToken authenticationResult = (OAuth2DeviceAuthorizationConsentAuthenticationToken) this.authenticationProvider
|
OAuth2DeviceAuthorizationConsentAuthenticationToken authenticationResult = (OAuth2DeviceAuthorizationConsentAuthenticationToken) this.authenticationProvider
|
||||||
.authenticate(authentication);
|
.authenticate(authentication);
|
||||||
@@ -292,7 +295,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
|
|||||||
assertThat(authenticationResult.getScopes()).containsExactly("previous");
|
assertThat(authenticationResult.getScopes()).containsExactly("previous");
|
||||||
|
|
||||||
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
|
||||||
verify(this.authorizationService).findByToken(USER_CODE, USER_CODE_TOKEN_TYPE);
|
verify(this.authorizationService).findByToken(USER_CODE,
|
||||||
|
OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE);
|
||||||
verify(this.registeredClientRepository).findById(authorization.getRegisteredClientId());
|
verify(this.registeredClientRepository).findById(authorization.getRegisteredClientId());
|
||||||
verify(this.authorizationService).save(authorizationCaptor.capture());
|
verify(this.authorizationService).save(authorizationCaptor.capture());
|
||||||
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user