Browse Source

Merge branch '1.2.x'

pull/1630/head
Joe Grandja 2 years ago
parent
commit
12b71ea8e2
  1. 8
      etc/checkstyle/checkstyle-suppressions.xml
  2. 57
      etc/checkstyle/checkstyle.xml
  3. 2
      etc/checkstyle/header.txt
  4. 20
      etc/checkstyle/suppressions.xml
  5. 11
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/AbstractOAuth2AuthorizationServerMetadata.java
  6. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java
  7. 25
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationService.java
  8. 22
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentService.java
  9. 142
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java
  10. 5
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2Authorization.java
  11. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentService.java
  12. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadata.java
  13. 8
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenIntrospection.java
  14. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenType.java
  15. 10
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/aot/hint/OAuth2AuthorizationServerBeanRegistrationAotProcessor.java
  16. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java
  17. 8
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java
  18. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java
  19. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationToken.java
  20. 10
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProvider.java
  21. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationToken.java
  22. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationGrantAuthenticationToken.java
  23. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientAuthenticationToken.java
  24. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProvider.java
  25. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationToken.java
  26. 20
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProvider.java
  27. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationToken.java
  28. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProvider.java
  29. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationToken.java
  30. 8
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProvider.java
  31. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProvider.java
  32. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationToken.java
  33. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProvider.java
  34. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationToken.java
  35. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProvider.java
  36. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationToken.java
  37. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProvider.java
  38. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/InMemoryRegisteredClientRepository.java
  39. 38
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java
  40. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClient.java
  41. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientRepository.java
  42. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/OAuth2AuthorizationServerConfiguration.java
  43. 5
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationEndpointConfigurer.java
  44. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerConfigurer.java
  45. 9
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataEndpointConfigurer.java
  46. 3
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientAuthenticationConfigurer.java
  47. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ConfigurerUtils.java
  48. 3
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceAuthorizationEndpointConfigurer.java
  49. 3
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceVerificationEndpointConfigurer.java
  50. 3
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenEndpointConfigurer.java
  51. 3
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionEndpointConfigurer.java
  52. 3
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationEndpointConfigurer.java
  53. 3
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationEndpointConfigurer.java
  54. 5
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcConfigurer.java
  55. 3
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcLogoutEndpointConfigurer.java
  56. 9
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationEndpointConfigurer.java
  57. 3
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoEndpointConfigurer.java
  58. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/http/converter/HttpMessageConverters.java
  59. 9
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistration.java
  60. 9
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfiguration.java
  61. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProvider.java
  62. 25
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/converter/OidcClientRegistrationRegisteredClientConverter.java
  63. 10
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/converter/RegisteredClientOidcClientRegistrationConverter.java
  64. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/HttpMessageConverters.java
  65. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverter.java
  66. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilter.java
  67. 5
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AbstractSettings.java
  68. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettings.java
  69. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettings.java
  70. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettings.java
  71. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/JwtGenerator.java
  72. 1
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSet.java
  73. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenCustomizer.java
  74. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenGenerator.java
  75. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/DefaultConsentPage.java
  76. 9
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilter.java
  77. 6
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilter.java
  78. 4
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilter.java
  79. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilter.java
  80. 2
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilter.java
  81. 8
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2AuthorizationCodeRequestAuthenticationConverter.java
  82. 3
      oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2ErrorAuthenticationFailureHandler.java
  83. 36
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentServiceTests.java
  84. 269
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationServiceTests.java
  85. 2
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java
  86. 18
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataTests.java
  87. 5
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/TestOAuth2Authorizations.java
  88. 90
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProviderTests.java
  89. 54
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProviderTests.java
  90. 12
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactoryTests.java
  91. 10
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationTokenTests.java
  92. 118
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java
  93. 156
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProviderTests.java
  94. 2
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContextTests.java
  95. 158
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProviderTests.java
  96. 22
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProviderTests.java
  97. 67
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProviderTests.java
  98. 18
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProviderTests.java
  99. 62
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProviderTests.java
  100. 40
      oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProviderTests.java
  101. Some files were not shown because too many files have changed in this diff Show More

8
etc/checkstyle/checkstyle-suppressions.xml

@ -0,0 +1,8 @@ @@ -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>

57
etc/checkstyle/checkstyle.xml

@ -1,51 +1,18 @@ @@ -1,51 +1,18 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"https://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<!-- Suppressions -->
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="com.puppycrawl.tools.checkstyle.Checker">
<module name="SuppressionFilter">
<property name="file" value="${config_loc}/suppressions.xml"/>
<property name="file"
value="${config_loc}/checkstyle-suppressions.xml" />
</module>
<!-- Root Checks -->
<module name="RegexpHeader">
<property name="headerFile" value="${config_loc}/header.txt"/>
<property name="fileExtensions" value="java"/>
<module name="com.puppycrawl.tools.checkstyle.checks.header.RegexpHeaderCheck">
<property name="headerFile" value="${config_loc}/header.txt" />
<property name="fileExtensions" value="java" />
</module>
<!-- Root Checks -->
<module name="TreeWalker">
<!-- 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 name="io.spring.javaformat.checkstyle.SpringChecks">
<property name="excludes" value="io.spring.javaformat.checkstyle.check.SpringHeaderCheck" />
<property name="excludes" value="com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck" />
</module>
</module>

2
etc/checkstyle/header.txt

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
^\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 * 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$

20
etc/checkstyle/suppressions.xml

@ -1,20 +0,0 @@ @@ -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>

11
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/AbstractOAuth2AuthorizationServerMetadata.java

@ -36,8 +36,8 @@ import org.springframework.util.Assert; @@ -36,8 +36,8 @@ import org.springframework.util.Assert;
*
* @author Daniel Garnier-Moiroux
* @author Joe Grandja
* @see OAuth2AuthorizationServerMetadataClaimAccessor
* @since 0.1.1
* @see OAuth2AuthorizationServerMetadataClaimAccessor
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc8414#section-3.2">3.2.
* Authorization Server Metadata Response</a>
* @see <a target="_blank" href=
@ -72,8 +72,11 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata @@ -72,8 +72,11 @@ public abstract class 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<>();
@ -509,7 +512,7 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata @@ -509,7 +512,7 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata
private void addClaimToClaimList(String name, String value) {
Assert.hasText(name, "name cannot be empty");
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);
}
@ -517,7 +520,7 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata @@ -517,7 +520,7 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
Assert.hasText(name, "name cannot be empty");
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);
valuesConsumer.accept(values);
}

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java

@ -63,7 +63,7 @@ public final class InMemoryOAuth2AuthorizationConsentService implements OAuth2Au @@ -63,7 +63,7 @@ public final class InMemoryOAuth2AuthorizationConsentService implements OAuth2Au
*/
public InMemoryOAuth2AuthorizationConsentService(List<OAuth2AuthorizationConsent> authorizationConsents) {
Assert.notNull(authorizationConsents, "authorizationConsents cannot be null");
authorizationConsents.forEach(authorizationConsent -> {
authorizationConsents.forEach((authorizationConsent) -> {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
int id = getId(authorizationConsent);
Assert.isTrue(!this.authorizationConsents.containsKey(id),

25
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationService.java

@ -94,7 +94,7 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza @@ -94,7 +94,7 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
*/
public InMemoryOAuth2AuthorizationService(List<OAuth2Authorization> authorizations) {
Assert.notNull(authorizations, "authorizations cannot be null");
authorizations.forEach(authorization -> {
authorizations.forEach((authorization) -> {
Assert.notNull(authorization, "authorization cannot be null");
Assert.isTrue(!this.authorizations.containsKey(authorization.getId()),
"The authorization must be unique. Found duplicate identifier: " + authorization.getId());
@ -129,7 +129,7 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza @@ -129,7 +129,7 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
public OAuth2Authorization findById(String id) {
Assert.hasText(id, "id cannot be empty");
OAuth2Authorization authorization = this.authorizations.get(id);
return authorization != null ? authorization : this.initializedAuthorizations.get(id);
return (authorization != null) ? authorization : this.initializedAuthorizations.get(id);
}
@Nullable
@ -164,19 +164,26 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza @@ -164,19 +164,26 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza
matchesRefreshToken(authorization, token) ||
matchesDeviceCode(authorization, token) ||
matchesUserCode(authorization, token);
} else if (OAuth2ParameterNames.STATE.equals(tokenType.getValue())) {
}
else if (OAuth2ParameterNames.STATE.equals(tokenType.getValue())) {
return matchesState(authorization, token);
} else if (OAuth2ParameterNames.CODE.equals(tokenType.getValue())) {
}
else if (OAuth2ParameterNames.CODE.equals(tokenType.getValue())) {
return matchesAuthorizationCode(authorization, token);
} else if (OAuth2TokenType.ACCESS_TOKEN.equals(tokenType)) {
}
else if (OAuth2TokenType.ACCESS_TOKEN.equals(tokenType)) {
return matchesAccessToken(authorization, token);
} else if (OidcParameterNames.ID_TOKEN.equals(tokenType.getValue())) {
}
else if (OidcParameterNames.ID_TOKEN.equals(tokenType.getValue())) {
return matchesIdToken(authorization, token);
} else if (OAuth2TokenType.REFRESH_TOKEN.equals(tokenType)) {
}
else if (OAuth2TokenType.REFRESH_TOKEN.equals(tokenType)) {
return matchesRefreshToken(authorization, token);
} else if (OAuth2ParameterNames.DEVICE_CODE.equals(tokenType.getValue())) {
}
else if (OAuth2ParameterNames.DEVICE_CODE.equals(tokenType.getValue())) {
return matchesDeviceCode(authorization, token);
} else if (OAuth2ParameterNames.USER_CODE.equals(tokenType.getValue())) {
}
else if (OAuth2ParameterNames.USER_CODE.equals(tokenType.getValue())) {
return matchesUserCode(authorization, token);
}
// @formatter:on

22
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentService.java

@ -71,17 +71,6 @@ import org.springframework.util.StringUtils; @@ -71,17 +71,6 @@ import org.springframework.util.StringUtils;
@ImportRuntimeHints(JdbcOAuth2AuthorizationConsentService.JdbcOAuth2AuthorizationConsentServiceRuntimeHintsRegistrar.class)
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
private static final String COLUMN_NAMES = "registered_client_id, "
+ "principal_name, "
@ -288,4 +277,15 @@ public class JdbcOAuth2AuthorizationConsentService implements OAuth2Authorizatio @@ -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"));
}
}
}

142
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java

@ -97,17 +97,6 @@ import org.springframework.util.StringUtils; @@ -97,17 +97,6 @@ import org.springframework.util.StringUtils;
@ImportRuntimeHints(JdbcOAuth2AuthorizationService.JdbcOAuth2AuthorizationServiceRuntimeHintsRegistrar.class)
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
private static final String COLUMN_NAMES = "id, "
+ "registered_client_id, "
@ -379,6 +368,70 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic @@ -379,6 +368,70 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
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
* {@code java.sql.ResultSet} to {@link OAuth2Authorization}.
@ -758,68 +811,15 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic @@ -758,68 +811,15 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic
}
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);
}
static class JdbcOAuth2AuthorizationServiceRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
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);
}
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.resources()
.registerResource(new ClassPathResource(
"org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql"));
}
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);
}
}

5
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2Authorization.java

@ -144,7 +144,7 @@ public class OAuth2Authorization implements Serializable { @@ -144,7 +144,7 @@ public class OAuth2Authorization implements Serializable {
public <T extends OAuth2Token> Token<T> getToken(Class<T> tokenType) {
Assert.notNull(tokenType, "tokenType cannot be null");
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 { @@ -234,12 +234,13 @@ public class OAuth2Authorization implements Serializable {
.authorizationGrantType(authorization.getAuthorizationGrantType())
.authorizedScopes(authorization.getAuthorizedScopes())
.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.
*
* @param <T> the type of the {@link OAuth2Token}
* @author Joe Grandja
* @since 0.1.0
*/

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentService.java

@ -15,11 +15,11 @@ @@ -15,11 +15,11 @@
*/
package org.springframework.security.oauth2.server.authorization;
import java.security.Principal;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import java.security.Principal;
/**
* Implementations of this interface are responsible for the management of
* {@link OAuth2AuthorizationConsent OAuth 2.0 Authorization Consent(s)}.

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadata.java

@ -52,13 +52,13 @@ public final class OAuth2AuthorizationServerMetadata extends AbstractOAuth2Autho @@ -52,13 +52,13 @@ public final class OAuth2AuthorizationServerMetadata extends AbstractOAuth2Autho
*/
public static Builder withClaims(Map<String, Object> claims) {
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}.
*/
public static class Builder extends AbstractBuilder<OAuth2AuthorizationServerMetadata, Builder> {
public static final class Builder extends AbstractBuilder<OAuth2AuthorizationServerMetadata, Builder> {
private Builder() {
}

8
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenIntrospection.java

@ -88,13 +88,13 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC @@ -88,13 +88,13 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
*/
public static Builder withClaims(Map<String, Object> claims) {
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}.
*/
public static class Builder {
public static final class Builder {
private final Map<String, Object> claims = new LinkedHashMap<>();
@ -312,7 +312,7 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC @@ -312,7 +312,7 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
private void addClaimToClaimList(String name, String value) {
Assert.hasText(name, "name cannot be empty");
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);
}
@ -320,7 +320,7 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC @@ -320,7 +320,7 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
Assert.hasText(name, "name cannot be empty");
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);
valuesConsumer.accept(values);
}

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenType.java

@ -32,8 +32,14 @@ public final class OAuth2TokenType implements Serializable { @@ -32,8 +32,14 @@ public final class OAuth2TokenType implements Serializable {
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
/**
* {@code access_token} token type.
*/
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");
private final String value;

10
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/aot/hint/OAuth2AuthorizationServerBeanRegistrationAotProcessor.java

@ -71,10 +71,10 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis @@ -71,10 +71,10 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis
// @formatter:off
if ((beanClassName.equals("org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService") ||
beanClassName.equals("org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository")) &&
!jackson2Contributed) {
!this.jackson2Contributed) {
Jackson2ConfigurationBeanRegistrationAotContribution jackson2Contribution =
new Jackson2ConfigurationBeanRegistrationAotContribution();
jackson2Contributed = true;
this.jackson2Contributed = true;
return jackson2Contribution;
}
// @formatter:on
@ -117,7 +117,7 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis @@ -117,7 +117,7 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis
TypeReference.of(AuthorizationGrantType.class),
TypeReference.of(OAuth2AuthorizationResponseType.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));
// Jackson Modules - Spring Security and Spring Authorization Server
@ -126,7 +126,7 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis @@ -126,7 +126,7 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis
Arrays.asList(TypeReference.of(CoreJackson2Module.class),
TypeReference.of(WebServletJackson2Module.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));
// Jackson Mixins - Spring Security and Spring Authorization Server
@ -170,7 +170,7 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis @@ -170,7 +170,7 @@ class OAuth2AuthorizationServerBeanRegistrationAotProcessor implements BeanRegis
.of("org.springframework.security.oauth2.client.jackson2.OAuth2ClientJackson2Module"),
TypeReference
.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_METHODS));

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java

@ -128,7 +128,7 @@ public final class JwtClientAssertionAuthenticationProvider implements Authentic @@ -128,7 +128,7 @@ public final class JwtClientAssertionAuthenticationProvider implements Authentic
// @formatter:off
ClientAuthenticationMethod clientAuthenticationMethod =
registeredClient.getClientSettings().getTokenEndpointAuthenticationSigningAlgorithm() instanceof SignatureAlgorithm ?
(registeredClient.getClientSettings().getTokenEndpointAuthenticationSigningAlgorithm() instanceof SignatureAlgorithm) ?
ClientAuthenticationMethod.PRIVATE_KEY_JWT :
ClientAuthenticationMethod.CLIENT_SECRET_JWT;
// @formatter:on

8
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java

@ -62,8 +62,6 @@ import org.springframework.util.Assert; @@ -62,8 +62,6 @@ import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
/**
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Authorization Code
* Grant.
@ -118,8 +116,8 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth @@ -118,8 +116,8 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
authorizationCodeAuthentication);
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
.getAuthenticatedClientElseThrowInvalidClient(authorizationCodeAuthentication);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
if (this.logger.isTraceEnabled()) {
@ -169,7 +167,7 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth @@ -169,7 +167,7 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth
if (!authorizationCode.isActive()) {
if (authorizationCode.isInvalidated()) {
OAuth2Authorization.Token<? extends OAuth2Token> token = authorization.getRefreshToken() != null
OAuth2Authorization.Token<? extends OAuth2Token> token = (authorization.getRefreshToken() != null)
? authorization.getRefreshToken() : authorization.getAccessToken();
if (token != null) {
// Invalidate the access (and refresh) token as the client is

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java

@ -198,12 +198,12 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen @@ -198,12 +198,12 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationProvider implemen
.build();
if (this.logger.isTraceEnabled()) {
logger.trace("Generated authorization consent state");
this.logger.trace("Generated authorization consent state");
}
this.authorizationService.save(authorization);
Set<String> currentAuthorizedScopes = currentAuthorizationConsent != null
Set<String> currentAuthorizedScopes = (currentAuthorizationConsent != null)
? currentAuthorizationConsent.getScopes() : null;
if (this.logger.isTraceEnabled()) {

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationToken.java

@ -81,9 +81,9 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA @@ -81,9 +81,9 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
this.principal = principal;
this.redirectUri = redirectUri;
this.state = state;
this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet());
this.additionalParameters = Collections.unmodifiableMap(
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
this.authorizationCode = null;
}
@ -113,7 +113,7 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA @@ -113,7 +113,7 @@ public class OAuth2AuthorizationCodeRequestAuthenticationToken extends AbstractA
this.authorizationCode = authorizationCode;
this.redirectUri = redirectUri;
this.state = state;
this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet());
this.additionalParameters = Collections.emptyMap();
setAuthenticated(true);
}

10
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProvider.java

@ -154,7 +154,7 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A @@ -154,7 +154,7 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService
.findById(authorization.getRegisteredClientId(), authorization.getPrincipalName());
Set<String> currentAuthorizedScopes = currentAuthorizationConsent != null
Set<String> currentAuthorizedScopes = (currentAuthorizationConsent != null)
? currentAuthorizationConsent.getScopes() : Collections.emptySet();
if (!currentAuthorizedScopes.isEmpty()) {
@ -242,9 +242,7 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A @@ -242,9 +242,7 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
.authorizedScopes(authorizedScopes)
.token(authorizationCode)
.attributes(attrs -> {
attrs.remove(OAuth2ParameterNames.STATE);
})
.attributes((attrs) -> attrs.remove(OAuth2ParameterNames.STATE))
.build();
this.authorizationService.save(updatedAuthorization);
@ -353,9 +351,9 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A @@ -353,9 +351,9 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A
redirectUri = null; // Prevent redirects
}
String state = authorizationRequest != null ? authorizationRequest.getState()
String state = (authorizationRequest != null) ? authorizationRequest.getState()
: authorizationConsentAuthentication.getState();
Set<String> requestedScopes = authorizationRequest != null ? authorizationRequest.getScopes()
Set<String> requestedScopes = (authorizationRequest != null) ? authorizationRequest.getScopes()
: authorizationConsentAuthentication.getScopes();
OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken(

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationToken.java

@ -74,9 +74,9 @@ public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthe @@ -74,9 +74,9 @@ public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthe
this.clientId = clientId;
this.principal = principal;
this.state = state;
this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet());
this.additionalParameters = Collections.unmodifiableMap(
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
setAuthenticated(true);
}

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationGrantAuthenticationToken.java

@ -62,7 +62,7 @@ public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthent @@ -62,7 +62,7 @@ public class OAuth2AuthorizationGrantAuthenticationToken extends AbstractAuthent
this.authorizationGrantType = authorizationGrantType;
this.clientPrincipal = clientPrincipal;
this.additionalParameters = Collections.unmodifiableMap(
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
}
/**

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientAuthenticationToken.java

@ -73,7 +73,7 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken @@ -73,7 +73,7 @@ public class OAuth2ClientAuthenticationToken extends AbstractAuthenticationToken
this.clientAuthenticationMethod = clientAuthenticationMethod;
this.credentials = credentials;
this.additionalParameters = Collections
.unmodifiableMap(additionalParameters != null ? additionalParameters : Collections.emptyMap());
.unmodifiableMap((additionalParameters != null) ? additionalParameters : Collections.emptyMap());
}
/**

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProvider.java

@ -42,8 +42,6 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke @@ -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.util.Assert;
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
/**
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Client Credentials
* Grant.
@ -93,8 +91,8 @@ public final class OAuth2ClientCredentialsAuthenticationProvider implements Auth @@ -93,8 +91,8 @@ public final class OAuth2ClientCredentialsAuthenticationProvider implements Auth
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication = (OAuth2ClientCredentialsAuthenticationToken) authentication;
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
clientCredentialsAuthentication);
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
.getAuthenticatedClientElseThrowInvalidClient(clientCredentialsAuthentication);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
if (this.logger.isTraceEnabled()) {

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationToken.java

@ -47,7 +47,7 @@ public class OAuth2ClientCredentialsAuthenticationToken extends OAuth2Authorizat @@ -47,7 +47,7 @@ public class OAuth2ClientCredentialsAuthenticationToken extends OAuth2Authorizat
public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal, @Nullable Set<String> scopes,
@Nullable Map<String, Object> 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());
}
/**

20
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProvider.java

@ -133,7 +133,7 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem @@ -133,7 +133,7 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService
.findById(authorization.getRegisteredClientId(), principal.getName());
Set<String> currentAuthorizedScopes = currentAuthorizationConsent != null
Set<String> currentAuthorizedScopes = (currentAuthorizationConsent != null)
? currentAuthorizationConsent.getScopes() : Collections.emptySet();
if (!currentAuthorizedScopes.isEmpty()) {
@ -187,11 +187,11 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem @@ -187,11 +187,11 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
}
}
authorization = OAuth2Authorization.from(authorization)
.token(deviceCodeToken.getToken(),
metadata -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
.token(userCodeToken.getToken(),
metadata -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
.attributes(attrs -> attrs.remove(OAuth2ParameterNames.STATE))
.token((deviceCodeToken.getToken()),
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
.token((userCodeToken.getToken()),
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
.attributes((attrs) -> attrs.remove(OAuth2ParameterNames.STATE))
.build();
this.authorizationService.save(authorization);
if (this.logger.isTraceEnabled()) {
@ -210,10 +210,10 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem @@ -210,10 +210,10 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem
authorization = OAuth2Authorization.from(authorization)
.authorizedScopes(authorizedScopes)
.token(userCodeToken.getToken(),
metadata -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
.attributes(attrs -> attrs.remove(OAuth2ParameterNames.STATE))
.attributes(attrs -> attrs.remove(OAuth2ParameterNames.SCOPE))
.token((userCodeToken.getToken()),
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
.attributes((attrs) -> attrs.remove(OAuth2ParameterNames.STATE))
.attributes((attrs) -> attrs.remove(OAuth2ParameterNames.SCOPE))
.build();
this.authorizationService.save(authorization);

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationToken.java

@ -82,7 +82,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationToken extends OAuth2A @@ -82,7 +82,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationToken extends OAuth2A
Assert.hasText(userCode, "userCode cannot be empty");
this.userCode = userCode;
this.requestedScopes = Collections
.unmodifiableSet(requestedScopes != null ? new HashSet<>(requestedScopes) : Collections.emptySet());
.unmodifiableSet((requestedScopes != null) ? new HashSet<>(requestedScopes) : Collections.emptySet());
setAuthenticated(true);
}

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProvider.java

@ -50,8 +50,6 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke @@ -50,8 +50,6 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke
import org.springframework.util.Assert;
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
* used in the OAuth 2.0 Device Authorization Grant.
@ -98,8 +96,8 @@ public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implem @@ -98,8 +96,8 @@ public final class OAuth2DeviceAuthorizationRequestAuthenticationProvider implem
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2DeviceAuthorizationRequestAuthenticationToken deviceAuthorizationRequestAuthentication = (OAuth2DeviceAuthorizationRequestAuthenticationToken) authentication;
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
deviceAuthorizationRequestAuthentication);
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
.getAuthenticatedClientElseThrowInvalidClient(deviceAuthorizationRequestAuthentication);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
if (this.logger.isTraceEnabled()) {

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationToken.java

@ -70,9 +70,9 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac @@ -70,9 +70,9 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac
Assert.hasText(authorizationUri, "authorizationUri cannot be empty");
this.clientPrincipal = clientPrincipal;
this.authorizationUri = authorizationUri;
this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet());
this.additionalParameters = Collections.unmodifiableMap(
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
this.deviceCode = null;
this.userCode = null;
}
@ -92,7 +92,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac @@ -92,7 +92,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationToken extends Abstrac
Assert.notNull(deviceCode, "deviceCode cannot be null");
Assert.notNull(userCode, "userCode cannot be null");
this.clientPrincipal = clientPrincipal;
this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet());
this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet());
this.deviceCode = deviceCode;
this.userCode = userCode;
this.authorizationUri = null;

8
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProvider.java

@ -44,8 +44,6 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke @@ -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.util.Assert;
import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthenticationProviderUtils.getAuthenticatedClientElseThrowInvalidClient;
/**
* An {@link AuthenticationProvider} implementation for the Device Access Token Request
* used in the OAuth 2.0 Device Authorization Grant.
@ -101,8 +99,8 @@ public final class OAuth2DeviceCodeAuthenticationProvider implements Authenticat @@ -101,8 +99,8 @@ public final class OAuth2DeviceCodeAuthenticationProvider implements Authenticat
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2DeviceCodeAuthenticationToken deviceCodeAuthentication = (OAuth2DeviceCodeAuthenticationToken) authentication;
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
deviceCodeAuthentication);
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
.getAuthenticatedClientElseThrowInvalidClient(deviceCodeAuthentication);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
if (this.logger.isTraceEnabled()) {
@ -202,7 +200,7 @@ public final class OAuth2DeviceCodeAuthenticationProvider implements Authenticat @@ -202,7 +200,7 @@ public final class OAuth2DeviceCodeAuthenticationProvider implements Authenticat
// @formatter:off
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.from(authorization)
// 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));
// @formatter:on

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProvider.java

@ -149,7 +149,7 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut @@ -149,7 +149,7 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut
this.logger.trace("Saved authorization");
}
Set<String> currentAuthorizedScopes = currentAuthorizationConsent != null
Set<String> currentAuthorizedScopes = (currentAuthorizationConsent != null)
? currentAuthorizationConsent.getScopes() : null;
AuthorizationServerSettings authorizationServerSettings = AuthorizationServerContextHolder.getContext()
@ -166,10 +166,10 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut @@ -166,10 +166,10 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut
authorization = OAuth2Authorization.from(authorization)
.principalName(principal.getName())
.authorizedScopes(requestedScopes)
.token(userCode.getToken(), metadata -> metadata
.token(userCode.getToken(), (metadata) -> metadata
.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
.attribute(Principal.class.getName(), principal)
.attributes(attributes -> attributes.remove(OAuth2ParameterNames.SCOPE))
.attributes((attributes) -> attributes.remove(OAuth2ParameterNames.SCOPE))
.build();
// @formatter:on
this.authorizationService.save(authorization);

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationToken.java

@ -61,7 +61,7 @@ public class OAuth2DeviceVerificationAuthenticationToken extends AbstractAuthent @@ -61,7 +61,7 @@ public class OAuth2DeviceVerificationAuthenticationToken extends AbstractAuthent
this.principal = principal;
this.userCode = userCode;
this.additionalParameters = Collections.unmodifiableMap(
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
this.clientId = null;
}

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProvider.java

@ -49,8 +49,6 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke @@ -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.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.
*
@ -100,8 +98,8 @@ public final class OAuth2RefreshTokenAuthenticationProvider implements Authentic @@ -100,8 +98,8 @@ public final class OAuth2RefreshTokenAuthenticationProvider implements Authentic
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2RefreshTokenAuthenticationToken refreshTokenAuthentication = (OAuth2RefreshTokenAuthenticationToken) authentication;
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
refreshTokenAuthentication);
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
.getAuthenticatedClientElseThrowInvalidClient(refreshTokenAuthentication);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
if (this.logger.isTraceEnabled()) {

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationToken.java

@ -52,7 +52,7 @@ public class OAuth2RefreshTokenAuthenticationToken extends OAuth2AuthorizationGr @@ -52,7 +52,7 @@ public class OAuth2RefreshTokenAuthenticationToken extends OAuth2AuthorizationGr
super(AuthorizationGrantType.REFRESH_TOKEN, clientPrincipal, additionalParameters);
Assert.hasText(refreshToken, "refreshToken cannot be empty");
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());
}
/**

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProvider.java

@ -39,8 +39,6 @@ import org.springframework.security.oauth2.server.authorization.client.Registere @@ -39,8 +39,6 @@ import org.springframework.security.oauth2.server.authorization.client.Registere
import org.springframework.util.Assert;
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.
*
@ -84,8 +82,8 @@ public final class OAuth2TokenIntrospectionAuthenticationProvider implements Aut @@ -84,8 +82,8 @@ public final class OAuth2TokenIntrospectionAuthenticationProvider implements Aut
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2TokenIntrospectionAuthenticationToken tokenIntrospectionAuthentication = (OAuth2TokenIntrospectionAuthenticationToken) authentication;
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
tokenIntrospectionAuthentication);
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
.getAuthenticatedClientElseThrowInvalidClient(tokenIntrospectionAuthentication);
OAuth2Authorization authorization = this.authorizationService
.findByToken(tokenIntrospectionAuthentication.getToken(), null);

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationToken.java

@ -67,7 +67,7 @@ public class OAuth2TokenIntrospectionAuthenticationToken extends AbstractAuthent @@ -67,7 +67,7 @@ public class OAuth2TokenIntrospectionAuthenticationToken extends AbstractAuthent
this.clientPrincipal = clientPrincipal;
this.tokenTypeHint = tokenTypeHint;
this.additionalParameters = Collections.unmodifiableMap(
additionalParameters != null ? new HashMap<>(additionalParameters) : Collections.emptyMap());
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
this.tokenClaims = OAuth2TokenIntrospection.builder().build();
}

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProvider.java

@ -29,8 +29,6 @@ import org.springframework.security.oauth2.server.authorization.OAuth2Authorizat @@ -29,8 +29,6 @@ import org.springframework.security.oauth2.server.authorization.OAuth2Authorizat
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
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.
*
@ -62,8 +60,8 @@ public final class OAuth2TokenRevocationAuthenticationProvider implements Authen @@ -62,8 +60,8 @@ public final class OAuth2TokenRevocationAuthenticationProvider implements Authen
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication = (OAuth2TokenRevocationAuthenticationToken) authentication;
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(
tokenRevocationAuthentication);
OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
.getAuthenticatedClientElseThrowInvalidClient(tokenRevocationAuthentication);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
OAuth2Authorization authorization = this.authorizationService

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/InMemoryRegisteredClientRepository.java

@ -34,9 +34,9 @@ import org.springframework.util.StringUtils; @@ -34,9 +34,9 @@ import org.springframework.util.StringUtils;
* @author Anoop Garlapati
* @author Ovidiu Popa
* @author Joe Grandja
* @since 0.0.1
* @see RegisteredClientRepository
* @see RegisteredClient
* @since 0.0.1
*/
public final class InMemoryRegisteredClientRepository implements RegisteredClientRepository {
@ -98,7 +98,7 @@ public final class InMemoryRegisteredClientRepository implements RegisteredClien @@ -98,7 +98,7 @@ public final class InMemoryRegisteredClientRepository implements RegisteredClien
private void assertUniqueIdentifiers(RegisteredClient registeredClient,
Map<String, RegisteredClient> registrations) {
registrations.values().forEach(registration -> {
registrations.values().forEach((registration) -> {
if (registeredClient.getId().equals(registration.getId())) {
throw new IllegalArgumentException("Registered client must be unique. " + "Found duplicate identifier: "
+ registeredClient.getId());

38
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java

@ -82,17 +82,6 @@ import org.springframework.util.StringUtils; @@ -82,17 +82,6 @@ import org.springframework.util.StringUtils;
@ImportRuntimeHints(JdbcRegisteredClientRepository.JdbcRegisteredClientRepositoryRuntimeHintsRegistrar.class)
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
private static final String COLUMN_NAMES = "id, "
+ "client_id, "
@ -279,15 +268,15 @@ public class JdbcRegisteredClientRepository implements RegisteredClientRepositor @@ -279,15 +268,15 @@ public class JdbcRegisteredClientRepository implements RegisteredClientRepositor
// @formatter:off
RegisteredClient.Builder builder = RegisteredClient.withId(rs.getString("id"))
.clientId(rs.getString("client_id"))
.clientIdIssuedAt(clientIdIssuedAt != null ? clientIdIssuedAt.toInstant() : null)
.clientIdIssuedAt((clientIdIssuedAt != null) ? clientIdIssuedAt.toInstant() : null)
.clientSecret(rs.getString("client_secret"))
.clientSecretExpiresAt(clientSecretExpiresAt != null ? clientSecretExpiresAt.toInstant() : null)
.clientSecretExpiresAt((clientSecretExpiresAt != null) ? clientSecretExpiresAt.toInstant() : null)
.clientName(rs.getString("client_name"))
.clientAuthenticationMethods((authenticationMethods) ->
clientAuthenticationMethods.forEach(authenticationMethod ->
clientAuthenticationMethods.forEach((authenticationMethod) ->
authenticationMethods.add(resolveClientAuthenticationMethod(authenticationMethod))))
.authorizationGrantTypes((grantTypes) ->
authorizationGrantTypes.forEach(grantType ->
authorizationGrantTypes.forEach((grantType) ->
grantTypes.add(resolveAuthorizationGrantType(grantType))))
.redirectUris((uris) -> uris.addAll(redirectUris))
.postLogoutRedirectUris((uris) -> uris.addAll(postLogoutRedirectUris))
@ -374,22 +363,22 @@ public class JdbcRegisteredClientRepository implements RegisteredClientRepositor @@ -374,22 +363,22 @@ public class JdbcRegisteredClientRepository implements RegisteredClientRepositor
@Override
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 clientSecretExpiresAt = registeredClient.getClientSecretExpiresAt() != null
Timestamp clientSecretExpiresAt = (registeredClient.getClientSecretExpiresAt() != null)
? Timestamp.from(registeredClient.getClientSecretExpiresAt()) : null;
List<String> clientAuthenticationMethods = new ArrayList<>(
registeredClient.getClientAuthenticationMethods().size());
registeredClient.getClientAuthenticationMethods()
.forEach(clientAuthenticationMethod -> clientAuthenticationMethods
.forEach((clientAuthenticationMethod) -> clientAuthenticationMethods
.add(clientAuthenticationMethod.getValue()));
List<String> authorizationGrantTypes = new ArrayList<>(
registeredClient.getAuthorizationGrantTypes().size());
registeredClient.getAuthorizationGrantTypes()
.forEach(authorizationGrantType -> authorizationGrantTypes.add(authorizationGrantType.getValue()));
.forEach((authorizationGrantType) -> authorizationGrantTypes.add(authorizationGrantType.getValue()));
return Arrays.asList(new SqlParameterValue(Types.VARCHAR, registeredClient.getId()),
new SqlParameterValue(Types.VARCHAR, registeredClient.getClientId()),
@ -431,4 +420,15 @@ public class JdbcRegisteredClientRepository implements RegisteredClientRepositor @@ -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"));
}
}
}

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClient.java

@ -40,9 +40,9 @@ import org.springframework.util.StringUtils; @@ -40,9 +40,9 @@ import org.springframework.util.StringUtils;
*
* @author Joe Grandja
* @author Anoop Garlapati
* @since 0.0.1
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-2">Section 2
* Client Registration</a>
* @since 0.0.1
*/
public class RegisteredClient implements Serializable {
@ -594,7 +594,7 @@ public class RegisteredClient implements Serializable { @@ -594,7 +594,7 @@ public class RegisteredClient implements Serializable {
private static boolean validateScope(String scope) {
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));
}

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientRepository.java

@ -23,8 +23,8 @@ import org.springframework.lang.Nullable; @@ -23,8 +23,8 @@ import org.springframework.lang.Nullable;
* @author Joe Grandja
* @author Anoop Garlapati
* @author Ovidiu Popa
* @see RegisteredClient
* @since 0.0.1
* @see RegisteredClient
*/
public interface RegisteredClientRepository {

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/OAuth2AuthorizationServerConfiguration.java

@ -64,10 +64,10 @@ public class OAuth2AuthorizationServerConfiguration { @@ -64,10 +64,10 @@ public class OAuth2AuthorizationServerConfiguration {
http
.securityMatcher(endpointsMatcher)
.authorizeHttpRequests(authorize ->
.authorizeHttpRequests((authorize) ->
authorize.anyRequest().authenticated()
)
.csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher))
.csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher))
.apply(authorizationServerConfigurer);
}
// @formatter:on

5
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationEndpointConfigurer.java

@ -88,6 +88,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C @@ -88,6 +88,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OAuth2AuthorizationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -225,7 +226,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C @@ -225,7 +226,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C
void addAuthorizationCodeRequestAuthenticationValidator(
Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> authenticationValidator) {
this.authorizationCodeRequestAuthenticationValidator = this.authorizationCodeRequestAuthenticationValidator == null
this.authorizationCodeRequestAuthenticationValidator = (this.authorizationCodeRequestAuthenticationValidator == null)
? authenticationValidator
: this.authorizationCodeRequestAuthenticationValidator.andThen(authenticationValidator);
}
@ -251,7 +252,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C @@ -251,7 +252,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C
}
this.authenticationProvidersConsumer.accept(authenticationProviders);
authenticationProviders.forEach(
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
}
@Override

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerConfigurer.java

@ -322,7 +322,7 @@ public final class OAuth2AuthorizationServerConfigurer @@ -322,7 +322,7 @@ public final class OAuth2AuthorizationServerConfigurer
}
List<RequestMatcher> requestMatchers = new ArrayList<>();
this.configurers.values().forEach(configurer -> {
this.configurers.values().forEach((configurer) -> {
configurer.init(httpSecurity);
requestMatchers.add(configurer.getRequestMatcher());
});
@ -345,7 +345,7 @@ public final class OAuth2AuthorizationServerConfigurer @@ -345,7 +345,7 @@ public final class OAuth2AuthorizationServerConfigurer
@Override
public void configure(HttpSecurity httpSecurity) {
this.configurers.values().forEach(configurer -> configurer.configure(httpSecurity));
this.configurers.values().forEach((configurer) -> configurer.configure(httpSecurity));
AuthorizationServerSettings authorizationServerSettings = OAuth2ConfigurerUtils
.getAuthorizationServerSettings(httpSecurity);
@ -401,7 +401,7 @@ public final class OAuth2AuthorizationServerConfigurer @@ -401,7 +401,7 @@ public final class OAuth2AuthorizationServerConfigurer
private <T extends AbstractOAuth2Configurer> RequestMatcher getRequestMatcher(Class<T> configurerType) {
T configurer = getConfigurer(configurerType);
return configurer != null ? configurer.getRequestMatcher() : null;
return (configurer != null) ? configurer.getRequestMatcher() : null;
}
private static void validateAuthorizationServerSettings(AuthorizationServerSettings authorizationServerSettings) {

9
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataEndpointConfigurer.java

@ -45,6 +45,7 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A @@ -45,6 +45,7 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OAuth2AuthorizationServerMetadataEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -67,7 +68,7 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A @@ -67,7 +68,7 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A
void addDefaultAuthorizationServerMetadataCustomizer(
Consumer<OAuth2AuthorizationServerMetadata.Builder> defaultAuthorizationServerMetadataCustomizer) {
this.defaultAuthorizationServerMetadataCustomizer = this.defaultAuthorizationServerMetadataCustomizer == null
this.defaultAuthorizationServerMetadataCustomizer = (this.defaultAuthorizationServerMetadataCustomizer == null)
? defaultAuthorizationServerMetadataCustomizer : this.defaultAuthorizationServerMetadataCustomizer
.andThen(defaultAuthorizationServerMetadataCustomizer);
}
@ -101,9 +102,9 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A @@ -101,9 +102,9 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A
authorizationServerMetadataCustomizer = this.defaultAuthorizationServerMetadataCustomizer;
}
if (this.authorizationServerMetadataCustomizer != null) {
authorizationServerMetadataCustomizer = authorizationServerMetadataCustomizer == null
? this.authorizationServerMetadataCustomizer
: authorizationServerMetadataCustomizer.andThen(this.authorizationServerMetadataCustomizer);
authorizationServerMetadataCustomizer = (authorizationServerMetadataCustomizer != null)
? authorizationServerMetadataCustomizer.andThen(this.authorizationServerMetadataCustomizer)
: this.authorizationServerMetadataCustomizer;
}
}
return authorizationServerMetadataCustomizer;

3
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientAuthenticationConfigurer.java

@ -83,6 +83,7 @@ public final class OAuth2ClientAuthenticationConfigurer extends AbstractOAuth2Co @@ -83,6 +83,7 @@ public final class OAuth2ClientAuthenticationConfigurer extends AbstractOAuth2Co
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OAuth2ClientAuthenticationConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -204,7 +205,7 @@ public final class OAuth2ClientAuthenticationConfigurer extends AbstractOAuth2Co @@ -204,7 +205,7 @@ public final class OAuth2ClientAuthenticationConfigurer extends AbstractOAuth2Co
}
this.authenticationProvidersConsumer.accept(authenticationProviders);
authenticationProviders.forEach(
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
}
@Override

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ConfigurerUtils.java

@ -240,7 +240,7 @@ final class OAuth2ConfigurerUtils { @@ -240,7 +240,7 @@ final class OAuth2ConfigurerUtils {
if (names.length > 1) {
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;
}
}

3
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceAuthorizationEndpointConfigurer.java

@ -78,6 +78,7 @@ public final class OAuth2DeviceAuthorizationEndpointConfigurer extends AbstractO @@ -78,6 +78,7 @@ public final class OAuth2DeviceAuthorizationEndpointConfigurer extends AbstractO
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OAuth2DeviceAuthorizationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -210,7 +211,7 @@ public final class OAuth2DeviceAuthorizationEndpointConfigurer extends AbstractO @@ -210,7 +211,7 @@ public final class OAuth2DeviceAuthorizationEndpointConfigurer extends AbstractO
}
this.authenticationProvidersConsumer.accept(authenticationProviders);
authenticationProviders
.forEach(authenticationProvider -> builder.authenticationProvider(postProcess(authenticationProvider)));
.forEach((authenticationProvider) -> builder.authenticationProvider(postProcess(authenticationProvider)));
}
@Override

3
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceVerificationEndpointConfigurer.java

@ -83,6 +83,7 @@ public final class OAuth2DeviceVerificationEndpointConfigurer extends AbstractOA @@ -83,6 +83,7 @@ public final class OAuth2DeviceVerificationEndpointConfigurer extends AbstractOA
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OAuth2DeviceVerificationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -247,7 +248,7 @@ public final class OAuth2DeviceVerificationEndpointConfigurer extends AbstractOA @@ -247,7 +248,7 @@ public final class OAuth2DeviceVerificationEndpointConfigurer extends AbstractOA
}
this.authenticationProvidersConsumer.accept(authenticationProviders);
authenticationProviders
.forEach(authenticationProvider -> builder.authenticationProvider(postProcess(authenticationProvider)));
.forEach((authenticationProvider) -> builder.authenticationProvider(postProcess(authenticationProvider)));
}
@Override

3
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenEndpointConfigurer.java

@ -87,6 +87,7 @@ public final class OAuth2TokenEndpointConfigurer extends AbstractOAuth2Configure @@ -87,6 +87,7 @@ public final class OAuth2TokenEndpointConfigurer extends AbstractOAuth2Configure
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OAuth2TokenEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -198,7 +199,7 @@ public final class OAuth2TokenEndpointConfigurer extends AbstractOAuth2Configure @@ -198,7 +199,7 @@ public final class OAuth2TokenEndpointConfigurer extends AbstractOAuth2Configure
}
this.authenticationProvidersConsumer.accept(authenticationProviders);
authenticationProviders.forEach(
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
}
@Override

3
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionEndpointConfigurer.java

@ -75,6 +75,7 @@ public final class OAuth2TokenIntrospectionEndpointConfigurer extends AbstractOA @@ -75,6 +75,7 @@ public final class OAuth2TokenIntrospectionEndpointConfigurer extends AbstractOA
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OAuth2TokenIntrospectionEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -193,7 +194,7 @@ public final class OAuth2TokenIntrospectionEndpointConfigurer extends AbstractOA @@ -193,7 +194,7 @@ public final class OAuth2TokenIntrospectionEndpointConfigurer extends AbstractOA
}
this.authenticationProvidersConsumer.accept(authenticationProviders);
authenticationProviders.forEach(
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
}
@Override

3
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationEndpointConfigurer.java

@ -74,6 +74,7 @@ public final class OAuth2TokenRevocationEndpointConfigurer extends AbstractOAuth @@ -74,6 +74,7 @@ public final class OAuth2TokenRevocationEndpointConfigurer extends AbstractOAuth
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OAuth2TokenRevocationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -192,7 +193,7 @@ public final class OAuth2TokenRevocationEndpointConfigurer extends AbstractOAuth @@ -192,7 +193,7 @@ public final class OAuth2TokenRevocationEndpointConfigurer extends AbstractOAuth
}
this.authenticationProvidersConsumer.accept(authenticationProviders);
authenticationProviders.forEach(
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
}
@Override

3
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationEndpointConfigurer.java

@ -78,6 +78,7 @@ public final class OidcClientRegistrationEndpointConfigurer extends AbstractOAut @@ -78,6 +78,7 @@ public final class OidcClientRegistrationEndpointConfigurer extends AbstractOAut
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OidcClientRegistrationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -205,7 +206,7 @@ public final class OidcClientRegistrationEndpointConfigurer extends AbstractOAut @@ -205,7 +206,7 @@ public final class OidcClientRegistrationEndpointConfigurer extends AbstractOAut
}
this.authenticationProvidersConsumer.accept(authenticationProviders);
authenticationProviders.forEach(
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
}
@Override

5
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcConfigurer.java

@ -49,6 +49,7 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer { @@ -49,6 +49,7 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer {
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OidcConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -117,7 +118,7 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer { @@ -117,7 +118,7 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer {
@Override
void init(HttpSecurity httpSecurity) {
List<RequestMatcher> requestMatchers = new ArrayList<>();
this.configurers.values().forEach(configurer -> {
this.configurers.values().forEach((configurer) -> {
configurer.init(httpSecurity);
requestMatchers.add(configurer.getRequestMatcher());
});
@ -147,7 +148,7 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer { @@ -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

3
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcLogoutEndpointConfigurer.java

@ -74,6 +74,7 @@ public final class OidcLogoutEndpointConfigurer extends AbstractOAuth2Configurer @@ -74,6 +74,7 @@ public final class OidcLogoutEndpointConfigurer extends AbstractOAuth2Configurer
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OidcLogoutEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -179,7 +180,7 @@ public final class OidcLogoutEndpointConfigurer extends AbstractOAuth2Configurer @@ -179,7 +180,7 @@ public final class OidcLogoutEndpointConfigurer extends AbstractOAuth2Configurer
}
this.authenticationProvidersConsumer.accept(authenticationProviders);
authenticationProviders.forEach(
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
}
@Override

9
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationEndpointConfigurer.java

@ -45,6 +45,7 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO @@ -45,6 +45,7 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OidcProviderConfigurationEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -67,7 +68,7 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO @@ -67,7 +68,7 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO
void addDefaultProviderConfigurationCustomizer(
Consumer<OidcProviderConfiguration.Builder> defaultProviderConfigurationCustomizer) {
this.defaultProviderConfigurationCustomizer = this.defaultProviderConfigurationCustomizer == null
this.defaultProviderConfigurationCustomizer = (this.defaultProviderConfigurationCustomizer == null)
? defaultProviderConfigurationCustomizer
: this.defaultProviderConfigurationCustomizer.andThen(defaultProviderConfigurationCustomizer);
}
@ -99,9 +100,9 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO @@ -99,9 +100,9 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO
providerConfigurationCustomizer = this.defaultProviderConfigurationCustomizer;
}
if (this.providerConfigurationCustomizer != null) {
providerConfigurationCustomizer = providerConfigurationCustomizer == null
? this.providerConfigurationCustomizer
: providerConfigurationCustomizer.andThen(this.providerConfigurationCustomizer);
providerConfigurationCustomizer = (providerConfigurationCustomizer != null)
? providerConfigurationCustomizer.andThen(this.providerConfigurationCustomizer)
: this.providerConfigurationCustomizer;
}
}
return providerConfigurationCustomizer;

3
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoEndpointConfigurer.java

@ -82,6 +82,7 @@ public final class OidcUserInfoEndpointConfigurer extends AbstractOAuth2Configur @@ -82,6 +82,7 @@ public final class OidcUserInfoEndpointConfigurer extends AbstractOAuth2Configur
/**
* Restrict for internal use only.
* @param objectPostProcessor an {@code ObjectPostProcessor}
*/
OidcUserInfoEndpointConfigurer(ObjectPostProcessor<Object> objectPostProcessor) {
super(objectPostProcessor);
@ -223,7 +224,7 @@ public final class OidcUserInfoEndpointConfigurer extends AbstractOAuth2Configur @@ -223,7 +224,7 @@ public final class OidcUserInfoEndpointConfigurer extends AbstractOAuth2Configur
}
this.authenticationProvidersConsumer.accept(authenticationProviders);
authenticationProviders.forEach(
authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
(authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider)));
}
@Override

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/http/converter/HttpMessageConverters.java

@ -26,7 +26,7 @@ import org.springframework.util.ClassUtils; @@ -26,7 +26,7 @@ import org.springframework.util.ClassUtils;
* Utility methods for {@link HttpMessageConverter}'s.
*
* @author Joe Grandja
* @author luamas
* @author l uamas
* @since 0.1.1
*/
final class HttpMessageConverters {

9
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistration.java

@ -85,16 +85,17 @@ public final class OidcClientRegistration implements OidcClientMetadataClaimAcce @@ -85,16 +85,17 @@ public final class OidcClientRegistration implements OidcClientMetadataClaimAcce
/**
* Constructs a new {@link Builder} with the provided claims.
* @param claims the claims to initialize the builder
* @return the {@link Builder}
*/
public static Builder withClaims(Map<String, Object> claims) {
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}.
*/
public static class Builder {
public static final class Builder {
private final Map<String, Object> claims = new LinkedHashMap<>();
@ -434,7 +435,7 @@ public final class OidcClientRegistration implements OidcClientMetadataClaimAcce @@ -434,7 +435,7 @@ public final class OidcClientRegistration implements OidcClientMetadataClaimAcce
private void addClaimToClaimList(String name, String value) {
Assert.hasText(name, "name cannot be empty");
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);
}
@ -442,7 +443,7 @@ public final class OidcClientRegistration implements OidcClientMetadataClaimAcce @@ -442,7 +443,7 @@ public final class OidcClientRegistration implements OidcClientMetadataClaimAcce
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
Assert.hasText(name, "name cannot be empty");
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);
valuesConsumer.accept(values);
}

9
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfiguration.java

@ -58,16 +58,17 @@ public final class OidcProviderConfiguration extends AbstractOAuth2Authorization @@ -58,16 +58,17 @@ public final class OidcProviderConfiguration extends AbstractOAuth2Authorization
/**
* Constructs a new {@link Builder} with the provided claims.
* @param claims the claims to initialize the builder
* @return the {@link Builder}
*/
public static Builder withClaims(Map<String, Object> claims) {
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}.
*/
public static class Builder extends AbstractBuilder<OidcProviderConfiguration, Builder> {
public static final class Builder extends AbstractBuilder<OidcProviderConfiguration, Builder> {
private Builder() {
}
@ -191,7 +192,7 @@ public final class OidcProviderConfiguration extends AbstractOAuth2Authorization @@ -191,7 +192,7 @@ public final class OidcProviderConfiguration extends AbstractOAuth2Authorization
private void addClaimToClaimList(String name, String value) {
Assert.hasText(name, "name cannot be empty");
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);
}
@ -199,7 +200,7 @@ public final class OidcProviderConfiguration extends AbstractOAuth2Authorization @@ -199,7 +200,7 @@ public final class OidcProviderConfiguration extends AbstractOAuth2Authorization
private void acceptClaimValues(String name, Consumer<List<String>> valuesConsumer) {
Assert.hasText(name, "name cannot be empty");
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);
valuesConsumer.accept(values);
}

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProvider.java

@ -217,7 +217,7 @@ public final class OidcUserInfoAuthenticationProvider implements AuthenticationP @@ -217,7 +217,7 @@ public final class OidcUserInfoAuthenticationProvider implements AuthenticationP
}
Map<String, Object> requestedClaims = new HashMap<>(claims);
requestedClaims.keySet().removeIf(claimName -> !scopeRequestedClaimNames.contains(claimName));
requestedClaims.keySet().removeIf((claimName) -> !scopeRequestedClaimNames.contains(claimName));
return requestedClaims;
}

25
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/converter/OidcClientRegistrationRegisteredClientConverter.java

@ -62,31 +62,35 @@ public final class OidcClientRegistrationRegisteredClientConverter @@ -62,31 +62,35 @@ public final class OidcClientRegistrationRegisteredClientConverter
builder
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
.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
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.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);
} else {
}
else {
builder
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.clientSecret(CLIENT_SECRET_GENERATOR.generateKey());
}
builder.redirectUris(redirectUris ->
builder.redirectUris((redirectUris) ->
redirectUris.addAll(clientRegistration.getRedirectUris()));
if (!CollectionUtils.isEmpty(clientRegistration.getPostLogoutRedirectUris())) {
builder.postLogoutRedirectUris(postLogoutRedirectUris ->
builder.postLogoutRedirectUris((postLogoutRedirectUris) ->
postLogoutRedirectUris.addAll(clientRegistration.getPostLogoutRedirectUris()));
}
if (!CollectionUtils.isEmpty(clientRegistration.getGrantTypes())) {
builder.authorizationGrantTypes(authorizationGrantTypes ->
clientRegistration.getGrantTypes().forEach(grantType ->
builder.authorizationGrantTypes((authorizationGrantTypes) ->
clientRegistration.getGrantTypes().forEach((grantType) ->
authorizationGrantTypes.add(new AuthorizationGrantType(grantType))));
} else {
}
else {
builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
}
if (CollectionUtils.isEmpty(clientRegistration.getResponseTypes()) ||
@ -95,7 +99,7 @@ public final class OidcClientRegistrationRegisteredClientConverter @@ -95,7 +99,7 @@ public final class OidcClientRegistrationRegisteredClientConverter
}
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
builder.scopes(scopes ->
builder.scopes((scopes) ->
scopes.addAll(clientRegistration.getScopes()));
}
@ -109,7 +113,8 @@ public final class OidcClientRegistrationRegisteredClientConverter @@ -109,7 +113,8 @@ public final class OidcClientRegistrationRegisteredClientConverter
macAlgorithm = MacAlgorithm.HS256;
}
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());
if (signatureAlgorithm == null) {
signatureAlgorithm = SignatureAlgorithm.RS256;

10
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/converter/RegisteredClientOidcClientRegistrationConverter.java

@ -49,16 +49,16 @@ public final class RegisteredClientOidcClientRegistrationConverter @@ -49,16 +49,16 @@ public final class RegisteredClientOidcClientRegistrationConverter
builder.clientSecret(registeredClient.getClientSecret());
}
builder.redirectUris(redirectUris ->
builder.redirectUris((redirectUris) ->
redirectUris.addAll(registeredClient.getRedirectUris()));
if (!CollectionUtils.isEmpty(registeredClient.getPostLogoutRedirectUris())) {
builder.postLogoutRedirectUris(postLogoutRedirectUris ->
builder.postLogoutRedirectUris((postLogoutRedirectUris) ->
postLogoutRedirectUris.addAll(registeredClient.getPostLogoutRedirectUris()));
}
builder.grantTypes(grantTypes ->
registeredClient.getAuthorizationGrantTypes().forEach(authorizationGrantType ->
builder.grantTypes((grantTypes) ->
registeredClient.getAuthorizationGrantTypes().forEach((authorizationGrantType) ->
grantTypes.add(authorizationGrantType.getValue())));
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.AUTHORIZATION_CODE)) {
@ -66,7 +66,7 @@ public final class RegisteredClientOidcClientRegistrationConverter @@ -66,7 +66,7 @@ public final class RegisteredClientOidcClientRegistrationConverter
}
if (!CollectionUtils.isEmpty(registeredClient.getScopes())) {
builder.scopes(scopes ->
builder.scopes((scopes) ->
scopes.addAll(registeredClient.getScopes()));
}

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/HttpMessageConverters.java

@ -26,7 +26,7 @@ import org.springframework.util.ClassUtils; @@ -26,7 +26,7 @@ import org.springframework.util.ClassUtils;
* Utility methods for {@link HttpMessageConverter}'s.
*
* @author Joe Grandja
* @author luamas
* @author l uamas
* @since 0.1.0
*/
final class HttpMessageConverters {

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverter.java

@ -184,7 +184,7 @@ public class OidcClientRegistrationHttpMessageConverter extends AbstractHttpMess @@ -184,7 +184,7 @@ public class OidcClientRegistrationHttpMessageConverter extends AbstractHttpMess
}
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) {

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilter.java

@ -123,7 +123,7 @@ public final class OidcClientRegistrationEndpointFilter extends OncePerRequestFi @@ -123,7 +123,7 @@ public final class OidcClientRegistrationEndpointFilter extends OncePerRequestFi
RequestMatcher clientConfigurationGetMatcher = new AntPathRequestMatcher(clientRegistrationEndpointUri,
HttpMethod.GET.name());
RequestMatcher clientIdMatcher = request -> {
RequestMatcher clientIdMatcher = (request) -> {
String clientId = request.getParameter(OAuth2ParameterNames.CLIENT_ID);
return StringUtils.hasText(clientId);
};
@ -190,7 +190,7 @@ public final class OidcClientRegistrationEndpointFilter extends OncePerRequestFi @@ -190,7 +190,7 @@ public final class OidcClientRegistrationEndpointFilter extends OncePerRequestFi
* {@link OidcClientRegistration Client Registration Response}.
* @param authenticationSuccessHandler the {@link AuthenticationSuccessHandler} used
* for handling an {@link OidcClientRegistrationAuthenticationToken}
* @see 0.4.0
* @since 0.4.0
*/
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) {
Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null");

5
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AbstractSettings.java

@ -86,8 +86,11 @@ public abstract class AbstractSettings implements Serializable { @@ -86,8 +86,11 @@ public abstract class AbstractSettings implements Serializable {
/**
* 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<>();

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettings.java

@ -178,13 +178,13 @@ public final class AuthorizationServerSettings extends AbstractSettings { @@ -178,13 +178,13 @@ public final class AuthorizationServerSettings extends AbstractSettings {
*/
public static Builder withSettings(Map<String, Object> settings) {
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}.
*/
public final static class Builder extends AbstractBuilder<AuthorizationServerSettings, Builder> {
public static final class Builder extends AbstractBuilder<AuthorizationServerSettings, Builder> {
private Builder() {
}

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettings.java

@ -107,13 +107,13 @@ public final class ClientSettings extends AbstractSettings { @@ -107,13 +107,13 @@ public final class ClientSettings extends AbstractSettings {
*/
public static Builder withSettings(Map<String, Object> settings) {
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}.
*/
public final static class Builder extends AbstractBuilder<ClientSettings, Builder> {
public static final class Builder extends AbstractBuilder<ClientSettings, Builder> {
private Builder() {
}

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettings.java

@ -76,6 +76,8 @@ public final class TokenSettings extends AbstractSettings { @@ -76,6 +76,8 @@ public final class TokenSettings extends AbstractSettings {
* 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
* {@code true}.
* @return {@code true} if refresh tokens are reused when returning the access token
* response, {@code false} otherwise
*/
public boolean isReuseRefreshTokens() {
return getSetting(ConfigurationSettingNames.Token.REUSE_REFRESH_TOKENS);
@ -135,13 +137,13 @@ public final class TokenSettings extends AbstractSettings { @@ -135,13 +137,13 @@ public final class TokenSettings extends AbstractSettings {
*/
public static Builder withSettings(Map<String, Object> settings) {
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}.
*/
public final static class Builder extends AbstractBuilder<TokenSettings, Builder> {
public static final class Builder extends AbstractBuilder<TokenSettings, Builder> {
private Builder() {
}

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/JwtGenerator.java

@ -124,7 +124,8 @@ public final class JwtGenerator implements OAuth2TokenGenerator<Jwt> { @@ -124,7 +124,8 @@ public final class JwtGenerator implements OAuth2TokenGenerator<Jwt> {
if (!CollectionUtils.isEmpty(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());
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(context.getAuthorizationGrantType())) {
OAuth2AuthorizationRequest authorizationRequest = context.getAuthorization().getAttribute(
@ -138,7 +139,8 @@ public final class JwtGenerator implements OAuth2TokenGenerator<Jwt> { @@ -138,7 +139,8 @@ public final class JwtGenerator implements OAuth2TokenGenerator<Jwt> {
claimsBuilder.claim("sid", sessionInformation.getSessionId());
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();
if (currentIdToken.hasClaim("sid")) {
claimsBuilder.claim("sid", currentIdToken.getClaim("sid"));

1
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSet.java

@ -156,6 +156,7 @@ public final class OAuth2TokenClaimsSet implements OAuth2TokenClaimAccessor { @@ -156,6 +156,7 @@ public final class OAuth2TokenClaimsSet implements OAuth2TokenClaimAccessor {
* A {@code Consumer} to be provided access to the claims allowing the ability to
* add, replace, or remove.
* @param claimsConsumer a {@code Consumer} of the claims
* @return the {@link Builder}
*/
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
claimsConsumer.accept(this.claims);

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenCustomizer.java

@ -19,10 +19,10 @@ package org.springframework.security.oauth2.server.authorization.token; @@ -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
* attributes contained within the {@link OAuth2TokenContext}.
*
* @param <T> the type of the context containing the OAuth 2.0 Token attributes
* @author Joe Grandja
* @since 0.1.0
* @see OAuth2TokenContext
* @param <T> the type of the context containing the OAuth 2.0 Token attributes
*/
@FunctionalInterface
public interface OAuth2TokenCustomizer<T extends OAuth2TokenContext> {

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenGenerator.java

@ -24,13 +24,13 @@ import org.springframework.security.oauth2.server.authorization.OAuth2Authorizat @@ -24,13 +24,13 @@ import org.springframework.security.oauth2.server.authorization.OAuth2Authorizat
* Implementations of this interface are responsible for generating an {@link OAuth2Token}
* using the attributes contained in the {@link OAuth2TokenContext}.
*
* @param <T> the type of the OAuth 2.0 Token
* @author Joe Grandja
* @since 0.2.3
* @see OAuth2Token
* @see OAuth2TokenContext
* @see OAuth2TokenClaimsSet
* @see ClaimAccessor
* @param <T> the type of the OAuth 2.0 Token
*/
@FunctionalInterface
public interface OAuth2TokenGenerator<T extends OAuth2Token> {

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/DefaultConsentPage.java

@ -31,8 +31,10 @@ import org.springframework.security.oauth2.core.oidc.OidcScopes; @@ -31,8 +31,10 @@ import org.springframework.security.oauth2.core.oidc.OidcScopes;
/**
* 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);

9
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilter.java

@ -18,16 +18,15 @@ package org.springframework.security.oauth2.server.authorization.web; @@ -18,16 +18,15 @@ package org.springframework.security.oauth2.server.authorization.web;
import java.io.IOException;
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.JWKSelector;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
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.MediaType;

6
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilter.java

@ -151,12 +151,12 @@ public final class OAuth2AuthorizationEndpointFilter extends OncePerRequestFilte @@ -151,12 +151,12 @@ public final class OAuth2AuthorizationEndpointFilter extends OncePerRequestFilte
HttpMethod.GET.name());
RequestMatcher authorizationRequestPostMatcher = new AntPathRequestMatcher(authorizationEndpointUri,
HttpMethod.POST.name());
RequestMatcher openidScopeMatcher = request -> {
RequestMatcher openidScopeMatcher = (request) -> {
String scope = request.getParameter(OAuth2ParameterNames.SCOPE);
return StringUtils.hasText(scope) && scope.contains(OidcScopes.OPENID);
};
RequestMatcher responseTypeParameterMatcher = request -> request
.getParameter(OAuth2ParameterNames.RESPONSE_TYPE) != null;
RequestMatcher responseTypeParameterMatcher = (
request) -> request.getParameter(OAuth2ParameterNames.RESPONSE_TYPE) != null;
RequestMatcher authorizationRequestMatcher = new OrRequestMatcher(authorizationRequestGetMatcher,
new AndRequestMatcher(authorizationRequestPostMatcher, responseTypeParameterMatcher,

4
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilter.java

@ -136,8 +136,8 @@ public final class OAuth2DeviceVerificationEndpointFilter extends OncePerRequest @@ -136,8 +136,8 @@ public final class OAuth2DeviceVerificationEndpointFilter extends OncePerRequest
HttpMethod.GET.name());
RequestMatcher verificationRequestPostMatcher = new AntPathRequestMatcher(deviceVerificationEndpointUri,
HttpMethod.POST.name());
RequestMatcher userCodeParameterMatcher = request -> request
.getParameter(OAuth2ParameterNames.USER_CODE) != null;
RequestMatcher userCodeParameterMatcher = (
request) -> request.getParameter(OAuth2ParameterNames.USER_CODE) != null;
return new AndRequestMatcher(
new OrRequestMatcher(verificationRequestGetMatcher, verificationRequestPostMatcher),

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilter.java

@ -51,12 +51,12 @@ import org.springframework.web.filter.OncePerRequestFilter; @@ -51,12 +51,12 @@ import org.springframework.web.filter.OncePerRequestFilter;
* @author Gerardo Roza
* @author Joe Grandja
* @author Gaurav Tiwari
* @since 0.1.1
* @see OAuth2TokenIntrospectionAuthenticationProvider
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7662#section-2">Section 2
* Introspection Endpoint</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7662#section-2.1">Section
* 2.1 Introspection Request</a>
* @since 0.1.1
*/
public final class OAuth2TokenIntrospectionEndpointFilter extends OncePerRequestFilter {

2
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilter.java

@ -48,12 +48,12 @@ import org.springframework.web.filter.OncePerRequestFilter; @@ -48,12 +48,12 @@ import org.springframework.web.filter.OncePerRequestFilter;
* @author Vivek Babu
* @author Joe Grandja
* @author Arfat Chaus
* @since 0.0.3
* @see OAuth2TokenRevocationAuthenticationProvider
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7009#section-2">Section 2
* Token Revocation</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7009#section-2.1">Section
* 2.1 Revocation Request</a>
* @since 0.0.3
*/
public final class OAuth2TokenRevocationEndpointFilter extends OncePerRequestFilter {

8
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2AuthorizationCodeRequestAuthenticationConverter.java

@ -145,10 +145,10 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationConverter impleme @@ -145,10 +145,10 @@ public final class OAuth2AuthorizationCodeRequestAuthenticationConverter impleme
}
private static RequestMatcher createOidcRequestMatcher() {
RequestMatcher postMethodMatcher = request -> "POST".equals(request.getMethod());
RequestMatcher responseTypeParameterMatcher = request -> request
.getParameter(OAuth2ParameterNames.RESPONSE_TYPE) != null;
RequestMatcher openidScopeMatcher = request -> {
RequestMatcher postMethodMatcher = (request) -> "POST".equals(request.getMethod());
RequestMatcher responseTypeParameterMatcher = (
request) -> request.getParameter(OAuth2ParameterNames.RESPONSE_TYPE) != null;
RequestMatcher openidScopeMatcher = (request) -> {
String scope = request.getParameter(OAuth2ParameterNames.SCOPE);
return StringUtils.hasText(scope) && scope.contains(OidcScopes.OPENID);
};

3
oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2ErrorAuthenticationFailureHandler.java

@ -20,7 +20,6 @@ import java.io.IOException; @@ -20,7 +20,6 @@ import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -40,9 +39,9 @@ import org.springframework.util.Assert; @@ -40,9 +39,9 @@ import org.springframework.util.Assert;
* Error Response}.
*
* @author Dmitriy Dubson
* @since 1.2
* @see AuthenticationFailureHandler
* @see OAuth2ErrorHttpMessageConverter
* @since 1.2
*/
public final class OAuth2ErrorAuthenticationFailureHandler implements AuthenticationFailureHandler {

36
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentServiceTests.java

@ -45,10 +45,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -45,10 +45,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link JdbcOAuth2AuthorizationConsentService}.
@ -150,7 +150,8 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { @@ -150,7 +150,8 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
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);
@ -164,7 +165,7 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { @@ -164,7 +165,7 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
OAuth2AuthorizationConsent expectedAuthorizationConsent = OAuth2AuthorizationConsent.from(AUTHORIZATION_CONSENT)
.authority(new SimpleGrantedAuthority("new.authority"))
.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);
@ -176,8 +177,7 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { @@ -176,8 +177,7 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
@Test
public void saveLoadAuthorizationConsentWhenCustomStrategiesSetThenCalled() throws Exception {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
JdbcOAuth2AuthorizationConsentService.OAuth2AuthorizationConsentRowMapper authorizationConsentRowMapper = spy(
new JdbcOAuth2AuthorizationConsentService.OAuth2AuthorizationConsentRowMapper(
@ -188,8 +188,8 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { @@ -188,8 +188,8 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
this.authorizationConsentService.setAuthorizationConsentParametersMapper(authorizationConsentParametersMapper);
this.authorizationConsentService.save(AUTHORIZATION_CONSENT);
OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService.findById(
AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService
.findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
assertThat(authorizationConsent).isEqualTo(AUTHORIZATION_CONSENT);
verify(authorizationConsentRowMapper).mapRow(any(), anyInt());
verify(authorizationConsentParametersMapper).apply(any());
@ -225,12 +225,11 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { @@ -225,12 +225,11 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
@Test
public void findByIdWhenAuthorizationConsentExistsThenFound() {
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(AUTHORIZATION_CONSENT);
OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService.findById(
AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService
.findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
assertThat(authorizationConsent).isNotNull();
}
@ -243,19 +242,18 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { @@ -243,19 +242,18 @@ public class JdbcOAuth2AuthorizationConsentServiceTests {
@Test
public void tableDefinitionWhenCustomThenAbleToOverride() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
EmbeddedDatabase db = createDb(CUSTOM_OAUTH2_AUTHORIZATION_CONSENT_SCHEMA_SQL_RESOURCE);
OAuth2AuthorizationConsentService authorizationConsentService =
new CustomJdbcOAuth2AuthorizationConsentService(new JdbcTemplate(db), this.registeredClientRepository);
OAuth2AuthorizationConsentService authorizationConsentService = new CustomJdbcOAuth2AuthorizationConsentService(
new JdbcTemplate(db), this.registeredClientRepository);
authorizationConsentService.save(AUTHORIZATION_CONSENT);
OAuth2AuthorizationConsent foundAuthorizationConsent1 = authorizationConsentService.findById(
AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
OAuth2AuthorizationConsent foundAuthorizationConsent1 = authorizationConsentService
.findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
assertThat(foundAuthorizationConsent1).isEqualTo(AUTHORIZATION_CONSENT);
authorizationConsentService.remove(AUTHORIZATION_CONSENT);
OAuth2AuthorizationConsent foundAuthorizationConsent2 = authorizationConsentService.findById(
AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
OAuth2AuthorizationConsent foundAuthorizationConsent2 = authorizationConsentService
.findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName());
assertThat(foundAuthorizationConsent2).isNull();
db.shutdown();
}

269
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationServiceTests.java

@ -63,10 +63,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -63,10 +63,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link JdbcOAuth2AuthorizationService}.
@ -182,14 +182,13 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -182,14 +182,13 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void saveWhenAuthorizationNewThenSaved() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
OAuth2Authorization expectedAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
this.authorizationService.save(expectedAuthorization);
OAuth2Authorization authorization = this.authorizationService.findById(ID);
@ -198,53 +197,47 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -198,53 +197,47 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void saveWhenAuthorizationExistsThenUpdated() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
this.authorizationService.save(originalAuthorization);
OAuth2Authorization authorization = this.authorizationService.findById(
originalAuthorization.getId());
OAuth2Authorization authorization = this.authorizationService.findById(originalAuthorization.getId());
assertThat(authorization).isEqualTo(originalAuthorization);
OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
.attribute("custom-name-1", "custom-value-1")
.build();
.attribute("custom-name-1", "custom-value-1")
.build();
this.authorizationService.save(updatedAuthorization);
authorization = this.authorizationService.findById(
updatedAuthorization.getId());
authorization = this.authorizationService.findById(updatedAuthorization.getId());
assertThat(authorization).isEqualTo(updatedAuthorization);
assertThat(authorization).isNotEqualTo(originalAuthorization);
}
@Test
public void saveLoadAuthorizationWhenCustomStrategiesSetThenCalled() throws Exception {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
RowMapper<OAuth2Authorization> authorizationRowMapper = spy(
new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper(
this.registeredClientRepository));
new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper(this.registeredClientRepository));
this.authorizationService.setAuthorizationRowMapper(authorizationRowMapper);
Function<OAuth2Authorization, List<SqlParameterValue>> authorizationParametersMapper = spy(
new JdbcOAuth2AuthorizationService.OAuth2AuthorizationParametersMapper());
this.authorizationService.setAuthorizationParametersMapper(authorizationParametersMapper);
this.authorizationService.save(originalAuthorization);
OAuth2Authorization authorization = this.authorizationService.findById(
originalAuthorization.getId());
OAuth2Authorization authorization = this.authorizationService.findById(originalAuthorization.getId());
assertThat(authorization).isEqualTo(originalAuthorization);
verify(authorizationRowMapper).mapRow(any(), anyInt());
verify(authorizationParametersMapper).apply(any());
@ -261,23 +254,22 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -261,23 +254,22 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void removeWhenAuthorizationProvidedThenRemoved() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
OAuth2Authorization expectedAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
this.authorizationService.save(expectedAuthorization);
OAuth2Authorization authorization = this.authorizationService.findByToken(
AUTHORIZATION_CODE.getTokenValue(), AUTHORIZATION_CODE_TOKEN_TYPE);
OAuth2Authorization authorization = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(),
AUTHORIZATION_CODE_TOKEN_TYPE);
assertThat(authorization).isEqualTo(expectedAuthorization);
this.authorizationService.remove(authorization);
authorization = this.authorizationService.findByToken(
AUTHORIZATION_CODE.getTokenValue(), AUTHORIZATION_CODE_TOKEN_TYPE);
authorization = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(),
AUTHORIZATION_CODE_TOKEN_TYPE);
assertThat(authorization).isNull();
}
@ -310,19 +302,17 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -310,19 +302,17 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void findByTokenWhenStateExistsThenFound() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
String state = "state";
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.attribute(OAuth2ParameterNames.STATE, state)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.attribute(OAuth2ParameterNames.STATE, state)
.build();
this.authorizationService.save(authorization);
OAuth2Authorization result = this.authorizationService.findByToken(
state, STATE_TOKEN_TYPE);
OAuth2Authorization result = this.authorizationService.findByToken(state, STATE_TOKEN_TYPE);
assertThat(authorization).isEqualTo(result);
result = this.authorizationService.findByToken(state, null);
assertThat(authorization).isEqualTo(result);
@ -330,18 +320,17 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -330,18 +320,17 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void findByTokenWhenAuthorizationCodeExistsThenFound() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
this.authorizationService.save(authorization);
OAuth2Authorization result = this.authorizationService.findByToken(
AUTHORIZATION_CODE.getTokenValue(), AUTHORIZATION_CODE_TOKEN_TYPE);
OAuth2Authorization result = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(),
AUTHORIZATION_CODE_TOKEN_TYPE);
assertThat(authorization).isEqualTo(result);
result = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(), null);
assertThat(authorization).isEqualTo(result);
@ -349,21 +338,21 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -349,21 +338,21 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void findByTokenWhenAccessTokenExistsThenFound() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token", Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS), Instant.now().truncatedTo(ChronoUnit.MILLIS));
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token",
Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS),
Instant.now().truncatedTo(ChronoUnit.MILLIS));
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.accessToken(accessToken)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.accessToken(accessToken)
.build();
this.authorizationService.save(authorization);
OAuth2Authorization result = this.authorizationService.findByToken(
accessToken.getTokenValue(), OAuth2TokenType.ACCESS_TOKEN);
OAuth2Authorization result = this.authorizationService.findByToken(accessToken.getTokenValue(),
OAuth2TokenType.ACCESS_TOKEN);
assertThat(authorization).isEqualTo(result);
result = this.authorizationService.findByToken(accessToken.getTokenValue(), null);
assertThat(authorization).isEqualTo(result);
@ -371,25 +360,24 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -371,25 +360,24 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void findByTokenWhenIdTokenExistsThenFound() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
OidcIdToken idToken = OidcIdToken.withTokenValue("id-token")
.issuer("https://provider.com")
.subject("subject")
.issuedAt(Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS))
.expiresAt(Instant.now().truncatedTo(ChronoUnit.MILLIS))
.build();
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
OidcIdToken idToken = OidcIdToken.withTokenValue("id-token")
.issuer("https://provider.com")
.subject("subject")
.issuedAt(Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS))
.expiresAt(Instant.now().truncatedTo(ChronoUnit.MILLIS))
.build();
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(idToken, (metadata) ->
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()))
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(idToken,
(metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims()))
.build();
this.authorizationService.save(authorization);
OAuth2Authorization result = this.authorizationService.findByToken(
idToken.getTokenValue(), ID_TOKEN_TOKEN_TYPE);
OAuth2Authorization result = this.authorizationService.findByToken(idToken.getTokenValue(),
ID_TOKEN_TOKEN_TYPE);
assertThat(authorization).isEqualTo(result);
result = this.authorizationService.findByToken(idToken.getTokenValue(), null);
assertThat(authorization).isEqualTo(result);
@ -397,21 +385,20 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -397,21 +385,20 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void findByTokenWhenRefreshTokenExistsThenFound() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token",
Instant.now().truncatedTo(ChronoUnit.MILLIS),
Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS));
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.refreshToken(refreshToken)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.refreshToken(refreshToken)
.build();
this.authorizationService.save(authorization);
OAuth2Authorization result = this.authorizationService.findByToken(
refreshToken.getTokenValue(), OAuth2TokenType.REFRESH_TOKEN);
OAuth2Authorization result = this.authorizationService.findByToken(refreshToken.getTokenValue(),
OAuth2TokenType.REFRESH_TOKEN);
assertThat(authorization).isEqualTo(result);
result = this.authorizationService.findByToken(refreshToken.getTokenValue(), null);
assertThat(authorization).isEqualTo(result);
@ -419,21 +406,19 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -419,21 +406,19 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void findByTokenWhenDeviceCodeExistsThenFound() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
OAuth2DeviceCode deviceCode = new OAuth2DeviceCode("device-code",
Instant.now().truncatedTo(ChronoUnit.MILLIS),
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
OAuth2DeviceCode deviceCode = new OAuth2DeviceCode("device-code", Instant.now().truncatedTo(ChronoUnit.MILLIS),
Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS));
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(deviceCode)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(deviceCode)
.build();
this.authorizationService.save(authorization);
OAuth2Authorization result = this.authorizationService.findByToken(
deviceCode.getTokenValue(), DEVICE_CODE_TOKEN_TYPE);
OAuth2Authorization result = this.authorizationService.findByToken(deviceCode.getTokenValue(),
DEVICE_CODE_TOKEN_TYPE);
assertThat(authorization).isEqualTo(result);
result = this.authorizationService.findByToken(deviceCode.getTokenValue(), null);
assertThat(authorization).isEqualTo(result);
@ -441,21 +426,19 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -441,21 +426,19 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void findByTokenWhenUserCodeExistsThenFound() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
OAuth2UserCode userCode = new OAuth2UserCode("user-code",
Instant.now().truncatedTo(ChronoUnit.MILLIS),
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
OAuth2UserCode userCode = new OAuth2UserCode("user-code", Instant.now().truncatedTo(ChronoUnit.MILLIS),
Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS));
OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(userCode)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(userCode)
.build();
this.authorizationService.save(authorization);
OAuth2Authorization result = this.authorizationService.findByToken(
userCode.getTokenValue(), USER_CODE_TOKEN_TYPE);
OAuth2Authorization result = this.authorizationService.findByToken(userCode.getTokenValue(),
USER_CODE_TOKEN_TYPE);
assertThat(authorization).isEqualTo(result);
result = this.authorizationService.findByToken(userCode.getTokenValue(), null);
assertThat(authorization).isEqualTo(result);
@ -487,20 +470,19 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -487,20 +470,19 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void tableDefinitionWhenCustomThenAbleToOverride() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
EmbeddedDatabase db = createDb(CUSTOM_OAUTH2_AUTHORIZATION_SCHEMA_SQL_RESOURCE);
OAuth2AuthorizationService authorizationService =
new CustomJdbcOAuth2AuthorizationService(new JdbcTemplate(db), this.registeredClientRepository);
OAuth2AuthorizationService authorizationService = new CustomJdbcOAuth2AuthorizationService(new JdbcTemplate(db),
this.registeredClientRepository);
String state = "state";
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.attribute(OAuth2ParameterNames.STATE, state)
.token(AUTHORIZATION_CODE)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.attribute(OAuth2ParameterNames.STATE, state)
.token(AUTHORIZATION_CODE)
.build();
authorizationService.save(originalAuthorization);
OAuth2Authorization foundAuthorization1 = authorizationService.findById(originalAuthorization.getId());
assertThat(foundAuthorization1).isEqualTo(originalAuthorization);
@ -511,31 +493,28 @@ public class JdbcOAuth2AuthorizationServiceTests { @@ -511,31 +493,28 @@ public class JdbcOAuth2AuthorizationServiceTests {
@Test
public void tableDefinitionWhenClobSqlTypeThenAuthorizationUpdated() {
when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId())))
.thenReturn(REGISTERED_CLIENT);
given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT);
EmbeddedDatabase db = createDb(OAUTH2_AUTHORIZATION_SCHEMA_CLOB_DATA_TYPE_SQL_RESOURCE);
OAuth2AuthorizationService authorizationService =
new JdbcOAuth2AuthorizationService(new JdbcTemplate(db), this.registeredClientRepository);
OAuth2AuthorizationService authorizationService = new JdbcOAuth2AuthorizationService(new JdbcTemplate(db),
this.registeredClientRepository);
OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT)
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
.id(ID)
.principalName(PRINCIPAL_NAME)
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE)
.token(AUTHORIZATION_CODE)
.build();
authorizationService.save(originalAuthorization);
OAuth2Authorization authorization = authorizationService.findById(
originalAuthorization.getId());
OAuth2Authorization authorization = authorizationService.findById(originalAuthorization.getId());
assertThat(authorization).isEqualTo(originalAuthorization);
OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization)
.attribute("custom-name-1", "custom-value-1")
.build();
.attribute("custom-name-1", "custom-value-1")
.build();
authorizationService.save(updatedAuthorization);
authorization = authorizationService.findById(
updatedAuthorization.getId());
authorization = authorizationService.findById(updatedAuthorization.getId());
assertThat(authorization).isEqualTo(updatedAuthorization);
assertThat(authorization).isNotEqualTo(originalAuthorization);
db.shutdown();

2
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java

@ -92,7 +92,7 @@ public class OAuth2AuthorizationConsentTests { @@ -92,7 +92,7 @@ public class OAuth2AuthorizationConsentTests {
public void authoritiesThenCustomizesAuthorities() {
OAuth2AuthorizationConsent authorizationConsent = OAuth2AuthorizationConsent.withId("some-client", "some-user")
.authority(new SimpleGrantedAuthority("some.authority"))
.authorities(authorities -> {
.authorities((authorities) -> {
authorities.clear();
authorities.add(new SimpleGrantedAuthority("other.authority"));
})

18
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataTests.java

@ -296,7 +296,7 @@ public class OAuth2AuthorizationServerMetadataTests { @@ -296,7 +296,7 @@ public class OAuth2AuthorizationServerMetadataTests {
public void buildWhenTokenEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() {
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
.tokenEndpointAuthenticationMethod("should-be-removed")
.tokenEndpointAuthenticationMethods(authMethods -> {
.tokenEndpointAuthenticationMethods((authMethods) -> {
authMethods.clear();
authMethods.add("some-authentication-method");
})
@ -334,7 +334,7 @@ public class OAuth2AuthorizationServerMetadataTests { @@ -334,7 +334,7 @@ public class OAuth2AuthorizationServerMetadataTests {
@Test
public void buildWhenScopesAddingOrRemovingThenCorrectValues() {
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder.scope("should-be-removed")
.scopes(scopes -> {
.scopes((scopes) -> {
scopes.clear();
scopes.add("some-scope");
})
@ -372,7 +372,7 @@ public class OAuth2AuthorizationServerMetadataTests { @@ -372,7 +372,7 @@ public class OAuth2AuthorizationServerMetadataTests {
public void buildWhenResponseTypesAddingOrRemovingThenCorrectValues() {
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
.responseType("should-be-removed")
.responseTypes(responseTypes -> {
.responseTypes((responseTypes) -> {
responseTypes.clear();
responseTypes.add("some-response-type");
})
@ -384,8 +384,8 @@ public class OAuth2AuthorizationServerMetadataTests { @@ -384,8 +384,8 @@ public class OAuth2AuthorizationServerMetadataTests {
@Test
public void buildWhenResponseTypesNotPresentAndAddingThenCorrectValues() {
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
.claims(claims -> claims.remove(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED))
.responseTypes(responseTypes -> responseTypes.add("some-response-type"))
.claims((claims) -> claims.remove(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED))
.responseTypes((responseTypes) -> responseTypes.add("some-response-type"))
.build();
assertThat(authorizationServerMetadata.getResponseTypes()).containsExactly("some-response-type");
@ -412,7 +412,7 @@ public class OAuth2AuthorizationServerMetadataTests { @@ -412,7 +412,7 @@ public class OAuth2AuthorizationServerMetadataTests {
public void buildWhenGrantTypesAddingOrRemovingThenCorrectValues() {
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
.grantType("should-be-removed")
.grantTypes(grantTypes -> {
.grantTypes((grantTypes) -> {
grantTypes.clear();
grantTypes.add("some-grant-type");
})
@ -452,7 +452,7 @@ public class OAuth2AuthorizationServerMetadataTests { @@ -452,7 +452,7 @@ public class OAuth2AuthorizationServerMetadataTests {
public void buildWhenTokenRevocationEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() {
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
.tokenRevocationEndpointAuthenticationMethod("should-be-removed")
.tokenRevocationEndpointAuthenticationMethods(authMethods -> {
.tokenRevocationEndpointAuthenticationMethods((authMethods) -> {
authMethods.clear();
authMethods.add("some-authentication-method");
})
@ -494,7 +494,7 @@ public class OAuth2AuthorizationServerMetadataTests { @@ -494,7 +494,7 @@ public class OAuth2AuthorizationServerMetadataTests {
public void buildWhenTokenIntrospectionEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() {
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
.tokenIntrospectionEndpointAuthenticationMethod("should-be-removed")
.tokenIntrospectionEndpointAuthenticationMethods(authMethods -> {
.tokenIntrospectionEndpointAuthenticationMethods((authMethods) -> {
authMethods.clear();
authMethods.add("some-authentication-method");
})
@ -527,7 +527,7 @@ public class OAuth2AuthorizationServerMetadataTests { @@ -527,7 +527,7 @@ public class OAuth2AuthorizationServerMetadataTests {
public void buildWhenCodeChallengeMethodsAddingOrRemovingThenCorrectValues() {
OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder
.codeChallengeMethod("should-be-removed")
.codeChallengeMethods(codeChallengeMethods -> {
.codeChallengeMethods((codeChallengeMethods) -> {
codeChallengeMethods.clear();
codeChallengeMethods.add("some-authentication-method");
})

5
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/TestOAuth2Authorizations.java

@ -37,7 +37,10 @@ import org.springframework.util.CollectionUtils; @@ -37,7 +37,10 @@ import org.springframework.util.CollectionUtils;
* @author Joe Grandja
* @author Daniel Garnier-Moiroux
*/
public class TestOAuth2Authorizations {
public final class TestOAuth2Authorizations {
private TestOAuth2Authorizations() {
}
public static OAuth2Authorization.Builder authorization() {
return authorization(TestRegisteredClients.registeredClient().build());

90
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProviderTests.java

@ -43,10 +43,10 @@ import static org.assertj.core.api.Assertions.assertThat; @@ -43,10 +43,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link ClientSecretAuthenticationProvider}.
@ -129,16 +129,16 @@ public class ClientSecretAuthenticationProviderTests { @@ -129,16 +129,16 @@ public class ClientSecretAuthenticationProviderTests {
@Test
public void authenticateWhenInvalidClientIdThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId() + "-invalid", ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
registeredClient.getClientSecret(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID);
});
@ -147,16 +147,16 @@ public class ClientSecretAuthenticationProviderTests { @@ -147,16 +147,16 @@ public class ClientSecretAuthenticationProviderTests {
@Test
public void authenticateWhenUnsupportedClientAuthenticationMethodThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_POST,
registeredClient.getClientSecret(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription()).contains("authentication_method");
});
@ -165,15 +165,15 @@ public class ClientSecretAuthenticationProviderTests { @@ -165,15 +165,15 @@ public class ClientSecretAuthenticationProviderTests {
@Test
public void authenticateWhenClientSecretNotProvidedThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription()).contains("credentials");
});
@ -182,16 +182,16 @@ public class ClientSecretAuthenticationProviderTests { @@ -182,16 +182,16 @@ public class ClientSecretAuthenticationProviderTests {
@Test
public void authenticateWhenInvalidClientSecretThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
registeredClient.getClientSecret() + "-invalid", null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_SECRET);
});
@ -203,16 +203,16 @@ public class ClientSecretAuthenticationProviderTests { @@ -203,16 +203,16 @@ public class ClientSecretAuthenticationProviderTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.clientSecretExpiresAt(Instant.now().minus(1, ChronoUnit.HOURS).truncatedTo(ChronoUnit.SECONDS))
.build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
registeredClient.getClientSecret(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription()).contains("client_secret_expires_at");
});
@ -222,8 +222,8 @@ public class ClientSecretAuthenticationProviderTests { @@ -222,8 +222,8 @@ public class ClientSecretAuthenticationProviderTests {
@Test
public void authenticateWhenValidCredentialsThenAuthenticated() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
@ -241,8 +241,8 @@ public class ClientSecretAuthenticationProviderTests { @@ -241,8 +241,8 @@ public class ClientSecretAuthenticationProviderTests {
@Test
public void authenticateWhenValidCredentialsAndRequiresUpgradingThenClientSecretUpgraded() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
@ -263,11 +263,11 @@ public class ClientSecretAuthenticationProviderTests { @@ -263,11 +263,11 @@ public class ClientSecretAuthenticationProviderTests {
@Test
public void authenticateWhenAuthorizationCodeGrantAndValidCredentialsThenAuthenticated() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(TestOAuth2Authorizations.authorization().build());
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(TestOAuth2Authorizations.authorization().build());
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC,
registeredClient.getClientSecret(), createAuthorizationCodeTokenParameters());
@ -285,14 +285,14 @@ public class ClientSecretAuthenticationProviderTests { @@ -285,14 +285,14 @@ public class ClientSecretAuthenticationProviderTests {
@Test
public void authenticateWhenPkceAndInvalidCodeThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations
.authorization(registeredClient, createPkceAuthorizationParametersS256())
.build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER);
parameters.put(OAuth2ParameterNames.CODE, "invalid-code");
@ -303,8 +303,8 @@ public class ClientSecretAuthenticationProviderTests { @@ -303,8 +303,8 @@ public class ClientSecretAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CODE);
});
@ -313,14 +313,14 @@ public class ClientSecretAuthenticationProviderTests { @@ -313,14 +313,14 @@ public class ClientSecretAuthenticationProviderTests {
@Test
public void authenticateWhenPkceAndMissingCodeVerifierThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations
.authorization(registeredClient, createPkceAuthorizationParametersS256())
.build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
Map<String, Object> parameters = createAuthorizationCodeTokenParameters();
@ -330,8 +330,8 @@ public class ClientSecretAuthenticationProviderTests { @@ -330,8 +330,8 @@ public class ClientSecretAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
assertThat(error.getDescription()).contains(PkceParameterNames.CODE_VERIFIER);
});
@ -340,14 +340,14 @@ public class ClientSecretAuthenticationProviderTests { @@ -340,14 +340,14 @@ public class ClientSecretAuthenticationProviderTests {
@Test
public void authenticateWhenPkceAndValidCodeVerifierThenAuthenticated() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations
.authorization(registeredClient, createPkceAuthorizationParametersS256())
.build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER);

54
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProviderTests.java

@ -65,9 +65,9 @@ import org.springframework.web.util.UriComponentsBuilder; @@ -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.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link JwtClientAssertionAuthenticationProvider}.
@ -144,16 +144,16 @@ public class JwtClientAssertionAuthenticationProviderTests { @@ -144,16 +144,16 @@ public class JwtClientAssertionAuthenticationProviderTests {
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT)
.build();
// @formatter:on
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId() + "-invalid", JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD,
"jwt-assertion", null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID);
});
@ -162,15 +162,15 @@ public class JwtClientAssertionAuthenticationProviderTests { @@ -162,15 +162,15 @@ public class JwtClientAssertionAuthenticationProviderTests {
@Test
public void authenticateWhenUnsupportedClientAuthenticationMethodThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "jwt-assertion", null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription()).contains("authentication_method");
});
@ -183,15 +183,15 @@ public class JwtClientAssertionAuthenticationProviderTests { @@ -183,15 +183,15 @@ public class JwtClientAssertionAuthenticationProviderTests {
.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT)
.build();
// @formatter:on
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription()).contains("credentials");
});
@ -210,8 +210,8 @@ public class JwtClientAssertionAuthenticationProviderTests { @@ -210,8 +210,8 @@ public class JwtClientAssertionAuthenticationProviderTests {
)
.build();
// @formatter:on
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken(
registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "invalid-jwt-assertion",
@ -219,8 +219,8 @@ public class JwtClientAssertionAuthenticationProviderTests { @@ -219,8 +219,8 @@ public class JwtClientAssertionAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.hasCauseInstanceOf(BadJwtException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ASSERTION);
});
@ -239,8 +239,8 @@ public class JwtClientAssertionAuthenticationProviderTests { @@ -239,8 +239,8 @@ public class JwtClientAssertionAuthenticationProviderTests {
)
.build();
// @formatter:on
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
// @formatter:off
JwsHeader jwsHeader = JwsHeader.with(MacAlgorithm.HS256)
@ -261,8 +261,8 @@ public class JwtClientAssertionAuthenticationProviderTests { @@ -261,8 +261,8 @@ public class JwtClientAssertionAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.hasCauseInstanceOf(JwtValidationException.class)
.extracting(ex -> (OAuth2AuthenticationException) ex)
.satisfies(ex -> {
.extracting((ex) -> (OAuth2AuthenticationException) ex)
.satisfies((ex) -> {
assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(ex.getError().getDescription()).contains(OAuth2ParameterNames.CLIENT_ASSERTION);
JwtValidationException jwtValidationException = (JwtValidationException) ex.getCause();
@ -284,8 +284,8 @@ public class JwtClientAssertionAuthenticationProviderTests { @@ -284,8 +284,8 @@ public class JwtClientAssertionAuthenticationProviderTests {
)
.build();
// @formatter:on
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
// @formatter:off
JwsHeader jwsHeader = JwsHeader.with(MacAlgorithm.HS256)
@ -324,14 +324,14 @@ public class JwtClientAssertionAuthenticationProviderTests { @@ -324,14 +324,14 @@ public class JwtClientAssertionAuthenticationProviderTests {
)
.build();
// @formatter:on
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations
.authorization(registeredClient, createPkceAuthorizationParametersS256())
.build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER);

12
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactoryTests.java

@ -60,8 +60,8 @@ public class JwtClientAssertionDecoderFactoryTests { @@ -60,8 +60,8 @@ public class JwtClientAssertionDecoderFactoryTests {
assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_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.");
@ -84,8 +84,8 @@ public class JwtClientAssertionDecoderFactoryTests { @@ -84,8 +84,8 @@ public class JwtClientAssertionDecoderFactoryTests {
assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription()).isEqualTo("Failed to find a Signature Verifier for Client: '"
+ registeredClient.getId() + "'. Check to ensure you have configured the client secret.");
@ -102,8 +102,8 @@ public class JwtClientAssertionDecoderFactoryTests { @@ -102,8 +102,8 @@ public class JwtClientAssertionDecoderFactoryTests {
assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
assertThat(error.getDescription())
.isEqualTo("Failed to find a Signature Verifier for Client: '" + registeredClient.getId()

10
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationTokenTests.java

@ -15,6 +15,11 @@ @@ -15,6 +15,11 @@
*/
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.springframework.security.oauth2.core.ClientAuthenticationMethod;
@ -23,11 +28,6 @@ import org.springframework.security.oauth2.core.OAuth2RefreshToken; @@ -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.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.assertThatThrownBy;

118
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java

@ -84,13 +84,13 @@ 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.mockito.ArgumentMatchers.any;
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.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link OAuth2AuthorizationCodeAuthenticationProvider}.
@ -188,7 +188,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -188,7 +188,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
AUTHORIZATION_CODE, clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
}
@ -203,7 +203,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -203,7 +203,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
AUTHORIZATION_CODE, clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
}
@ -217,7 +217,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -217,7 +217,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
AUTHORIZATION_CODE, clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
}
@ -225,8 +225,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -225,8 +225,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
@Test
public void authenticateWhenCodeIssuedToAnotherClientThenThrowOAuth2AuthenticationException() {
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization().build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
@ -235,7 +235,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -235,7 +235,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
AUTHORIZATION_CODE, clientPrincipal, null, null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
@ -251,8 +251,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -251,8 +251,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
public void authenticateWhenInvalidRedirectUriThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -262,7 +262,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -262,7 +262,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri() + "-invalid", null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
}
@ -276,8 +276,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -276,8 +276,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
.token(authorizationCode,
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
.build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -288,7 +288,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -288,7 +288,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
@ -309,8 +309,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -309,8 +309,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
.token(authorizationCode,
(metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true))
.build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -321,7 +321,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -321,7 +321,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
@ -337,8 +337,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -337,8 +337,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(authorizationCode)
.build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -349,7 +349,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -349,7 +349,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
}
@ -358,8 +358,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -358,8 +358,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
public void authenticateWhenAccessTokenNotGeneratedThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -368,7 +368,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -368,7 +368,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null);
doAnswer(answer -> {
willAnswer((answer) -> {
OAuth2TokenContext context = answer.getArgument(0);
if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
return null;
@ -376,12 +376,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -376,12 +376,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
else {
return answer.callRealMethod();
}
}).when(this.tokenGenerator).generate(any());
}).given(this.tokenGenerator).generate(any());
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
assertThat(error.getDescription()).contains("The token generator failed to generate the access token.");
});
@ -391,8 +391,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -391,8 +391,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
public void authenticateWhenInvalidRefreshTokenGeneratedThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -401,9 +401,9 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -401,9 +401,9 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
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);
if (OAuth2TokenType.REFRESH_TOKEN.equals(context.getTokenType())) {
return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", Instant.now(),
@ -412,12 +412,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -412,12 +412,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
else {
return answer.callRealMethod();
}
}).when(this.tokenGenerator).generate(any());
}).given(this.tokenGenerator).generate(any());
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
assertThat(error.getDescription())
.contains("The token generator failed to generate a valid refresh token.");
@ -428,8 +428,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -428,8 +428,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
public void authenticateWhenIdTokenNotGeneratedThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -438,9 +438,9 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -438,9 +438,9 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
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);
if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
return null;
@ -448,12 +448,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -448,12 +448,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
else {
return answer.callRealMethod();
}
}).when(this.tokenGenerator).generate(any());
}).given(this.tokenGenerator).generate(any());
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
assertThat(error.getDescription()).contains("The token generator failed to generate the ID token.");
});
@ -463,8 +463,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -463,8 +463,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
public void authenticateWhenValidCodeThenReturnAccessToken() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -473,7 +473,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -473,7 +473,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
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
.authenticate(authentication);
@ -528,8 +528,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -528,8 +528,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
Instant.now().plusSeconds(120));
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient, authorizationCode)
.build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -538,7 +538,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -538,7 +538,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
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());
@ -549,7 +549,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -549,7 +549,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
sessions.add(new SessionInformation(principal.getPrincipal(), "session1",
Date.from(Instant.now().minus(2, ChronoUnit.HOURS))));
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
.authenticate(authentication);
@ -622,8 +622,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -622,8 +622,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.NONE, null);
@ -632,7 +632,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -632,7 +632,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
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
.authenticate(authentication);
@ -690,8 +690,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -690,8 +690,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
.build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -702,7 +702,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -702,7 +702,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
Instant accessTokenIssuedAt = Instant.now();
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
.authenticate(authentication);
@ -731,12 +731,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -731,12 +731,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
@Test
public void authenticateWhenRefreshTokenGrantNotConfiguredThenRefreshTokenNotIssued() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.REFRESH_TOKEN))
.authorizationGrantTypes((grantTypes) -> grantTypes.remove(AuthorizationGrantType.REFRESH_TOKEN))
.build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -745,7 +745,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -745,7 +745,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
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
.authenticate(authentication);
@ -763,8 +763,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @@ -763,8 +763,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
.build();
// @formatter:on
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build();
when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());

156
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProviderTests.java

@ -55,9 +55,9 @@ import static org.assertj.core.api.Assertions.assertThat; @@ -55,9 +55,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link OAuth2AuthorizationCodeRequestAuthenticationProvider}.
@ -155,11 +155,11 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -155,11 +155,11 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null));
}
@ -167,14 +167,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -167,14 +167,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
@Test
public void authenticateWhenInvalidRedirectUriHostThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https:///invalid", STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https:///invalid", STATE,
registeredClient.getScopes(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
}
@ -182,28 +182,28 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -182,28 +182,28 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
@Test
public void authenticateWhenInvalidRedirectUriFragmentThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https://example.com#fragment", STATE,
registeredClient.getScopes(), null);
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https://example.com#fragment",
STATE, registeredClient.getScopes(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
}
@Test
public void authenticateWhenUnregisteredRedirectUriThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
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);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
}
@ -213,10 +213,10 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -213,10 +213,10 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.redirectUri("https://127.0.0.1:8080")
.build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
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);
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
@ -232,10 +232,10 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -232,10 +232,10 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.redirectUri("https://[::1]:8080")
.build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
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);
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
@ -250,14 +250,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -250,14 +250,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.redirectUri("https://example2.com")
.build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, null, STATE, registeredClient.getScopes(),
null);
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, null, STATE,
registeredClient.getScopes(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
}
@ -265,14 +265,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -265,14 +265,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
public void authenticateWhenAuthenticationRequestMissingRedirectUriThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
// redirect_uri is REQUIRED for OpenID Connect requests
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, null, STATE, registeredClient.getScopes(),
null);
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, null, STATE,
registeredClient.getScopes(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null));
}
@ -282,15 +282,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -282,15 +282,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
.authorizationGrantTypes(Set::clear)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.UNAUTHORIZED_CLIENT, OAuth2ParameterNames.CLIENT_ID,
authentication.getRedirectUri()));
}
@ -298,15 +298,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -298,15 +298,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
@Test
public void authenticateWhenInvalidScopeThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
Collections.singleton("invalid-scope"), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE, authentication.getRedirectUri()));
}
@ -315,15 +315,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -315,15 +315,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.clientSettings(ClientSettings.builder().requireProofKey(true).build())
.build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE,
authentication.getRedirectUri()));
}
@ -331,18 +331,18 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -331,18 +331,18 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
@Test
public void authenticateWhenPkceUnsupportedCodeChallengeMethodThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0];
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge");
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "unsupported");
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), additionalParameters);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD,
authentication.getRedirectUri()));
}
@ -351,17 +351,17 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -351,17 +351,17 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
@Test
public void authenticateWhenPkceMissingCodeChallengeMethodThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge");
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), additionalParameters);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD,
authentication.getRedirectUri()));
}
@ -369,13 +369,13 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -369,13 +369,13 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
@Test
public void authenticateWhenPrincipalNotAuthenticatedThenReturnAuthorizationCodeRequest() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
this.principal.setAuthenticated(false);
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), null);
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
@ -390,12 +390,12 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -390,12 +390,12 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
.build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0];
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), null);
OAuth2AuthorizationConsentAuthenticationToken authenticationResult = (OAuth2AuthorizationConsentAuthenticationToken) this.authenticationProvider
@ -436,17 +436,17 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -436,17 +436,17 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
public void authenticateWhenRequireAuthorizationConsentAndOnlyOpenidScopeRequestedThenAuthorizationConsentNotRequired() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
.scopes(scopes -> {
.scopes((scopes) -> {
scopes.clear();
scopes.add(OidcScopes.OPENID);
})
.build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), null);
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
@ -461,19 +461,19 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -461,19 +461,19 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
.build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2AuthorizationConsent.Builder builder = OAuth2AuthorizationConsent.withId(registeredClient.getId(),
this.principal.getName());
registeredClient.getScopes().forEach(builder::scope);
OAuth2AuthorizationConsent previousAuthorizationConsent = builder.build();
when(this.authorizationConsentService.findById(eq(registeredClient.getId()), eq(this.principal.getName())))
.thenReturn(previousAuthorizationConsent);
given(this.authorizationConsentService.findById(eq(registeredClient.getId()), eq(this.principal.getName())))
.willReturn(previousAuthorizationConsent);
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), null);
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
@ -511,15 +511,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -511,15 +511,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
@Test
public void authenticateWhenAuthorizationCodeRequestValidThenReturnAuthorizationCode() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0];
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge");
additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256");
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), additionalParameters);
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
@ -532,8 +532,8 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -532,8 +532,8 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
@Test
public void authenticateWhenAuthorizationCodeNotGeneratedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
@SuppressWarnings("unchecked")
OAuth2TokenGenerator<OAuth2AuthorizationCode> authorizationCodeGenerator = mock(OAuth2TokenGenerator.class);
@ -541,13 +541,13 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -541,13 +541,13 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1];
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.extracting(ex -> ((OAuth2AuthorizationCodeRequestAuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthorizationCodeRequestAuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
assertThat(error.getDescription())
.contains("The token generator failed to generate the authorization code.");
@ -557,8 +557,8 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -557,8 +557,8 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
@Test
public void authenticateWhenCustomAuthenticationValidatorThenUsed() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
@SuppressWarnings("unchecked")
Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> authenticationValidator = mock(Consumer.class);
@ -566,7 +566,7 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @@ -566,7 +566,7 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests {
String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2];
OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE,
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE,
registeredClient.getScopes(), null);
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider

2
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContextTests.java

@ -107,7 +107,7 @@ public class OAuth2AuthorizationConsentAuthenticationContextTests { @@ -107,7 +107,7 @@ public class OAuth2AuthorizationConsentAuthenticationContextTests {
.authorization(this.authorization)
.authorizationRequest(this.authorizationRequest)
.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();
assertThat(context.<Authentication>getAuthentication()).isEqualTo(this.authorizationConsentAuthentication);

158
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProviderTests.java

@ -49,10 +49,10 @@ import static org.assertj.core.api.Assertions.assertThat; @@ -49,10 +49,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link OAuth2AuthorizationConsentAuthenticationProvider}.
@ -141,14 +141,14 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -141,14 +141,14 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
public void authenticateWhenInvalidStateThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(),
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(),
null);
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.thenReturn(null);
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.willReturn(null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null));
}
@ -159,15 +159,15 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -159,15 +159,15 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
.principalName(this.principal.getName())
.build();
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(),
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(),
null);
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.willReturn(authorization);
this.principal.setAuthenticated(false);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null));
}
@ -178,14 +178,14 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -178,14 +178,14 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
.principalName(this.principal.getName().concat("-other"))
.build();
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(),
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(),
null);
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.thenReturn(authorization);
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.willReturn(authorization);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null));
}
@ -195,43 +195,43 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -195,43 +195,43 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.principalName(this.principal.getName())
.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();
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, otherRegisteredClient.getClientId(), principal, STATE, registeredClient.getScopes(),
null);
AUTHORIZATION_URI, otherRegisteredClient.getClientId(), this.principal, STATE,
registeredClient.getScopes(), null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null));
}
@Test
public void authenticateWhenDoesNotMatchClientThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
RegisteredClient otherRegisteredClient = TestRegisteredClients.registeredClient2().build();
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(otherRegisteredClient)
.principalName(this.principal.getName())
.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(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(),
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(),
null);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null));
}
@Test
public void authenticateWhenScopeNotRequestedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.principalName(this.principal.getName())
.build();
@ -240,37 +240,37 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -240,37 +240,37 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
Set<String> authorizedScopes = new HashSet<>(authorizationRequest.getScopes());
authorizedScopes.add("scope-not-requested");
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, authorizedScopes, null);
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.thenReturn(authorization);
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, authorizedScopes, null);
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.willReturn(authorization);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE, authorizationRequest.getRedirectUri()));
}
@Test
public void authenticateWhenNotApprovedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.principalName(this.principal.getName())
.build();
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); // No
// scopes
// approved
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.thenReturn(authorization);
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); // No
// scopes
// approved
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2AuthorizationRequest authorizationRequest = authorization
.getAttribute(OAuth2AuthorizationRequest.class.getName());
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ParameterNames.CLIENT_ID,
authorizationRequest.getRedirectUri()));
@ -280,8 +280,8 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -280,8 +280,8 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
@Test
public void authenticateWhenApproveAllThenReturnAuthorizationCode() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.principalName(this.principal.getName())
.build();
@ -289,11 +289,11 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -289,11 +289,11 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
.getAttribute(OAuth2AuthorizationRequest.class.getName());
Set<String> authorizedScopes = authorizationRequest.getScopes();
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, authorizedScopes, null); // Approve
// all
// scopes
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.thenReturn(authorization);
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, authorizedScopes, null); // Approve
// all
// scopes
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
@ -305,8 +305,8 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -305,8 +305,8 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
@Test
public void authenticateWhenCustomAuthorizationConsentCustomizerThenUsed() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.principalName(this.principal.getName())
.build();
@ -314,11 +314,11 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -314,11 +314,11 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
.getAttribute(OAuth2AuthorizationRequest.class.getName());
Set<String> authorizedScopes = authorizationRequest.getScopes();
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, authorizedScopes, null); // Approve
// all
// scopes
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.thenReturn(authorization);
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, authorizedScopes, null); // Approve
// all
// scopes
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.willReturn(authorization);
@SuppressWarnings("unchecked")
Consumer<OAuth2AuthorizationConsentAuthenticationContext> authorizationConsentCustomizer = mock(Consumer.class);
@ -391,31 +391,31 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -391,31 +391,31 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
public void authenticateWhenApproveNoneAndRevokePreviouslyApprovedThenAuthorizationConsentRemoved() {
String previouslyApprovedScope = "message.read";
String requestedScope = "message.write";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> {
scopes.clear();
scopes.add(previouslyApprovedScope);
scopes.add(requestedScope);
}).build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.principalName(this.principal.getName())
.build();
OAuth2AuthorizationRequest authorizationRequest = authorization
.getAttribute(OAuth2AuthorizationRequest.class.getName());
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); // No
// scopes
// approved
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.thenReturn(authorization);
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); // No
// scopes
// approved
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent
.withId(authorization.getRegisteredClientId(), authorization.getPrincipalName())
.scope(previouslyApprovedScope)
.build();
when(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
given(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
eq(authorization.getPrincipalName())))
.thenReturn(previousAuthorizationConsent);
.willReturn(previousAuthorizationConsent);
// Revoke all (including previously approved)
this.authenticationProvider.setAuthorizationConsentCustomizer(
@ -424,7 +424,7 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -424,7 +424,7 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class)
.satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
.satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex,
OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ParameterNames.CLIENT_ID,
authorizationRequest.getRedirectUri()));
@ -437,13 +437,13 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -437,13 +437,13 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
String previouslyApprovedScope = "message.read";
String requestedScope = "message.write";
String otherPreviouslyApprovedScope = "other.scope";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> {
scopes.clear();
scopes.add(previouslyApprovedScope);
scopes.add(requestedScope);
}).build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.principalName(this.principal.getName())
.build();
@ -451,17 +451,17 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -451,17 +451,17 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
.getAttribute(OAuth2AuthorizationRequest.class.getName());
Set<String> requestedScopes = authorizationRequest.getScopes();
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, requestedScopes, null);
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.thenReturn(authorization);
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, requestedScopes, null);
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent
.withId(authorization.getRegisteredClientId(), authorization.getPrincipalName())
.scope(previouslyApprovedScope)
.scope(otherPreviouslyApprovedScope)
.build();
when(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
given(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
eq(authorization.getPrincipalName())))
.thenReturn(previousAuthorizationConsent);
.willReturn(previousAuthorizationConsent);
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
@ -489,29 +489,29 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @@ -489,29 +489,29 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests {
public void authenticateWhenApproveNoneAndPreviouslyApprovedThenAuthorizationConsentNotUpdated() {
String previouslyApprovedScope = "message.read";
String requestedScope = "message.write";
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> {
scopes.clear();
scopes.add(previouslyApprovedScope);
scopes.add(requestedScope);
}).build();
when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.thenReturn(registeredClient);
given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId())))
.willReturn(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.principalName(this.principal.getName())
.build();
OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken(
AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); // No
// scopes
// approved
when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.thenReturn(authorization);
AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); // No
// scopes
// approved
given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE)))
.willReturn(authorization);
OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent
.withId(authorization.getRegisteredClientId(), authorization.getPrincipalName())
.scope(previouslyApprovedScope)
.build();
when(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
given(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()),
eq(authorization.getPrincipalName())))
.thenReturn(previousAuthorizationConsent);
.willReturn(previousAuthorizationConsent);
OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider
.authenticate(authentication);

22
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProviderTests.java

@ -60,11 +60,11 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke @@ -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.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link OAuth2ClientCredentialsAuthenticationProvider}.
@ -159,7 +159,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { @@ -159,7 +159,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
}
@ -175,7 +175,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { @@ -175,7 +175,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
}
@ -183,7 +183,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { @@ -183,7 +183,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
@Test
public void authenticateWhenClientNotAuthorizedToRequestTokenThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient2()
.authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.CLIENT_CREDENTIALS))
.authorizationGrantTypes((grantTypes) -> grantTypes.remove(AuthorizationGrantType.CLIENT_CREDENTIALS))
.build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret());
@ -192,7 +192,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { @@ -192,7 +192,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
}
@ -207,7 +207,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { @@ -207,7 +207,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.extracting("errorCode")
.isEqualTo(OAuth2ErrorCodes.INVALID_SCOPE);
}
@ -221,7 +221,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { @@ -221,7 +221,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
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
.authenticate(authentication);
@ -236,7 +236,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { @@ -236,7 +236,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
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
.authenticate(authentication);
@ -255,8 +255,8 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { @@ -255,8 +255,8 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.isInstanceOf(OAuth2AuthenticationException.class)
.extracting(ex -> ((OAuth2AuthenticationException) ex).getError())
.satisfies(error -> {
.extracting((ex) -> ((OAuth2AuthenticationException) ex).getError())
.satisfies((error) -> {
assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
assertThat(error.getDescription()).contains("The token generator failed to generate the access token.");
});
@ -270,7 +270,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { @@ -270,7 +270,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests {
OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken(
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
.authenticate(authentication);

67
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProviderTests.java

@ -52,12 +52,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -52,12 +52,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
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}.
@ -149,7 +148,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -149,7 +148,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
verify(this.authorizationService).findByToken(STATE,
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
}
@ -157,7 +157,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -157,7 +157,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
public void authenticateWhenPrincipalIsNotAuthenticatedThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
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);
Authentication authentication = new OAuth2DeviceAuthorizationConsentAuthenticationToken(AUTHORIZATION_URI,
registeredClient.getClientId(), principal, USER_CODE, STATE, null, Collections.emptyMap());
@ -170,7 +170,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -170,7 +170,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
verify(this.authorizationService).findByToken(STATE,
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
}
@ -178,7 +179,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -178,7 +179,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
public void authenticateWhenPrincipalNameDoesNotMatchThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
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());
Authentication authentication = new OAuth2DeviceAuthorizationConsentAuthenticationToken(AUTHORIZATION_URI,
registeredClient.getClientId(), principal, USER_CODE, STATE, null, Collections.emptyMap());
@ -191,7 +192,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -191,7 +192,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE);
verify(this.authorizationService).findByToken(STATE,
OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE);
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
}
@ -199,7 +201,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -199,7 +201,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
public void authenticateWhenRegisteredClientNotFoundThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
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);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
@ -211,7 +213,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -211,7 +213,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
// @formatter:on
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);
verifyNoInteractions(this.authorizationConsentService);
}
@ -221,8 +224,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -221,8 +224,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
RegisteredClient registeredClient2 = TestRegisteredClients.registeredClient2().build();
OAuth2Authorization authorization = createAuthorization(registeredClient2);
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
Authentication authentication = createAuthentication(registeredClient);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
@ -234,7 +237,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -234,7 +237,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
// @formatter:on
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);
verifyNoInteractions(this.authorizationConsentService);
}
@ -247,8 +251,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -247,8 +251,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
.scope("invalid")
.build();
OAuth2Authorization authorization = createAuthorization(registeredClient);
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
Authentication authentication = createAuthentication(registeredClient2);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
@ -260,7 +264,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -260,7 +264,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
// @formatter:on
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);
verifyNoInteractions(this.authorizationConsentService);
}
@ -271,8 +276,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -271,8 +276,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
RegisteredClient registeredClient2 = TestRegisteredClients.registeredClient().scopes(Set::clear).build();
OAuth2Authorization authorization = createAuthorization(registeredClient2);
Authentication authentication = createAuthentication(registeredClient2);
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
@ -282,7 +287,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -282,7 +287,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
// @formatter:on
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.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
verify(this.authorizationService).save(authorizationCaptor.capture());
@ -305,8 +311,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -305,8 +311,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
public void authenticateWhenAuthoritiesIsNotEmptyThenAuthorizationConsentSaved() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2Authorization authorization = createAuthorization(registeredClient);
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
Authentication authentication = createAuthentication(registeredClient);
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
@ -317,7 +323,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -317,7 +323,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
assertThat(authenticationResult.getUserCode()).isEqualTo(USER_CODE);
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.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
verify(this.authorizationConsentService).save(any(OAuth2AuthorizationConsent.class));
@ -354,9 +361,9 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -354,9 +361,9 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
OAuth2AuthorizationConsent.withId(registeredClient.getId(), authentication.getName())
.scope("scope1").build();
// @formatter:on
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(authorizationConsent);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(authorizationConsent);
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
@ -367,7 +374,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -367,7 +374,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
ArgumentCaptor<OAuth2AuthorizationConsent> authorizationConsentCaptor = ArgumentCaptor
.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.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
verify(this.authorizationConsentService).save(authorizationConsentCaptor.capture());
@ -390,9 +398,9 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -390,9 +398,9 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(Set::clear).build();
OAuth2Authorization authorization = createAuthorization(registeredClient);
Authentication authentication = createAuthentication(registeredClient);
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient);
when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(null);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient);
given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(null);
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
@ -403,7 +411,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { @@ -403,7 +411,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests {
ArgumentCaptor<OAuth2AuthorizationConsent> authorizationConsentCaptor = ArgumentCaptor
.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.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
verify(this.authorizationConsentService).save(authorizationConsentCaptor.capture());

18
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProviderTests.java

@ -48,13 +48,11 @@ import static org.assertj.core.api.Assertions.assertThat; @@ -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.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
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}.
@ -171,7 +169,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests { @@ -171,7 +169,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests {
public void authenticateWhenDeviceCodeIsNullThenThrowOAuth2AuthenticationException() {
@SuppressWarnings("unchecked")
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);
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
@ -196,7 +194,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests { @@ -196,7 +194,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests {
public void authenticateWhenUserCodeIsNullThenThrowOAuth2AuthenticationException() {
@SuppressWarnings("unchecked")
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);
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.DEVICE_CODE)
@ -277,7 +275,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests { @@ -277,7 +275,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests {
public void authenticateWhenDeviceCodeGeneratorSetThenUsed() {
@SuppressWarnings("unchecked")
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);
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
@ -303,14 +301,15 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests { @@ -303,14 +301,15 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests {
assertThat(tokenContext.getAuthorizationServerContext()).isNotNull();
assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.DEVICE_CODE);
assertThat(tokenContext.<Authentication>getAuthorizationGrant()).isEqualTo(authentication);
assertThat(tokenContext.getTokenType()).isEqualTo(DEVICE_CODE_TOKEN_TYPE);
assertThat(tokenContext.getTokenType())
.isEqualTo(OAuth2DeviceAuthorizationRequestAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE);
}
@Test
public void authenticateWhenUserCodeGeneratorSetThenUsed() {
@SuppressWarnings("unchecked")
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);
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
@ -335,7 +334,8 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests { @@ -335,7 +334,8 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests {
assertThat(tokenContext.getAuthorizationServerContext()).isNotNull();
assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.DEVICE_CODE);
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() {

62
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProviderTests.java

@ -55,15 +55,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -55,15 +55,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
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}.
@ -142,7 +139,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -142,7 +139,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
public void authenticateWhenAuthorizationNotFoundThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
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
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
@ -151,7 +148,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -151,7 +148,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @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);
verifyNoInteractions(this.tokenGenerator);
}
@ -164,7 +162,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -164,7 +162,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient2)
.token(createDeviceCode())
.build();
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
@ -174,7 +172,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -174,7 +172,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
// @formatter:on
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());
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
@ -194,16 +193,17 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -194,16 +193,17 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createUserCode())
.build();
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(AUTHORIZATION_PENDING);
.isEqualTo(OAuth2DeviceCodeAuthenticationProvider.AUTHORIZATION_PENDING);
// @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);
verifyNoInteractions(this.tokenGenerator);
}
@ -216,7 +216,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -216,7 +216,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.token(createDeviceCode(), withInvalidated())
.token(createUserCode(), withInvalidated())
.build();
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
@ -225,7 +225,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -225,7 +225,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.isEqualTo(OAuth2ErrorCodes.ACCESS_DENIED);
// @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);
verifyNoInteractions(this.tokenGenerator);
}
@ -238,17 +239,18 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -238,17 +239,18 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.token(createExpiredDeviceCode())
.token(createUserCode(), withInvalidated())
.build();
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(EXPIRED_TOKEN);
.isEqualTo(OAuth2DeviceCodeAuthenticationProvider.EXPIRED_TOKEN);
// @formatter:on
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());
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
@ -272,8 +274,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -272,8 +274,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.attribute(Principal.class.getName(), authentication.getPrincipal())
.build();
// @formatter:on
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(null);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(null);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
@ -283,7 +285,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -283,7 +285,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
// @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));
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
}
@ -299,8 +302,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -299,8 +302,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.attribute(Principal.class.getName(), authentication.getPrincipal())
.build();
// @formatter:on
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(createAccessToken(),
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(createAccessToken(),
(OAuth2RefreshToken) null);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
@ -311,7 +314,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -311,7 +314,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
// @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));
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
}
@ -327,9 +331,9 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -327,9 +331,9 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.attribute(Principal.class.getName(), authentication.getPrincipal())
.build();
// @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();
when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(accessToken, accessToken);
given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(accessToken, accessToken);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
@ -339,7 +343,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -339,7 +343,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.isEqualTo(OAuth2ErrorCodes.SERVER_ERROR);
// @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));
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
}
@ -355,10 +360,10 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -355,10 +360,10 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
.attribute(Principal.class.getName(), authentication.getPrincipal())
.build();
// @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();
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
.authenticate(authentication);
assertThat(authenticationResult.getRegisteredClient()).isEqualTo(registeredClient);
@ -368,7 +373,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { @@ -368,7 +373,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests {
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.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.tokenGenerator, times(2)).generate(tokenContextCaptor.capture());
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);

40
oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProviderTests.java

@ -55,12 +55,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -55,12 +55,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
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}.
@ -130,7 +129,7 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { @@ -130,7 +129,7 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
@Test
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();
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
@ -140,7 +139,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { @@ -140,7 +139,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @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);
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
}
@ -152,14 +152,15 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { @@ -152,14 +152,15 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
TestingAuthenticationToken principal = new TestingAuthenticationToken("user", null);
Authentication authentication = new OAuth2DeviceVerificationAuthenticationToken(principal, USER_CODE,
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
.authenticate(authentication);
assertThat(authenticationResult).isEqualTo(authentication);
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);
verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService);
}
@ -175,9 +176,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { @@ -175,9 +176,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
.build();
// @formatter:on
Authentication authentication = createAuthentication();
when(this.registeredClientRepository.findById(anyString())).thenReturn(registeredClient);
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(null);
given(this.registeredClientRepository.findById(anyString())).willReturn(registeredClient);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(null);
OAuth2DeviceAuthorizationConsentAuthenticationToken authenticationResult = (OAuth2DeviceAuthorizationConsentAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
@ -191,7 +192,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { @@ -191,7 +192,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
assertThat(authenticationResult.getScopes()).isEmpty();
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.authorizationService).save(authorizationCaptor.capture());
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
@ -222,9 +224,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { @@ -222,9 +224,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
.scope(registeredClient.getScopes().iterator().next())
.build();
// @formatter:on
when(this.registeredClientRepository.findById(anyString())).thenReturn(registeredClient);
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(authorizationConsent);
given(this.registeredClientRepository.findById(anyString())).willReturn(registeredClient);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(authorizationConsent);
OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
@ -234,7 +236,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { @@ -234,7 +236,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
assertThat(authenticationResult.getUserCode()).isEqualTo(USER_CODE);
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.authorizationService).save(authorizationCaptor.capture());
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());
@ -276,9 +279,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { @@ -276,9 +279,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
.scope("previous")
.build();
// @formatter:on
when(this.registeredClientRepository.findById(anyString())).thenReturn(registeredClient);
when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization);
when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(authorizationConsent);
given(this.registeredClientRepository.findById(anyString())).willReturn(registeredClient);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(authorizationConsent);
OAuth2DeviceAuthorizationConsentAuthenticationToken authenticationResult = (OAuth2DeviceAuthorizationConsentAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
@ -292,7 +295,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { @@ -292,7 +295,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests {
assertThat(authenticationResult.getScopes()).containsExactly("previous");
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.authorizationService).save(authorizationCaptor.capture());
verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName());

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save