From 1dd0ab0c5f14ed10a73b01d1e2b92ec39ee6b9e6 Mon Sep 17 00:00:00 2001 From: Joe Grandja <10884212+jgrandja@users.noreply.github.com> Date: Fri, 17 May 2024 10:14:19 -0400 Subject: [PATCH 1/5] Apply Spring checkstyle conventions Issue gh-1624 --- etc/checkstyle/checkstyle-suppressions.xml | 8 +++ etc/checkstyle/checkstyle.xml | 57 +++++----------------- etc/checkstyle/header.txt | 2 +- etc/checkstyle/suppressions.xml | 19 -------- 4 files changed, 21 insertions(+), 65 deletions(-) create mode 100644 etc/checkstyle/checkstyle-suppressions.xml delete mode 100644 etc/checkstyle/suppressions.xml diff --git a/etc/checkstyle/checkstyle-suppressions.xml b/etc/checkstyle/checkstyle-suppressions.xml new file mode 100644 index 00000000..003a53d7 --- /dev/null +++ b/etc/checkstyle/checkstyle-suppressions.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/etc/checkstyle/checkstyle.xml b/etc/checkstyle/checkstyle.xml index d7b39201..da8d0119 100644 --- a/etc/checkstyle/checkstyle.xml +++ b/etc/checkstyle/checkstyle.xml @@ -1,51 +1,18 @@ - - - + + - + - - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + diff --git a/etc/checkstyle/header.txt b/etc/checkstyle/header.txt index 5e5d28b9..92317df0 100644 --- a/etc/checkstyle/header.txt +++ b/etc/checkstyle/header.txt @@ -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$ diff --git a/etc/checkstyle/suppressions.xml b/etc/checkstyle/suppressions.xml deleted file mode 100644 index 297f0624..00000000 --- a/etc/checkstyle/suppressions.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - From 9c45484c21a9c5944d790137cb7c63fe026f8be1 Mon Sep 17 00:00:00 2001 From: Joe Grandja <10884212+jgrandja@users.noreply.github.com> Date: Fri, 17 May 2024 13:59:32 -0400 Subject: [PATCH 2/5] Fix checkstyle violations for main module Issue gh-1624 --- ...ractOAuth2AuthorizationServerMetadata.java | 11 +- ...moryOAuth2AuthorizationConsentService.java | 2 +- .../InMemoryOAuth2AuthorizationService.java | 25 ++-- .../JdbcOAuth2AuthorizationService.java | 128 +++++++++--------- .../authorization/OAuth2Authorization.java | 5 +- .../OAuth2AuthorizationConsentService.java | 4 +- .../OAuth2AuthorizationServerMetadata.java | 4 +- .../OAuth2TokenIntrospection.java | 8 +- .../server/authorization/OAuth2TokenType.java | 6 + ...ClientAssertionAuthenticationProvider.java | 2 +- ...thorizationCodeAuthenticationProvider.java | 8 +- ...tionCodeRequestAuthenticationProvider.java | 4 +- ...izationCodeRequestAuthenticationToken.java | 6 +- ...rizationConsentAuthenticationProvider.java | 10 +- ...thorizationConsentAuthenticationToken.java | 4 +- ...AuthorizationGrantAuthenticationToken.java | 2 +- .../OAuth2ClientAuthenticationToken.java | 2 +- ...ientCredentialsAuthenticationProvider.java | 6 +- ...2ClientCredentialsAuthenticationToken.java | 2 +- ...rizationConsentAuthenticationProvider.java | 20 +-- ...thorizationConsentAuthenticationToken.java | 2 +- ...rizationRequestAuthenticationProvider.java | 6 +- ...thorizationRequestAuthenticationToken.java | 6 +- ...Auth2DeviceCodeAuthenticationProvider.java | 8 +- ...iceVerificationAuthenticationProvider.java | 6 +- ...DeviceVerificationAuthenticationToken.java | 2 +- ...th2RefreshTokenAuthenticationProvider.java | 6 +- ...OAuth2RefreshTokenAuthenticationToken.java | 2 +- ...enIntrospectionAuthenticationProvider.java | 6 +- ...TokenIntrospectionAuthenticationToken.java | 2 +- ...TokenRevocationAuthenticationProvider.java | 6 +- .../InMemoryRegisteredClientRepository.java | 4 +- .../JdbcRegisteredClientRepository.java | 16 +-- .../client/RegisteredClient.java | 4 +- .../client/RegisteredClientRepository.java | 2 +- ...Auth2AuthorizationServerConfiguration.java | 4 +- .../AuthorizationServerContextFilter.java | 2 +- ...OAuth2AuthorizationEndpointConfigurer.java | 5 +- .../OAuth2AuthorizationServerConfigurer.java | 6 +- ...ationServerMetadataEndpointConfigurer.java | 9 +- .../OAuth2ClientAuthenticationConfigurer.java | 3 +- .../configurers/OAuth2ConfigurerUtils.java | 2 +- ...DeviceAuthorizationEndpointConfigurer.java | 3 +- ...2DeviceVerificationEndpointConfigurer.java | 3 +- .../OAuth2TokenEndpointConfigurer.java | 3 +- ...2TokenIntrospectionEndpointConfigurer.java | 3 +- ...uth2TokenRevocationEndpointConfigurer.java | 3 +- ...cClientRegistrationEndpointConfigurer.java | 3 +- .../web/configurers/OidcConfigurer.java | 5 +- .../OidcLogoutEndpointConfigurer.java | 3 +- ...oviderConfigurationEndpointConfigurer.java | 9 +- .../OidcUserInfoEndpointConfigurer.java | 3 +- .../http/converter/HttpMessageConverters.java | 2 +- .../oidc/OidcClientRegistration.java | 9 +- .../oidc/OidcProviderConfiguration.java | 9 +- ...entRegistrationAuthenticationProvider.java | 25 ++-- .../OidcUserInfoAuthenticationProvider.java | 2 +- ...ClientOidcClientRegistrationConverter.java | 10 +- .../http/converter/HttpMessageConverters.java | 2 +- ...lientRegistrationHttpMessageConverter.java | 2 +- .../OidcClientRegistrationEndpointFilter.java | 4 +- .../settings/AbstractSettings.java | 5 +- .../settings/AuthorizationServerSettings.java | 4 +- .../settings/ClientSettings.java | 4 +- .../authorization/settings/TokenSettings.java | 6 +- .../authorization/token/JwtGenerator.java | 6 +- .../token/OAuth2TokenClaimsSet.java | 1 + .../token/OAuth2TokenCustomizer.java | 2 +- .../token/OAuth2TokenGenerator.java | 2 +- .../authorization/web/DefaultConsentPage.java | 4 +- .../web/NimbusJwkSetEndpointFilter.java | 9 +- .../OAuth2AuthorizationEndpointFilter.java | 6 +- ...Auth2DeviceVerificationEndpointFilter.java | 4 +- ...Auth2TokenIntrospectionEndpointFilter.java | 2 +- .../OAuth2TokenRevocationEndpointFilter.java | 2 +- ...ionCodeRequestAuthenticationConverter.java | 8 +- 76 files changed, 283 insertions(+), 253 deletions(-) diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/AbstractOAuth2AuthorizationServerMetadata.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/AbstractOAuth2AuthorizationServerMetadata.java index 09168646..5356ee03 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/AbstractOAuth2AuthorizationServerMetadata.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/AbstractOAuth2AuthorizationServerMetadata.java @@ -35,8 +35,8 @@ import org.springframework.util.Assert; * describes about its configuration. * * @author Daniel Garnier-Moiroux - * @see OAuth2AuthorizationServerMetadataClaimAccessor * @since 0.1.1 + * @see OAuth2AuthorizationServerMetadataClaimAccessor * @see 3.2. * Authorization Server Metadata Response * @see the type of object + * @param the type of the builder */ - protected static abstract class AbstractBuilder> { + protected abstract static class AbstractBuilder> { private final Map claims = new LinkedHashMap<>(); @@ -492,7 +495,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()); + getClaims().computeIfAbsent(name, (k) -> new LinkedList()); ((List) getClaims().get(name)).add(value); } @@ -500,7 +503,7 @@ public abstract class AbstractOAuth2AuthorizationServerMetadata private void acceptClaimValues(String name, Consumer> valuesConsumer) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(valuesConsumer, "valuesConsumer cannot be null"); - getClaims().computeIfAbsent(name, k -> new LinkedList()); + getClaims().computeIfAbsent(name, (k) -> new LinkedList()); List values = (List) getClaims().get(name); valuesConsumer.accept(values); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java index a2b351b7..15884b90 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java @@ -63,7 +63,7 @@ public final class InMemoryOAuth2AuthorizationConsentService implements OAuth2Au */ public InMemoryOAuth2AuthorizationConsentService(List 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), diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationService.java index e69dad95..cc697df8 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationService.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationService.java @@ -94,7 +94,7 @@ public final class InMemoryOAuth2AuthorizationService implements OAuth2Authoriza */ public InMemoryOAuth2AuthorizationService(List 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 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 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 diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java index 9bbbb912..21c3dfcb 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java @@ -362,6 +362,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) (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}. @@ -741,68 +805,4 @@ 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); - } - - private static ColumnMetadata getColumnMetadata(JdbcOperations jdbcOperations, String columnName, - int defaultDataType) { - Integer dataType = jdbcOperations.execute((ConnectionCallback) conn -> { - DatabaseMetaData databaseMetaData = conn.getMetaData(); - ResultSet rs = databaseMetaData.getColumns(null, null, TABLE_NAME, columnName); - 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); - } - } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2Authorization.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2Authorization.java index d40399cc..364b2139 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2Authorization.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2Authorization.java @@ -144,7 +144,7 @@ public class OAuth2Authorization implements Serializable { public Token getToken(Class tokenType) { Assert.notNull(tokenType, "tokenType cannot be null"); Token token = this.tokens.get(tokenType); - return token != null ? (Token) token : null; + return (token != null) ? (Token) token : null; } /** @@ -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 the type of the {@link OAuth2Token} * @author Joe Grandja * @since 0.1.0 */ diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentService.java index 19e0622b..56d8b249 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentService.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentService.java @@ -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)}. diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadata.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadata.java index e62740a3..d2876d3e 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadata.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadata.java @@ -52,13 +52,13 @@ public final class OAuth2AuthorizationServerMetadata extends AbstractOAuth2Autho */ public static Builder withClaims(Map claims) { Assert.notEmpty(claims, "claims cannot be empty"); - return new Builder().claims(c -> c.putAll(claims)); + return new Builder().claims((c) -> c.putAll(claims)); } /** * Helps configure an {@link OAuth2AuthorizationServerMetadata}. */ - public static class Builder extends AbstractBuilder { + public static final class Builder extends AbstractBuilder { private Builder() { } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenIntrospection.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenIntrospection.java index f2652c3b..e8254202 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenIntrospection.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenIntrospection.java @@ -88,13 +88,13 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC */ public static Builder withClaims(Map 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 claims = new LinkedHashMap<>(); @@ -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()); + this.claims.computeIfAbsent(name, (k) -> new LinkedList()); ((List) this.claims.get(name)).add(value); } @@ -320,7 +320,7 @@ public final class OAuth2TokenIntrospection implements OAuth2TokenIntrospectionC private void acceptClaimValues(String name, Consumer> valuesConsumer) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(valuesConsumer, "valuesConsumer cannot be null"); - this.claims.computeIfAbsent(name, k -> new LinkedList()); + this.claims.computeIfAbsent(name, (k) -> new LinkedList()); List values = (List) this.claims.get(name); valuesConsumer.accept(values); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenType.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenType.java index 63735785..9ddf3d05 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenType.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2TokenType.java @@ -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; diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java index 9c5c02b2..6352d6d5 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProvider.java @@ -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 diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java index 4de4aaaa..377dad03 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProvider.java @@ -64,8 +64,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. @@ -120,8 +118,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()) { @@ -166,7 +164,7 @@ public final class OAuth2AuthorizationCodeAuthenticationProvider implements Auth if (!authorizationCode.isActive()) { if (authorizationCode.isInvalidated()) { - OAuth2Authorization.Token token = authorization.getRefreshToken() != null + OAuth2Authorization.Token token = (authorization.getRefreshToken() != null) ? authorization.getRefreshToken() : authorization.getAccessToken(); if (token != null) { // Invalidate the access (and refresh) token as the client is diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java index 04db9883..d224ecc4 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProvider.java @@ -186,12 +186,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 currentAuthorizedScopes = currentAuthorizationConsent != null + Set currentAuthorizedScopes = (currentAuthorizationConsent != null) ? currentAuthorizationConsent.getScopes() : null; if (this.logger.isTraceEnabled()) { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationToken.java index 83cf1651..ebf3121b 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationToken.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationToken.java @@ -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 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); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProvider.java index a644b636..131b58ce 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProvider.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProvider.java @@ -154,7 +154,7 @@ public final class OAuth2AuthorizationConsentAuthenticationProvider implements A OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService .findById(authorization.getRegisteredClientId(), authorization.getPrincipalName()); - Set currentAuthorizedScopes = currentAuthorizationConsent != null + Set currentAuthorizedScopes = (currentAuthorizationConsent != null) ? currentAuthorizationConsent.getScopes() : Collections.emptySet(); if (!currentAuthorizedScopes.isEmpty()) { @@ -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 redirectUri = null; // Prevent redirects } - String state = authorizationRequest != null ? authorizationRequest.getState() + String state = (authorizationRequest != null) ? authorizationRequest.getState() : authorizationConsentAuthentication.getState(); - Set requestedScopes = authorizationRequest != null ? authorizationRequest.getScopes() + Set requestedScopes = (authorizationRequest != null) ? authorizationRequest.getScopes() : authorizationConsentAuthentication.getScopes(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationToken.java index abe8fbc9..f22a5a9e 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationToken.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationToken.java @@ -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); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationGrantAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationGrantAuthenticationToken.java index 59f4e4b5..df49fd4a 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationGrantAuthenticationToken.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationGrantAuthenticationToken.java @@ -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()); } /** diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientAuthenticationToken.java index cd898750..7a5c7e7d 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientAuthenticationToken.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientAuthenticationToken.java @@ -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()); } /** diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProvider.java index c8fcf167..192952e2 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProvider.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProvider.java @@ -43,8 +43,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 OAuth 2.0 Client Credentials * Grant. @@ -92,8 +90,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()) { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationToken.java index 59ef7d3a..71c58338 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationToken.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationToken.java @@ -47,7 +47,7 @@ public class OAuth2ClientCredentialsAuthenticationToken extends OAuth2Authorizat public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal, @Nullable Set scopes, @Nullable Map additionalParameters) { super(AuthorizationGrantType.CLIENT_CREDENTIALS, clientPrincipal, additionalParameters); - this.scopes = Collections.unmodifiableSet(scopes != null ? new HashSet<>(scopes) : Collections.emptySet()); + this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet()); } /** diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProvider.java index 38f15c7b..55978f0a 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProvider.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProvider.java @@ -133,7 +133,7 @@ public final class OAuth2DeviceAuthorizationConsentAuthenticationProvider implem OAuth2AuthorizationConsent currentAuthorizationConsent = this.authorizationConsentService .findById(authorization.getRegisteredClientId(), principal.getName()); - Set currentAuthorizedScopes = currentAuthorizationConsent != null + Set currentAuthorizedScopes = (currentAuthorizationConsent != null) ? currentAuthorizationConsent.getScopes() : Collections.emptySet(); if (!currentAuthorizedScopes.isEmpty()) { @@ -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 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); diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationToken.java index 12d34272..825ee536 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationToken.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationToken.java @@ -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); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProvider.java index 610c7c46..2a4164b7 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProvider.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProvider.java @@ -49,8 +49,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. @@ -97,8 +95,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()) { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationToken.java index 7d4a7e91..883b4a97 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationToken.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationToken.java @@ -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 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; diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProvider.java index 6e5b51be..63826aa7 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProvider.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProvider.java @@ -45,8 +45,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. @@ -102,8 +100,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()) { @@ -203,7 +201,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 diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProvider.java index 519dbe1a..6dc4e2de 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProvider.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProvider.java @@ -149,7 +149,7 @@ public final class OAuth2DeviceVerificationAuthenticationProvider implements Aut this.logger.trace("Saved authorization"); } - Set currentAuthorizedScopes = currentAuthorizationConsent != null + Set currentAuthorizedScopes = (currentAuthorizationConsent != null) ? currentAuthorizationConsent.getScopes() : null; AuthorizationServerSettings authorizationServerSettings = AuthorizationServerContextHolder.getContext() @@ -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); diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationToken.java index 28f08f43..114d11b3 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationToken.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationToken.java @@ -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; } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProvider.java index 7f255b93..3005ce02 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProvider.java +++ b/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 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 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()) { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationToken.java index 19209c4a..a216854c 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationToken.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationToken.java @@ -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()); } /** diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProvider.java index 15ad6f05..2bb28427 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProvider.java +++ b/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 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 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); diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationToken.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationToken.java index eb97771a..dff4a81e 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationToken.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationToken.java @@ -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(); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProvider.java index 7f6699b9..604d7fba 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProvider.java +++ b/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 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 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 diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/InMemoryRegisteredClientRepository.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/InMemoryRegisteredClientRepository.java index e230b358..69d91745 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/InMemoryRegisteredClientRepository.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/InMemoryRegisteredClientRepository.java @@ -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 private void assertUniqueIdentifiers(RegisteredClient registeredClient, Map 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()); diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java index c4faf0fe..d14919f0 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java @@ -262,15 +262,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)) @@ -357,22 +357,22 @@ public class JdbcRegisteredClientRepository implements RegisteredClientRepositor @Override public List 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 clientAuthenticationMethods = new ArrayList<>( registeredClient.getClientAuthenticationMethods().size()); registeredClient.getClientAuthenticationMethods() - .forEach(clientAuthenticationMethod -> clientAuthenticationMethods + .forEach((clientAuthenticationMethod) -> clientAuthenticationMethods .add(clientAuthenticationMethod.getValue())); List 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()), diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClient.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClient.java index f21e2851..bb5918d7 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClient.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClient.java @@ -40,9 +40,9 @@ import org.springframework.util.StringUtils; * * @author Joe Grandja * @author Anoop Garlapati + * @since 0.0.1 * @see Section 2 * Client Registration - * @since 0.0.1 */ 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)); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientRepository.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientRepository.java index e9045852..66ffdeb7 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientRepository.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientRepository.java @@ -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 { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/OAuth2AuthorizationServerConfiguration.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/OAuth2AuthorizationServerConfiguration.java index 2dbb7b67..3af6b56d 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/OAuth2AuthorizationServerConfiguration.java +++ b/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 { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); } // @formatter:on diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/AuthorizationServerContextFilter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/AuthorizationServerContextFilter.java index 3f7a4f3a..331b6723 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/AuthorizationServerContextFilter.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/AuthorizationServerContextFilter.java @@ -67,7 +67,7 @@ final class AuthorizationServerContextFilter extends OncePerRequestFilter { private static String resolveIssuer(AuthorizationServerSettings authorizationServerSettings, HttpServletRequest request) { - return authorizationServerSettings.getIssuer() != null ? authorizationServerSettings.getIssuer() + return (authorizationServerSettings.getIssuer() != null) ? authorizationServerSettings.getIssuer() : getContextPath(request); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationEndpointConfigurer.java index d2fc4213..595bc797 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationEndpointConfigurer.java @@ -86,6 +86,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OAuth2AuthorizationEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -223,7 +224,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C void addAuthorizationCodeRequestAuthenticationValidator( Consumer authenticationValidator) { - this.authorizationCodeRequestAuthenticationValidator = this.authorizationCodeRequestAuthenticationValidator == null + this.authorizationCodeRequestAuthenticationValidator = (this.authorizationCodeRequestAuthenticationValidator == null) ? authenticationValidator : this.authorizationCodeRequestAuthenticationValidator.andThen(authenticationValidator); } @@ -248,7 +249,7 @@ public final class OAuth2AuthorizationEndpointConfigurer extends AbstractOAuth2C } this.authenticationProvidersConsumer.accept(authenticationProviders); authenticationProviders.forEach( - authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); + (authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); } @Override diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerConfigurer.java index 926d5eb5..bd486b6b 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerConfigurer.java @@ -320,7 +320,7 @@ public final class OAuth2AuthorizationServerConfigurer } List requestMatchers = new ArrayList<>(); - this.configurers.values().forEach(configurer -> { + this.configurers.values().forEach((configurer) -> { configurer.init(httpSecurity); requestMatchers.add(configurer.getRequestMatcher()); }); @@ -341,7 +341,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); @@ -394,7 +394,7 @@ public final class OAuth2AuthorizationServerConfigurer private RequestMatcher getRequestMatcher(Class configurerType) { T configurer = getConfigurer(configurerType); - return configurer != null ? configurer.getRequestMatcher() : null; + return (configurer != null) ? configurer.getRequestMatcher() : null; } private static void validateAuthorizationServerSettings(AuthorizationServerSettings authorizationServerSettings) { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataEndpointConfigurer.java index 55d0b284..f0707ecf 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataEndpointConfigurer.java @@ -44,6 +44,7 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OAuth2AuthorizationServerMetadataEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -66,7 +67,7 @@ public final class OAuth2AuthorizationServerMetadataEndpointConfigurer extends A void addDefaultAuthorizationServerMetadataCustomizer( Consumer defaultAuthorizationServerMetadataCustomizer) { - this.defaultAuthorizationServerMetadataCustomizer = this.defaultAuthorizationServerMetadataCustomizer == null + this.defaultAuthorizationServerMetadataCustomizer = (this.defaultAuthorizationServerMetadataCustomizer == null) ? defaultAuthorizationServerMetadataCustomizer : this.defaultAuthorizationServerMetadataCustomizer .andThen(defaultAuthorizationServerMetadataCustomizer); } @@ -97,9 +98,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; diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientAuthenticationConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientAuthenticationConfigurer.java index 73f63b66..f6ef3819 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientAuthenticationConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientAuthenticationConfigurer.java @@ -79,6 +79,7 @@ public final class OAuth2ClientAuthenticationConfigurer extends AbstractOAuth2Co /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OAuth2ClientAuthenticationConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -193,7 +194,7 @@ public final class OAuth2ClientAuthenticationConfigurer extends AbstractOAuth2Co } this.authenticationProvidersConsumer.accept(authenticationProviders); authenticationProviders.forEach( - authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); + (authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); } @Override diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ConfigurerUtils.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ConfigurerUtils.java index 470e09b8..d51192ee 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ConfigurerUtils.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ConfigurerUtils.java @@ -223,7 +223,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; } } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceAuthorizationEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceAuthorizationEndpointConfigurer.java index 623f6c22..fc03149c 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceAuthorizationEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceAuthorizationEndpointConfigurer.java @@ -76,6 +76,7 @@ public final class OAuth2DeviceAuthorizationEndpointConfigurer extends AbstractO /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OAuth2DeviceAuthorizationEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -206,7 +207,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 diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceVerificationEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceVerificationEndpointConfigurer.java index 79a4adff..cb099a18 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceVerificationEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceVerificationEndpointConfigurer.java @@ -81,6 +81,7 @@ public final class OAuth2DeviceVerificationEndpointConfigurer extends AbstractOA /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OAuth2DeviceVerificationEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -244,7 +245,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 diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenEndpointConfigurer.java index 863150c6..ba4b3cba 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenEndpointConfigurer.java @@ -83,6 +83,7 @@ public final class OAuth2TokenEndpointConfigurer extends AbstractOAuth2Configure /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OAuth2TokenEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -192,7 +193,7 @@ public final class OAuth2TokenEndpointConfigurer extends AbstractOAuth2Configure } this.authenticationProvidersConsumer.accept(authenticationProviders); authenticationProviders.forEach( - authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); + (authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); } @Override diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionEndpointConfigurer.java index fe940056..dce96b4d 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionEndpointConfigurer.java @@ -73,6 +73,7 @@ public final class OAuth2TokenIntrospectionEndpointConfigurer extends AbstractOA /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OAuth2TokenIntrospectionEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -189,7 +190,7 @@ public final class OAuth2TokenIntrospectionEndpointConfigurer extends AbstractOA } this.authenticationProvidersConsumer.accept(authenticationProviders); authenticationProviders.forEach( - authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); + (authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); } @Override diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationEndpointConfigurer.java index 3e0f20e2..3ae15fd7 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationEndpointConfigurer.java @@ -72,6 +72,7 @@ public final class OAuth2TokenRevocationEndpointConfigurer extends AbstractOAuth /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OAuth2TokenRevocationEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -188,7 +189,7 @@ public final class OAuth2TokenRevocationEndpointConfigurer extends AbstractOAuth } this.authenticationProvidersConsumer.accept(authenticationProviders); authenticationProviders.forEach( - authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); + (authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); } @Override diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationEndpointConfigurer.java index 798428f2..32fa5855 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationEndpointConfigurer.java @@ -76,6 +76,7 @@ public final class OidcClientRegistrationEndpointConfigurer extends AbstractOAut /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OidcClientRegistrationEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -201,7 +202,7 @@ public final class OidcClientRegistrationEndpointConfigurer extends AbstractOAut } this.authenticationProvidersConsumer.accept(authenticationProviders); authenticationProviders.forEach( - authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); + (authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); } @Override diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcConfigurer.java index 6464c171..166c3136 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcConfigurer.java +++ b/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 { /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OidcConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -117,7 +118,7 @@ public final class OidcConfigurer extends AbstractOAuth2Configurer { @Override void init(HttpSecurity httpSecurity) { List 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 { }); } - this.configurers.values().forEach(configurer -> configurer.configure(httpSecurity)); + this.configurers.values().forEach((configurer) -> configurer.configure(httpSecurity)); } @Override diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcLogoutEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcLogoutEndpointConfigurer.java index 841491d4..0c21b297 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcLogoutEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcLogoutEndpointConfigurer.java @@ -72,6 +72,7 @@ public final class OidcLogoutEndpointConfigurer extends AbstractOAuth2Configurer /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OidcLogoutEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -175,7 +176,7 @@ public final class OidcLogoutEndpointConfigurer extends AbstractOAuth2Configurer } this.authenticationProvidersConsumer.accept(authenticationProviders); authenticationProviders.forEach( - authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); + (authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); } @Override diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationEndpointConfigurer.java index 1ddfd8d7..f82a1e95 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationEndpointConfigurer.java @@ -44,6 +44,7 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OidcProviderConfigurationEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -66,7 +67,7 @@ public final class OidcProviderConfigurationEndpointConfigurer extends AbstractO void addDefaultProviderConfigurationCustomizer( Consumer defaultProviderConfigurationCustomizer) { - this.defaultProviderConfigurationCustomizer = this.defaultProviderConfigurationCustomizer == null + this.defaultProviderConfigurationCustomizer = (this.defaultProviderConfigurationCustomizer == null) ? defaultProviderConfigurationCustomizer : this.defaultProviderConfigurationCustomizer.andThen(defaultProviderConfigurationCustomizer); } @@ -94,9 +95,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; diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoEndpointConfigurer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoEndpointConfigurer.java index 425d5ea5..355f700e 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoEndpointConfigurer.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoEndpointConfigurer.java @@ -80,6 +80,7 @@ public final class OidcUserInfoEndpointConfigurer extends AbstractOAuth2Configur /** * Restrict for internal use only. + * @param objectPostProcessor an {@code ObjectPostProcessor} */ OidcUserInfoEndpointConfigurer(ObjectPostProcessor objectPostProcessor) { super(objectPostProcessor); @@ -219,7 +220,7 @@ public final class OidcUserInfoEndpointConfigurer extends AbstractOAuth2Configur } this.authenticationProvidersConsumer.accept(authenticationProviders); authenticationProviders.forEach( - authenticationProvider -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); + (authenticationProvider) -> httpSecurity.authenticationProvider(postProcess(authenticationProvider))); } @Override diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/http/converter/HttpMessageConverters.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/http/converter/HttpMessageConverters.java index 864eb7f8..eae99670 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/http/converter/HttpMessageConverters.java +++ b/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; * Utility methods for {@link HttpMessageConverter}'s. * * @author Joe Grandja - * @author luamas + * @author l uamas * @since 0.1.1 */ final class HttpMessageConverters { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistration.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistration.java index a43bd291..f1686afd 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistration.java +++ b/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 /** * Constructs a new {@link Builder} with the provided claims. * @param claims the claims to initialize the builder + * @return the {@link Builder} */ public static Builder withClaims(Map claims) { Assert.notEmpty(claims, "claims cannot be empty"); - return new Builder().claims(c -> c.putAll(claims)); + return new Builder().claims((c) -> c.putAll(claims)); } /** * Helps configure an {@link OidcClientRegistration}. */ - public static class Builder { + public static final class Builder { private final Map claims = new LinkedHashMap<>(); @@ -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()); + this.claims.computeIfAbsent(name, (k) -> new LinkedList()); ((List) this.claims.get(name)).add(value); } @@ -442,7 +443,7 @@ public final class OidcClientRegistration implements OidcClientMetadataClaimAcce private void acceptClaimValues(String name, Consumer> valuesConsumer) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(valuesConsumer, "valuesConsumer cannot be null"); - this.claims.computeIfAbsent(name, k -> new LinkedList()); + this.claims.computeIfAbsent(name, (k) -> new LinkedList()); List values = (List) this.claims.get(name); valuesConsumer.accept(values); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfiguration.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfiguration.java index 0c8a0d59..567dd3c5 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfiguration.java +++ b/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 /** * Constructs a new {@link Builder} with the provided claims. * @param claims the claims to initialize the builder + * @return the {@link Builder} */ public static Builder withClaims(Map claims) { Assert.notEmpty(claims, "claims cannot be empty"); - return new Builder().claims(c -> c.putAll(claims)); + return new Builder().claims((c) -> c.putAll(claims)); } /** * Helps configure an {@link OidcProviderConfiguration}. */ - public static class Builder extends AbstractBuilder { + public static final class Builder extends AbstractBuilder { private Builder() { } @@ -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()); + getClaims().computeIfAbsent(name, (k) -> new LinkedList()); ((List) getClaims().get(name)).add(value); } @@ -199,7 +200,7 @@ public final class OidcProviderConfiguration extends AbstractOAuth2Authorization private void acceptClaimValues(String name, Consumer> valuesConsumer) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(valuesConsumer, "valuesConsumer cannot be null"); - getClaims().computeIfAbsent(name, k -> new LinkedList()); + getClaims().computeIfAbsent(name, (k) -> new LinkedList()); List values = (List) getClaims().get(name); valuesConsumer.accept(values); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProvider.java index 185ccaf0..a77aff5b 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProvider.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProvider.java @@ -427,31 +427,35 @@ public final class OidcClientRegistrationAuthenticationProvider implements Authe 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()) || @@ -460,7 +464,7 @@ public final class OidcClientRegistrationAuthenticationProvider implements Authe } if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) { - builder.scopes(scopes -> + builder.scopes((scopes) -> scopes.addAll(clientRegistration.getScopes())); } @@ -474,7 +478,8 @@ public final class OidcClientRegistrationAuthenticationProvider implements Authe 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; diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProvider.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProvider.java index 19e39087..1e900a82 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProvider.java +++ b/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 } Map requestedClaims = new HashMap<>(claims); - requestedClaims.keySet().removeIf(claimName -> !scopeRequestedClaimNames.contains(claimName)); + requestedClaims.keySet().removeIf((claimName) -> !scopeRequestedClaimNames.contains(claimName)); return requestedClaims; } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/RegisteredClientOidcClientRegistrationConverter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/RegisteredClientOidcClientRegistrationConverter.java index a98e5e9d..b54c4ece 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/RegisteredClientOidcClientRegistrationConverter.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/RegisteredClientOidcClientRegistrationConverter.java @@ -46,16 +46,16 @@ 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)) { @@ -63,7 +63,7 @@ final class RegisteredClientOidcClientRegistrationConverter } if (!CollectionUtils.isEmpty(registeredClient.getScopes())) { - builder.scopes(scopes -> + builder.scopes((scopes) -> scopes.addAll(registeredClient.getScopes())); } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/HttpMessageConverters.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/HttpMessageConverters.java index 1ba662f3..12bc8a91 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/HttpMessageConverters.java +++ b/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; * Utility methods for {@link HttpMessageConverter}'s. * * @author Joe Grandja - * @author luamas + * @author l uamas * @since 0.1.0 */ final class HttpMessageConverters { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverter.java index 234db461..2a0ceff3 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverter.java +++ b/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 } private static Converter 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) { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilter.java index 3fd7bc9d..88b32848 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilter.java +++ b/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 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 * {@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"); diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AbstractSettings.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AbstractSettings.java index 53638bf0..34b8720d 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AbstractSettings.java +++ b/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 { /** * A builder for subclasses of {@link AbstractSettings}. + * + * @param the type of object + * @param the type of the builder */ - protected static abstract class AbstractBuilder> { + protected abstract static class AbstractBuilder> { private final Map settings = new HashMap<>(); diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettings.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettings.java index 98860965..d481d5fc 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettings.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettings.java @@ -156,13 +156,13 @@ public final class AuthorizationServerSettings extends AbstractSettings { */ public static Builder withSettings(Map 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 { + public static final class Builder extends AbstractBuilder { private Builder() { } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettings.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettings.java index d60762a4..f6649829 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettings.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettings.java @@ -95,13 +95,13 @@ public final class ClientSettings extends AbstractSettings { */ public static Builder withSettings(Map 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 { + public static final class Builder extends AbstractBuilder { private Builder() { } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettings.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettings.java index 67f29f2c..f5156f68 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettings.java +++ b/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 { * 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); @@ -121,13 +123,13 @@ public final class TokenSettings extends AbstractSettings { */ public static Builder withSettings(Map 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 { + public static final class Builder extends AbstractBuilder { private Builder() { } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/JwtGenerator.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/JwtGenerator.java index 2889ca72..7b5b8aee 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/JwtGenerator.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/JwtGenerator.java @@ -122,7 +122,8 @@ public final class JwtGenerator implements OAuth2TokenGenerator { 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( @@ -136,7 +137,8 @@ public final class JwtGenerator implements OAuth2TokenGenerator { 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")); diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSet.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSet.java index b7e56c82..c168b808 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSet.java +++ b/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 { * 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> claimsConsumer) { claimsConsumer.accept(this.claims); diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenCustomizer.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenCustomizer.java index c76603d2..4403e7b2 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenCustomizer.java +++ b/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; * Implementations of this interface are responsible for customizing the OAuth 2.0 Token * attributes contained within the {@link OAuth2TokenContext}. * + * @param the type of the context containing the OAuth 2.0 Token attributes * @author Joe Grandja * @since 0.1.0 * @see OAuth2TokenContext - * @param the type of the context containing the OAuth 2.0 Token attributes */ @FunctionalInterface public interface OAuth2TokenCustomizer { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenGenerator.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenGenerator.java index eda7502e..f4fe0466 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenGenerator.java +++ b/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 * Implementations of this interface are responsible for generating an {@link OAuth2Token} * using the attributes contained in the {@link OAuth2TokenContext}. * + * @param the type of the OAuth 2.0 Token * @author Joe Grandja * @since 0.2.3 * @see OAuth2Token * @see OAuth2TokenContext * @see OAuth2TokenClaimsSet * @see ClaimAccessor - * @param the type of the OAuth 2.0 Token */ @FunctionalInterface public interface OAuth2TokenGenerator { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/DefaultConsentPage.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/DefaultConsentPage.java index 7bb0a515..bc11f5fd 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/DefaultConsentPage.java +++ b/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; /** * 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); diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilter.java index 9cbf87ba..feec0e1f 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilter.java +++ b/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; 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; diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilter.java index 76bb5d0a..d3f609e4 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilter.java +++ b/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 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, diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilter.java index ca700d45..d920356d 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilter.java +++ b/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 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), diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilter.java index d36a589f..5134a993 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilter.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilter.java @@ -53,12 +53,12 @@ import org.springframework.web.filter.OncePerRequestFilter; * @author Gerardo Roza * @author Joe Grandja * @author Gaurav Tiwari + * @since 0.1.1 * @see OAuth2TokenIntrospectionAuthenticationProvider * @see Section 2 * Introspection Endpoint * @see Section * 2.1 Introspection Request - * @since 0.1.1 */ public final class OAuth2TokenIntrospectionEndpointFilter extends OncePerRequestFilter { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilter.java index 8e65f199..d9cf5eb5 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilter.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilter.java @@ -51,12 +51,12 @@ import org.springframework.web.filter.OncePerRequestFilter; * @author Vivek Babu * @author Joe Grandja * @author Arfat Chaus + * @since 0.0.3 * @see OAuth2TokenRevocationAuthenticationProvider * @see Section 2 * Token Revocation * @see Section * 2.1 Revocation Request - * @since 0.0.3 */ public final class OAuth2TokenRevocationEndpointFilter extends OncePerRequestFilter { diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2AuthorizationCodeRequestAuthenticationConverter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2AuthorizationCodeRequestAuthenticationConverter.java index 73832583..d54442b0 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2AuthorizationCodeRequestAuthenticationConverter.java +++ b/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 } 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); }; From 00e7d6703dd5a4897bf3a2983922fa2b15df0210 Mon Sep 17 00:00:00 2001 From: Joe Grandja <10884212+jgrandja@users.noreply.github.com> Date: Sun, 19 May 2024 07:33:12 -0400 Subject: [PATCH 3/5] Fix checkstyle violations for test module Issue gh-1624 --- ...Auth2AuthorizationConsentServiceTests.java | 36 ++- .../JdbcOAuth2AuthorizationServiceTests.java | 269 ++++++++---------- .../OAuth2AuthorizationConsentTests.java | 2 +- ...Auth2AuthorizationServerMetadataTests.java | 18 +- .../TestOAuth2Authorizations.java | 5 +- ...ientSecretAuthenticationProviderTests.java | 90 +++--- ...tAssertionAuthenticationProviderTests.java | 54 ++-- ...JwtClientAssertionDecoderFactoryTests.java | 12 +- ...h2AccessTokenAuthenticationTokenTests.java | 10 +- ...zationCodeAuthenticationProviderTests.java | 118 ++++---- ...odeRequestAuthenticationProviderTests.java | 156 +++++----- ...tionConsentAuthenticationContextTests.java | 2 +- ...ionConsentAuthenticationProviderTests.java | 158 +++++----- ...redentialsAuthenticationProviderTests.java | 22 +- ...ionConsentAuthenticationProviderTests.java | 67 +++-- ...ionRequestAuthenticationProviderTests.java | 18 +- ...DeviceCodeAuthenticationProviderTests.java | 62 ++-- ...rificationAuthenticationProviderTests.java | 40 +-- ...freshTokenAuthenticationProviderTests.java | 100 +++---- ...rospectionAuthenticationProviderTests.java | 30 +- ...RevocationAuthenticationProviderTests.java | 18 +- ...blicClientAuthenticationProviderTests.java | 84 +++--- .../JdbcRegisteredClientRepositoryTests.java | 8 +- .../client/RegisteredClientTests.java | 95 +++---- .../client/TestRegisteredClients.java | 5 +- ...RegisterMissingBeanPostProcessorTests.java | 2 +- .../web/configurers/JwkSetTests.java | 4 +- .../OAuth2AuthorizationCodeGrantTests.java | 66 ++--- ...Auth2AuthorizationServerMetadataTests.java | 12 +- .../OAuth2ClientCredentialsGrantTests.java | 41 ++- .../OAuth2DeviceCodeGrantTests.java | 6 +- .../OAuth2RefreshTokenGrantTests.java | 6 +- .../OAuth2TokenIntrospectionTests.java | 20 +- .../OAuth2TokenRevocationTests.java | 20 +- .../OidcClientRegistrationTests.java | 75 ++--- .../OidcProviderConfigurationTests.java | 12 +- .../annotation/web/configurers/OidcTests.java | 14 +- .../web/configurers/OidcUserInfoTests.java | 46 +-- .../TestAuthorizationServerContext.java | 2 +- ...rverMetadataHttpMessageConverterTests.java | 4 +- ...ntrospectionHttpMessageConverterTests.java | 4 +- .../oidc/OidcClientRegistrationTests.java | 10 +- .../oidc/OidcProviderConfigurationTests.java | 16 +- ...figurationAuthenticationProviderTests.java | 56 ++-- ...gistrationAuthenticationProviderTests.java | 92 +++--- ...OidcLogoutAuthenticationProviderTests.java | 124 ++++---- ...dcUserInfoAuthenticationProviderTests.java | 30 +- ...RegistrationHttpMessageConverterTests.java | 56 ++-- ...onfigurationHttpMessageConverterTests.java | 4 +- ...OidcUserInfoHttpMessageConverterTests.java | 4 +- ...ClientRegistrationEndpointFilterTests.java | 27 +- .../web/OidcLogoutEndpointFilterTests.java | 33 ++- ...viderConfigurationEndpointFilterTests.java | 1 - .../web/OidcUserInfoEndpointFilterTests.java | 19 +- .../AuthorizationServerSettingsTests.java | 2 +- .../settings/ClientSettingsTests.java | 2 +- .../settings/TokenSettingsTests.java | 2 +- .../authorization/test/SpringTestContext.java | 8 +- .../DelegatingOAuth2TokenGeneratorTests.java | 4 +- .../token/JwtEncodingContextTests.java | 2 +- .../token/OAuth2TokenClaimsContextTests.java | 2 +- .../token/OAuth2TokenClaimsSetTests.java | 4 +- .../web/NimbusJwkSetEndpointFilterTests.java | 7 +- ...Auth2AuthorizationEndpointFilterTests.java | 101 ++++--- ...tionServerMetadataEndpointFilterTests.java | 1 - ...OAuth2ClientAuthenticationFilterTests.java | 33 +-- ...eviceAuthorizationEndpointFilterTests.java | 32 +-- ...DeviceVerificationEndpointFilterTests.java | 39 ++- .../web/OAuth2TokenEndpointFilterTests.java | 32 ++- ...TokenIntrospectionEndpointFilterTests.java | 15 +- ...th2TokenRevocationEndpointFilterTests.java | 21 +- ...cretBasicAuthenticationConverterTests.java | 6 +- ...ecretPostAuthenticationConverterTests.java | 4 +- ...AssertionAuthenticationConverterTests.java | 2 +- ...onConsentAuthenticationConverterTests.java | 7 +- ...onRequestAuthenticationConverterTests.java | 7 +- ...eviceCodeAuthenticationConverterTests.java | 7 +- ...ificationAuthenticationConverterTests.java | 7 +- ...licClientAuthenticationConverterTests.java | 6 +- 79 files changed, 1320 insertions(+), 1318 deletions(-) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentServiceTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentServiceTests.java index de6c4868..f104c905 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentServiceTests.java +++ b/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; 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 { 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 { 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 { @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 { 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 { @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 { @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(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationServiceTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationServiceTests.java index 37052d06..ff9b69ab 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationServiceTests.java +++ b/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; 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 { @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 { @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 authorizationRowMapper = spy( - new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper( - this.registeredClientRepository)); + new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper(this.registeredClientRepository)); this.authorizationService.setAuthorizationRowMapper(authorizationRowMapper); Function> 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 { @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 { @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 { @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 { @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 { @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 { @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 { @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 { @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 { @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 { @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(); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java index 53080165..256ba86a 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java @@ -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")); }) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataTests.java index af59e98a..b8961137 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataTests.java @@ -294,7 +294,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"); }) @@ -332,7 +332,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"); }) @@ -370,7 +370,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"); }) @@ -382,8 +382,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"); @@ -410,7 +410,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"); }) @@ -450,7 +450,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"); }) @@ -492,7 +492,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"); }) @@ -525,7 +525,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"); }) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/TestOAuth2Authorizations.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/TestOAuth2Authorizations.java index eee09c21..bc8d17fa 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/TestOAuth2Authorizations.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/TestOAuth2Authorizations.java @@ -36,7 +36,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()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProviderTests.java index bfd3506d..4d41cf99 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProviderTests.java +++ b/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; 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 { @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 { @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 { @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 { @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 { 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 { @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 { @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 { @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 { @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 parameters = createPkceTokenParameters(S256_CODE_VERIFIER); parameters.put(OAuth2ParameterNames.CODE, "invalid-code"); @@ -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 { @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 parameters = createAuthorizationCodeTokenParameters(); @@ -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 { @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 parameters = createPkceTokenParameters(S256_CODE_VERIFIER); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProviderTests.java index d2179944..b9cb6c66 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProviderTests.java +++ b/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; 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 { .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 { @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 { .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 { ) .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 { 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 { ) .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 { 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 { ) .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 { ) .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 parameters = createPkceTokenParameters(S256_CODE_VERIFIER); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactoryTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactoryTests.java index d44777da..8c543f46 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactoryTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactoryTests.java @@ -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 { 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 { 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() diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationTokenTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationTokenTests.java index ee6be4cd..f95a55d3 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationTokenTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationTokenTests.java @@ -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; 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; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java index e302f645..3a928980 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java @@ -83,13 +83,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}. @@ -187,7 +187,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); } @@ -202,7 +202,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); } @@ -216,7 +216,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); } @@ -224,8 +224,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, @@ -234,7 +234,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); @@ -250,8 +250,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()); @@ -261,7 +261,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); } @@ -275,8 +275,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()); @@ -287,7 +287,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); @@ -308,8 +308,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()); @@ -320,7 +320,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); @@ -336,8 +336,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()); @@ -348,7 +348,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); } @@ -357,8 +357,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()); @@ -367,7 +367,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; @@ -375,12 +375,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."); }); @@ -390,8 +390,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { public void authenticateWhenRefreshTokenNotGeneratedThenThrowOAuth2AuthenticationException() { 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()); @@ -400,9 +400,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 null; @@ -410,12 +410,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 refresh token."); @@ -426,8 +426,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()); @@ -436,9 +436,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; @@ -446,12 +446,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."); }); @@ -461,8 +461,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()); @@ -471,7 +471,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); @@ -526,8 +526,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()); @@ -536,7 +536,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()); @@ -547,7 +547,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); @@ -620,8 +620,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); @@ -630,7 +630,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); @@ -688,8 +688,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()); @@ -700,7 +700,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); @@ -729,12 +729,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()); @@ -743,7 +743,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); @@ -761,8 +761,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()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProviderTests.java index 4fac15c6..3fddd987 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProviderTests.java @@ -54,9 +54,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}. @@ -147,11 +147,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)); } @@ -159,14 +159,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)); } @@ -174,28 +174,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)); } @@ -205,10 +205,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 @@ -224,10 +224,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 @@ -242,14 +242,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)); } @@ -257,14 +257,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)); } @@ -274,15 +274,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())); } @@ -290,15 +290,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())); } @@ -307,15 +307,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())); } @@ -323,18 +323,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 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())); } @@ -343,17 +343,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 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())); } @@ -361,13 +361,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 @@ -382,12 +382,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 @@ -428,17 +428,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 @@ -453,19 +453,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 @@ -478,15 +478,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 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 @@ -499,8 +499,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 authorizationCodeGenerator = mock(OAuth2TokenGenerator.class); @@ -508,13 +508,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."); @@ -524,8 +524,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 authenticationValidator = mock(Consumer.class); @@ -533,7 +533,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 diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContextTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContextTests.java index 43887dd4..af745991 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContextTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContextTests.java @@ -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.getAuthentication()).isEqualTo(this.authorizationConsentAuthentication); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProviderTests.java index a2687abf..cb51847e 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProviderTests.java +++ b/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; 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 { 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 { .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 { .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 { 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 { Set 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 { @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 { .getAttribute(OAuth2AuthorizationRequest.class.getName()); Set 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 { @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 { .getAttribute(OAuth2AuthorizationRequest.class.getName()); Set 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 authorizationConsentCustomizer = mock(Consumer.class); @@ -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 { 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 { 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 { .getAttribute(OAuth2AuthorizationRequest.class.getName()); Set 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 { 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); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProviderTests.java index 076d541c..1029dd7f 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProviderTests.java @@ -59,11 +59,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}. @@ -151,7 +151,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); } @@ -167,7 +167,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 { @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()); @@ -184,7 +184,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); } @@ -199,7 +199,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); } @@ -213,7 +213,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); @@ -228,7 +228,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); @@ -247,8 +247,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."); }); @@ -262,7 +262,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); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProviderTests.java index 8f279d9d..86e900af 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProviderTests.java +++ b/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; 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 { .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 { 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 { .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 { 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 { .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 { 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 { // @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 { 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 { // @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 { .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 { // @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 { 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 { // @formatter:on ArgumentCaptor 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 { 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 { assertThat(authenticationResult.getUserCode()).isEqualTo(USER_CODE); ArgumentCaptor 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 { 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 { ArgumentCaptor 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 { 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 { ArgumentCaptor 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()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProviderTests.java index 3719da77..81b038f6 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProviderTests.java +++ b/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; 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 { public void authenticateWhenDeviceCodeIsNullThenThrowOAuth2AuthenticationException() { @SuppressWarnings("unchecked") OAuth2TokenGenerator 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 { public void authenticateWhenUserCodeIsNullThenThrowOAuth2AuthenticationException() { @SuppressWarnings("unchecked") OAuth2TokenGenerator 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 { public void authenticateWhenDeviceCodeGeneratorSetThenUsed() { @SuppressWarnings("unchecked") OAuth2TokenGenerator 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 { assertThat(tokenContext.getAuthorizationServerContext()).isNotNull(); assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.DEVICE_CODE); assertThat(tokenContext.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 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 { assertThat(tokenContext.getAuthorizationServerContext()).isNotNull(); assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.DEVICE_CODE); assertThat(tokenContext.getAuthorizationGrant()).isEqualTo(authentication); - assertThat(tokenContext.getTokenType()).isEqualTo(USER_CODE_TOKEN_TYPE); + assertThat(tokenContext.getTokenType()) + .isEqualTo(OAuth2DeviceAuthorizationRequestAuthenticationProvider.USER_CODE_TOKEN_TYPE); } private static void mockAuthorizationServerContext() { diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProviderTests.java index ac445ff5..0c37bb16 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProviderTests.java +++ b/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; 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 { 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 { .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 { 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 { // @formatter:on ArgumentCaptor 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 { 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 { .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 { .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 { .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 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 { .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 { .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 { .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 { .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 { .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 { .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 { .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 { ArgumentCaptor authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class); ArgumentCaptor 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); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProviderTests.java index 3e97029d..a0f3d12b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProviderTests.java +++ b/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; 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 { @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 { .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 { 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 { .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 { assertThat(authenticationResult.getScopes()).isEmpty(); ArgumentCaptor 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 { .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 { assertThat(authenticationResult.getUserCode()).isEqualTo(USER_CODE); ArgumentCaptor 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 { .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 { assertThat(authenticationResult.getScopes()).containsExactly("previous"); ArgumentCaptor 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()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProviderTests.java index 311f78ab..beb2b00a 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProviderTests.java @@ -73,12 +73,12 @@ 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.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2RefreshTokenAuthenticationProvider}. @@ -106,7 +106,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void setUp() { this.authorizationService = mock(OAuth2AuthorizationService.class); this.jwtEncoder = mock(JwtEncoder.class); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt(Collections.singleton("scope1"))); + given(this.jwtEncoder.encode(any())).willReturn(createJwt(Collections.singleton("scope1"))); this.jwtCustomizer = mock(OAuth2TokenCustomizer.class); JwtGenerator jwtGenerator = new JwtGenerator(this.jwtEncoder); jwtGenerator.setJwtCustomizer(this.jwtCustomizer); @@ -165,9 +165,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void authenticateWhenValidRefreshTokenThenReturnAccessToken() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -222,9 +222,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .token(authorizedIdToken) .build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -296,9 +296,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { .tokenSettings(TokenSettings.builder().reuseRefreshTokens(false).build()) .build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -324,9 +324,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { .scope("scope3") .build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -346,9 +346,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void authenticateWhenRequestedScopesNotAuthorizedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -360,7 +360,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_SCOPE); } @@ -375,7 +375,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -390,7 +390,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -406,7 +406,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -415,9 +415,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void authenticateWhenRefreshTokenIssuedToAnotherClientThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); RegisteredClient registeredClient2 = TestRegisteredClients.registeredClient2().build(); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient2, @@ -427,7 +427,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -435,12 +435,12 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { @Test public void authenticateWhenClientNotAuthorizedToRefreshTokenThenThrowOAuth2AuthenticationException() { 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.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -449,7 +449,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT); } @@ -461,9 +461,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { OAuth2RefreshToken expiredRefreshToken = new OAuth2RefreshToken("expired-refresh-token", Instant.now().minusSeconds(120), Instant.now().minusSeconds(60)); authorization = OAuth2Authorization.from(authorization).token(expiredRefreshToken).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -472,7 +472,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -485,9 +485,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .token(refreshToken, (metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true)) .build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -496,7 +496,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -505,16 +505,16 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void authenticateWhenAccessTokenNotGeneratedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); - doAnswer(answer -> { + willAnswer((answer) -> { OAuth2TokenContext context = answer.getArgument(0); if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) { return null; @@ -522,12 +522,12 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { 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."); }); @@ -539,16 +539,16 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { .tokenSettings(TokenSettings.builder().reuseRefreshTokens(false).build()) .build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); - doAnswer(answer -> { + willAnswer((answer) -> { OAuth2TokenContext context = answer.getArgument(0); if (OAuth2TokenType.REFRESH_TOKEN.equals(context.getTokenType())) { return null; @@ -556,12 +556,12 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { 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 refresh token."); @@ -572,16 +572,16 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void authenticateWhenIdTokenNotGeneratedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); - doAnswer(answer -> { + willAnswer((answer) -> { OAuth2TokenContext context = answer.getArgument(0); if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) { return null; @@ -589,12 +589,12 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { 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."); }); @@ -610,9 +610,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { .build(); // @formatter:on OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProviderTests.java index 95c9d848..3ff0b62f 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProviderTests.java @@ -46,9 +46,9 @@ 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.ArgumentMatchers.isNull; +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 OAuth2TokenIntrospectionAuthenticationProvider}. @@ -103,7 +103,7 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -120,7 +120,7 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -148,8 +148,8 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, accessToken); - when(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -174,8 +174,8 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .token(accessToken) .build(); - when(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -202,8 +202,8 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, accessToken, accessTokenClaims) .build(); - when(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -243,9 +243,9 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(authorizedClient, accessToken, claimsSet.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorizedClient.getId()))).thenReturn(authorizedClient); + given(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorizedClient.getId()))).willReturn(authorizedClient); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -278,9 +278,9 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { RegisteredClient authorizedClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization().build(); OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken(); - when(this.authorizationService.findByToken(eq(refreshToken.getTokenValue()), isNull())) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorizedClient.getId()))).thenReturn(authorizedClient); + given(this.authorizationService.findByToken(eq(refreshToken.getTokenValue()), isNull())) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorizedClient.getId()))).willReturn(authorizedClient); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProviderTests.java index e1560cde..27f77748 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProviderTests.java @@ -37,10 +37,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; +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 OAuth2TokenRevocationAuthenticationProvider}. @@ -81,7 +81,7 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { clientPrincipal, OAuth2TokenType.ACCESS_TOKEN.getValue()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -96,7 +96,7 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { clientPrincipal, OAuth2TokenType.ACCESS_TOKEN.getValue()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -120,7 +120,7 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(TestRegisteredClients.registeredClient2().build()) .build(); - when(this.authorizationService.findByToken(eq("token"), isNull())).thenReturn(authorization); + given(this.authorizationService.findByToken(eq("token"), isNull())).willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -129,7 +129,7 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -138,9 +138,9 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { public void authenticateWhenValidRefreshTokenThenRevoked() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), isNull())) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -166,9 +166,9 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { public void authenticateWhenValidAccessTokenThenRevoked() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getAccessToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getAccessToken().getToken().getTokenValue()), isNull())) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/PublicClientAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/PublicClientAuthenticationProviderTests.java index 062043f0..36095a7d 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/PublicClientAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/PublicClientAuthenticationProviderTests.java @@ -38,8 +38,8 @@ import org.springframework.security.oauth2.server.authorization.client.TestRegis 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.when; /** * Tests for {@link PublicClientAuthenticationProvider}. @@ -95,15 +95,15 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenInvalidClientIdThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().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.NONE, 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(OAuth2ParameterNames.CLIENT_ID); }); @@ -112,15 +112,15 @@ public class PublicClientAuthenticationProviderTests { @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.NONE, 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("authentication_method"); }); @@ -129,14 +129,14 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenInvalidCodeThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().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 parameters = createPkceTokenParameters(S256_CODE_VERIFIER); parameters.put(OAuth2ParameterNames.CODE, "invalid-code"); @@ -146,8 +146,8 @@ public class PublicClientAuthenticationProviderTests { 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); }); @@ -156,12 +156,12 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenMissingCodeChallengeThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); 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); Map parameters = createPkceTokenParameters(S256_CODE_VERIFIER); @@ -170,8 +170,8 @@ public class PublicClientAuthenticationProviderTests { 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_CHALLENGE); }); @@ -180,14 +180,14 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenMissingCodeVerifierThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().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 parameters = createAuthorizationCodeTokenParameters(); @@ -196,8 +196,8 @@ public class PublicClientAuthenticationProviderTests { 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); }); @@ -206,14 +206,14 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenS256MethodAndInvalidCodeVerifierThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().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 parameters = createPkceTokenParameters("invalid-code-verifier"); @@ -222,8 +222,8 @@ public class PublicClientAuthenticationProviderTests { 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); }); @@ -232,14 +232,14 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenS256MethodAndValidCodeVerifierThenAuthenticated() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().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 parameters = createPkceTokenParameters(S256_CODE_VERIFIER); @@ -257,8 +257,8 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenUnsupportedCodeChallengeMethodThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); Map authorizationRequestAdditionalParameters = createPkceAuthorizationParametersS256(); // This should never happen: the Authorization endpoint should not allow it @@ -267,8 +267,8 @@ public class PublicClientAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, authorizationRequestAdditionalParameters) .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 parameters = createPkceTokenParameters(S256_CODE_VERIFIER); @@ -277,7 +277,7 @@ public class PublicClientAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepositoryTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepositoryTests.java index 2b46f1c7..e5d8c795 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepositoryTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepositoryTests.java @@ -374,15 +374,15 @@ public class JdbcRegisteredClientRepositoryTests { // @formatter:off RegisteredClient.Builder builder = RegisteredClient.withId(rs.getString("id")) .clientId(rs.getString("clientId")) - .clientIdIssuedAt(clientIdIssuedAt != null ? clientIdIssuedAt.toInstant() : null) + .clientIdIssuedAt((clientIdIssuedAt != null) ? clientIdIssuedAt.toInstant() : null) .clientSecret(rs.getString("clientSecret")) - .clientSecretExpiresAt(clientSecretExpiresAt != null ? clientSecretExpiresAt.toInstant() : null) + .clientSecretExpiresAt((clientSecretExpiresAt != null) ? clientSecretExpiresAt.toInstant() : null) .clientName(rs.getString("clientName")) .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)) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientTests.java index 91d36e33..c7c75942 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientTests.java @@ -59,8 +59,8 @@ public class RegisteredClientTests { assertThatThrownBy(() -> RegisteredClient.withId(ID) .clientId(CLIENT_ID) .clientSecret(CLIENT_SECRET) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -77,9 +77,10 @@ public class RegisteredClientTests { .clientName("client-name") .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .postLogoutRedirectUris(postLogoutRedirectUris -> postLogoutRedirectUris.addAll(POST_LOGOUT_REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .postLogoutRedirectUris( + (postLogoutRedirectUris) -> postLogoutRedirectUris.addAll(POST_LOGOUT_REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getId()).isEqualTo(ID); @@ -108,8 +109,8 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -120,7 +121,7 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .scopes(scopes -> scopes.addAll(SCOPES)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -133,7 +134,7 @@ public class RegisteredClientTests { .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .redirectUri("https://example.com") .redirectUris(Set::clear) - .scopes(scopes -> scopes.addAll(SCOPES)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -143,8 +144,8 @@ public class RegisteredClientTests { .clientId(CLIENT_ID) .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getClientAuthenticationMethods()) @@ -158,7 +159,7 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) .build(); } @@ -169,8 +170,8 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getScopes()).isEqualTo(SCOPES); @@ -182,7 +183,7 @@ public class RegisteredClientTests { .clientId(CLIENT_ID) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) .scope("openid profile") .build()).isInstanceOf(IllegalArgumentException.class); } @@ -194,7 +195,7 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) .scope("an\"invalid\"scope") .build()).isInstanceOf(IllegalArgumentException.class); } @@ -207,7 +208,7 @@ public class RegisteredClientTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .redirectUri("invalid URI") - .scopes(scopes -> scopes.addAll(SCOPES)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -219,7 +220,7 @@ public class RegisteredClientTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .redirectUri("https://example.com/page#fragment") - .scopes(scopes -> scopes.addAll(SCOPES)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -230,7 +231,7 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) .postLogoutRedirectUri("invalid URI") .build()).isInstanceOf(IllegalArgumentException.class); } @@ -244,7 +245,7 @@ public class RegisteredClientTests { .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .redirectUri("https://example.com") .postLogoutRedirectUri("https://example.com/index#fragment") - .scopes(scopes -> scopes.addAll(SCOPES)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -256,8 +257,8 @@ public class RegisteredClientTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getAuthorizationGrantTypes()).containsExactlyInAnyOrder( @@ -269,13 +270,13 @@ public class RegisteredClientTests { RegisteredClient registration = RegisteredClient.withId(ID) .clientId(CLIENT_ID) .clientSecret(CLIENT_SECRET) - .authorizationGrantTypes(authorizationGrantTypes -> { + .authorizationGrantTypes((authorizationGrantTypes) -> { authorizationGrantTypes.add(AuthorizationGrantType.AUTHORIZATION_CODE); authorizationGrantTypes.add(AuthorizationGrantType.CLIENT_CREDENTIALS); }) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getAuthorizationGrantTypes()).containsExactlyInAnyOrder( @@ -284,17 +285,15 @@ public class RegisteredClientTests { @Test public void buildWhenAuthorizationGrantTypesConsumerClearsSetThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> { - RegisteredClient.withId(ID) - .clientId(CLIENT_ID) - .clientSecret(CLIENT_SECRET) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .authorizationGrantTypes(Set::clear) - .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) - .build(); - }).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RegisteredClient.withId(ID) + .clientId(CLIENT_ID) + .clientSecret(CLIENT_SECRET) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .authorizationGrantTypes(Set::clear) + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) + .build()).isInstanceOf(IllegalArgumentException.class); } @Test @@ -305,8 +304,8 @@ public class RegisteredClientTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getClientAuthenticationMethods()).containsExactlyInAnyOrder( @@ -319,12 +318,12 @@ public class RegisteredClientTests { .clientId(CLIENT_ID) .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .clientAuthenticationMethods(clientAuthenticationMethods -> { + .clientAuthenticationMethods((clientAuthenticationMethods) -> { clientAuthenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_BASIC); clientAuthenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_POST); }) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getClientAuthenticationMethods()).containsExactlyInAnyOrder( @@ -340,8 +339,8 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getId()).isEqualTo(overriddenId); @@ -385,15 +384,15 @@ public class RegisteredClientTests { RegisteredClient updated = RegisteredClient.from(registration) .clientName(newName) .clientSecret(newSecret) - .scopes(scopes -> { + .scopes((scopes) -> { scopes.clear(); scopes.add(newScope); }) - .redirectUris(redirectUris -> { + .redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add(newRedirectUri); }) - .postLogoutRedirectUris(postLogoutRedirectUris -> { + .postLogoutRedirectUris((postLogoutRedirectUris) -> { postLogoutRedirectUris.clear(); postLogoutRedirectUris.add(newPostLogoutRedirectUri); }) @@ -420,8 +419,8 @@ public class RegisteredClientTests { .clientName("client-name") .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.NONE) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getId()).isEqualTo(ID); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/TestRegisteredClients.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/TestRegisteredClients.java index 208f0ccb..e08851d3 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/TestRegisteredClients.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/TestRegisteredClients.java @@ -25,7 +25,10 @@ import org.springframework.security.oauth2.server.authorization.settings.ClientS /** * @author Anoop Garlapati */ -public class TestRegisteredClients { +public final class TestRegisteredClients { + + private TestRegisteredClients() { + } public static RegisteredClient.Builder registeredClient() { return RegisteredClient.withId("registration-1") diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/RegisterMissingBeanPostProcessorTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/RegisterMissingBeanPostProcessorTests.java index 7cada95e..e637698f 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/RegisterMissingBeanPostProcessorTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/RegisterMissingBeanPostProcessorTests.java @@ -104,7 +104,7 @@ public class RegisterMissingBeanPostProcessorTests { } private String getField() { - return field; + return this.field; } } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/JwkSetTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/JwkSetTests.java index 51d19c9e..677c13d9 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/JwkSetTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/JwkSetTests.java @@ -93,8 +93,8 @@ public class JwkSetTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationCodeGrantTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationCodeGrantTests.java index 9e18413a..7b00e671 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationCodeGrantTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationCodeGrantTests.java @@ -134,12 +134,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; 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.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -259,9 +259,9 @@ public class OAuth2AuthorizationCodeGrantTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_authorization_consent"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_authorization_consent"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -311,7 +311,7 @@ public class OAuth2AuthorizationCodeGrantTests { } private void assertAuthorizationRequestRedirectsToClient(String authorizationEndpointUri) throws Exception { - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris(redirectUris -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add("https://example.com/callback-1?param=encoded%20parameter%20value"); // gh-1011 }).build(); @@ -499,7 +499,7 @@ public class OAuth2AuthorizationCodeGrantTests { this.spring.register(AuthorizationServerConfiguration.class).autowire(); String redirectUri = "https://example.com/callback-1?param=encoded%20parameter%20value"; - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris(redirectUris -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add(redirectUri); }).clientSettings(ClientSettings.builder().requireProofKey(true).build()).build(); @@ -576,7 +576,7 @@ public class OAuth2AuthorizationCodeGrantTests { public void requestWhenRequiresConsentThenDisplaysConsentPage() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); @@ -601,7 +601,7 @@ public class OAuth2AuthorizationCodeGrantTests { public void requestWhenConsentRequestThenReturnAccessTokenResponse() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); @@ -658,7 +658,7 @@ public class OAuth2AuthorizationCodeGrantTests { public void requestWhenCustomConsentPageConfiguredThenRedirect() throws Exception { this.spring.register(AuthorizationServerConfigurationCustomConsentPage.class).autowire(); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); @@ -739,7 +739,7 @@ public class OAuth2AuthorizationCodeGrantTests { .andExpect(jsonPath("$.access_token").value(new AssertionMatcher() { @Override public void assertion(String accessToken) throws AssertionError { - Jwt jwt = jwtDecoder.decode(accessToken); + Jwt jwt = OAuth2AuthorizationCodeGrantTests.this.jwtDecoder.decode(accessToken); assertThat(jwt.getClaimAsStringList(AUTHORITIES_CLAIM)).containsExactlyInAnyOrder("authority-1", "authority-2"); } @@ -763,11 +763,11 @@ public class OAuth2AuthorizationCodeGrantTests { "https://provider.com/oauth2/authorize", registeredClient.getClientId(), principal, authorizationCode, registeredClient.getRedirectUris().iterator().next(), STATE_URL_UNENCODED, registeredClient.getScopes()); - when(authorizationRequestConverter.convert(any())).thenReturn(authorizationCodeRequestAuthenticationResult); - when(authorizationRequestAuthenticationProvider - .supports(eq(OAuth2AuthorizationCodeRequestAuthenticationToken.class))).thenReturn(true); - when(authorizationRequestAuthenticationProvider.authenticate(any())) - .thenReturn(authorizationCodeRequestAuthenticationResult); + given(authorizationRequestConverter.convert(any())).willReturn(authorizationCodeRequestAuthenticationResult); + given(authorizationRequestAuthenticationProvider + .supports(eq(OAuth2AuthorizationCodeRequestAuthenticationToken.class))).willReturn(true); + given(authorizationRequestAuthenticationProvider.authenticate(any())) + .willReturn(authorizationCodeRequestAuthenticationResult); this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI).params(getAuthorizationRequestParameters(registeredClient)) @@ -940,7 +940,7 @@ public class OAuth2AuthorizationCodeGrantTests { @Bean OAuth2TokenCustomizer jwtCustomizer() { - return context -> { + return (context) -> { if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(context.getAuthorizationGrantType()) && OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) { Authentication principal = context.getPrincipal(); @@ -985,18 +985,18 @@ public class OAuth2AuthorizationCodeGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher(); http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .securityContext(securityContext -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .securityContext((securityContext) -> securityContext.securityContextRepository(securityContextRepository)) .apply(authorizationServerConfigurer); return http.build(); @@ -1048,20 +1048,20 @@ public class OAuth2AuthorizationCodeGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .authorizationEndpoint(authorizationEndpoint -> + .authorizationEndpoint((authorizationEndpoint) -> authorizationEndpoint.consentPage(consentPage)); RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher(); http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } @@ -1078,20 +1078,20 @@ public class OAuth2AuthorizationCodeGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .authorizationEndpoint(authorizationEndpoint -> + .authorizationEndpoint((authorizationEndpoint) -> authorizationEndpoint.authenticationProviders(configureAuthenticationProviders())); RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher(); http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } @@ -1100,7 +1100,7 @@ public class OAuth2AuthorizationCodeGrantTests { @Bean @Override OAuth2TokenCustomizer jwtCustomizer() { - return context -> { + return (context) -> { if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(context.getAuthorizationGrantType()) && OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) { OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService @@ -1167,11 +1167,11 @@ public class OAuth2AuthorizationCodeGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .authorizationEndpoint(authorizationEndpoint -> + .authorizationEndpoint((authorizationEndpoint) -> authorizationEndpoint .authorizationRequestConverter(authorizationRequestConverter) .authorizationRequestConverters(authorizationRequestConvertersConsumer) @@ -1183,10 +1183,10 @@ public class OAuth2AuthorizationCodeGrantTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataTests.java index 6824ee53..4b0aa93d 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataTests.java @@ -96,8 +96,8 @@ public class OAuth2AuthorizationServerMetadataTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -173,13 +173,13 @@ public class OAuth2AuthorizationServerMetadataTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); http.apply(authorizationServerConfigurer); authorizationServerConfigurer - .authorizationServerMetadataEndpoint(authorizationServerMetadataEndpoint -> + .authorizationServerMetadataEndpoint((authorizationServerMetadataEndpoint) -> authorizationServerMetadataEndpoint .authorizationServerMetadataCustomizer(authorizationServerMetadataCustomizer())); @@ -187,10 +187,10 @@ public class OAuth2AuthorizationServerMetadataTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)); + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientCredentialsGrantTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientCredentialsGrantTests.java index b3b63d0f..c6b86af5 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientCredentialsGrantTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientCredentialsGrantTests.java @@ -24,13 +24,12 @@ import java.util.Base64; import java.util.List; import java.util.function.Consumer; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -105,11 +104,11 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.assertj.core.api.Assertions.assertThat; 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.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -188,8 +187,8 @@ public class OAuth2ClientCredentialsGrantTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -285,14 +284,14 @@ public class OAuth2ClientCredentialsGrantTests { ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication = new OAuth2ClientCredentialsAuthenticationToken( clientPrincipal, null, null); - when(authenticationConverter.convert(any())).thenReturn(clientCredentialsAuthentication); + given(authenticationConverter.convert(any())).willReturn(clientCredentialsAuthentication); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1))); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); - when(authenticationProvider.supports(eq(OAuth2ClientCredentialsAuthenticationToken.class))).thenReturn(true); - when(authenticationProvider.authenticate(any())).thenReturn(accessTokenAuthentication); + given(authenticationProvider.supports(eq(OAuth2ClientCredentialsAuthenticationToken.class))).willReturn(true); + given(authenticationProvider.authenticate(any())).willReturn(accessTokenAuthentication); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI) @@ -339,9 +338,9 @@ public class OAuth2ClientCredentialsGrantTests { OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, new ClientAuthenticationMethod("custom"), null); - when(authenticationConverter.convert(any())).thenReturn(clientPrincipal); - when(authenticationProvider.supports(eq(OAuth2ClientAuthenticationToken.class))).thenReturn(true); - when(authenticationProvider.authenticate(any())).thenReturn(clientPrincipal); + given(authenticationConverter.convert(any())).willReturn(clientPrincipal); + given(authenticationProvider.supports(eq(OAuth2ClientAuthenticationToken.class))).willReturn(true); + given(authenticationProvider.authenticate(any())).willReturn(clientPrincipal); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI).param(OAuth2ParameterNames.GRANT_TYPE, @@ -453,11 +452,11 @@ public class OAuth2ClientCredentialsGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .tokenEndpoint(tokenEndpoint -> + .tokenEndpoint((tokenEndpoint) -> tokenEndpoint .accessTokenRequestConverter(authenticationConverter) .accessTokenRequestConverters(authenticationConvertersConsumer) @@ -469,10 +468,10 @@ public class OAuth2ClientCredentialsGrantTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } @@ -497,13 +496,13 @@ public class OAuth2ClientCredentialsGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { authenticationSuccessHandler = spy(authenticationSuccessHandler()); OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .clientAuthentication(clientAuthentication -> + .clientAuthentication((clientAuthentication) -> clientAuthentication .authenticationConverter(authenticationConverter) .authenticationConverters(authenticationConvertersConsumer) @@ -515,10 +514,10 @@ public class OAuth2ClientCredentialsGrantTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceCodeGrantTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceCodeGrantTests.java index 88450aa9..f3edae28 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceCodeGrantTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceCodeGrantTests.java @@ -151,9 +151,9 @@ public class OAuth2DeviceCodeGrantTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_authorization_consent"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_authorization_consent"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java index c9a2b5c3..f478599b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java @@ -142,8 +142,8 @@ public class OAuth2RefreshTokenGrantTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -282,7 +282,7 @@ public class OAuth2RefreshTokenGrantTests { @Bean OAuth2TokenCustomizer jwtCustomizer() { - return context -> { + return (context) -> { if (AuthorizationGrantType.REFRESH_TOKEN.equals(context.getAuthorizationGrantType())) { Authentication principal = context.getPrincipal(); Set authorities = new HashSet<>(); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionTests.java index dc53cc78..434c91db 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionTests.java @@ -106,9 +106,9 @@ import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; 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; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -180,8 +180,8 @@ public class OAuth2TokenIntrospectionTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -375,9 +375,9 @@ public class OAuth2TokenIntrospectionTests { OAuth2TokenIntrospectionAuthenticationToken tokenIntrospectionAuthentication = new OAuth2TokenIntrospectionAuthenticationToken( accessToken.getTokenValue(), clientPrincipal, null, null); - when(authenticationConverter.convert(any())).thenReturn(tokenIntrospectionAuthentication); - when(authenticationProvider.supports(eq(OAuth2TokenIntrospectionAuthenticationToken.class))).thenReturn(true); - when(authenticationProvider.authenticate(any())).thenReturn(tokenIntrospectionAuthentication); + given(authenticationConverter.convert(any())).willReturn(tokenIntrospectionAuthentication); + given(authenticationProvider.supports(eq(OAuth2TokenIntrospectionAuthenticationToken.class))).willReturn(true); + given(authenticationProvider.authenticate(any())).willReturn(tokenIntrospectionAuthentication); // @formatter:off this.mvc.perform(post(authorizationServerSettings.getTokenIntrospectionEndpoint()) @@ -528,11 +528,11 @@ public class OAuth2TokenIntrospectionTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .tokenIntrospectionEndpoint(tokenIntrospectionEndpoint -> + .tokenIntrospectionEndpoint((tokenIntrospectionEndpoint) -> tokenIntrospectionEndpoint .introspectionRequestConverter(authenticationConverter) .introspectionRequestConverters(authenticationConvertersConsumer) @@ -544,10 +544,10 @@ public class OAuth2TokenIntrospectionTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationTests.java index 67cec39d..441945a2 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationTests.java @@ -84,9 +84,9 @@ import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; 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; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -151,8 +151,8 @@ public class OAuth2TokenRevocationTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -229,9 +229,9 @@ public class OAuth2TokenRevocationTests { OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication = new OAuth2TokenRevocationAuthenticationToken( token, clientPrincipal); - when(authenticationConverter.convert(any())).thenReturn(tokenRevocationAuthentication); - when(authenticationProvider.supports(eq(OAuth2TokenRevocationAuthenticationToken.class))).thenReturn(true); - when(authenticationProvider.authenticate(any())).thenReturn(tokenRevocationAuthentication); + given(authenticationConverter.convert(any())).willReturn(tokenRevocationAuthentication); + given(authenticationProvider.supports(eq(OAuth2TokenRevocationAuthenticationToken.class))).willReturn(true); + given(authenticationProvider.authenticate(any())).willReturn(tokenRevocationAuthentication); this.mvc .perform(post(DEFAULT_TOKEN_REVOCATION_ENDPOINT_URI) @@ -344,11 +344,11 @@ public class OAuth2TokenRevocationTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .tokenRevocationEndpoint(tokenRevocationEndpoint -> + .tokenRevocationEndpoint((tokenRevocationEndpoint) -> tokenRevocationEndpoint .revocationRequestConverter(authenticationConverter) .revocationRequestConverters(authenticationConvertersConsumer) @@ -360,10 +360,10 @@ public class OAuth2TokenRevocationTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java index 7afac8fb..75f79fc7 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java @@ -114,12 +114,12 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.ArgumentMatchers.any; -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.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -216,14 +216,14 @@ public class OidcClientRegistrationTests { .setBody(clientJwkSet.toString()); // @formatter:on this.server.enqueue(response); - when(authenticationProvider.supports(OidcClientRegistrationAuthenticationToken.class)).thenReturn(true); + given(authenticationProvider.supports(OidcClientRegistrationAuthenticationToken.class)).willReturn(true); } @AfterEach public void tearDown() throws Exception { this.server.shutdown(); - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); reset(authenticationConverter); reset(authenticationConvertersConsumer); reset(authenticationProvider); @@ -343,13 +343,13 @@ public class OidcClientRegistrationTests { .build(); // @formatter:on - doAnswer(invocation -> { + willAnswer((invocation) -> { HttpServletResponse response = invocation.getArgument(1, HttpServletResponse.class); ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); httpResponse.setStatusCode(HttpStatus.CREATED); new OidcClientRegistrationHttpMessageConverter().write(clientRegistration, null, httpResponse); return null; - }).when(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), any()); + }).given(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), any()); registerClient(clientRegistration); @@ -359,7 +359,7 @@ public class OidcClientRegistrationTests { verify(authenticationConvertersConsumer).accept(authenticationConvertersCaptor.capture()); List authenticationConverters = authenticationConvertersCaptor.getValue(); assertThat(authenticationConverters).hasSize(2) - .allMatch(converter -> converter == authenticationConverter + .allMatch((converter) -> converter == authenticationConverter || converter instanceof OidcClientRegistrationAuthenticationConverter); verify(authenticationProvider).authenticate(any()); @@ -368,7 +368,7 @@ public class OidcClientRegistrationTests { verify(authenticationProvidersConsumer).accept(authenticationProvidersCaptor.capture()); List authenticationProviders = authenticationProvidersCaptor.getValue(); assertThat(authenticationProviders).hasSize(3) - .allMatch(provider -> provider == authenticationProvider + .allMatch((provider) -> provider == authenticationProvider || provider instanceof OidcClientRegistrationAuthenticationProvider || provider instanceof OidcClientConfigurationAuthenticationProvider); @@ -381,7 +381,7 @@ public class OidcClientRegistrationTests { throws Exception { this.spring.register(CustomClientRegistrationConfiguration.class).autowire(); - when(authenticationProvider.authenticate(any())).thenThrow(new OAuth2AuthenticationException("error")); + given(authenticationProvider.authenticate(any())).willThrow(new OAuth2AuthenticationException("error")); this.mvc .perform(get(DEFAULT_OIDC_CLIENT_REGISTRATION_ENDPOINT_URI).param(OAuth2ParameterNames.CLIENT_ID, "invalid") @@ -611,9 +611,9 @@ public class OidcClientRegistrationTests { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .oidc(oidc -> + .oidc((oidc) -> oidc - .clientRegistrationEndpoint(clientRegistration -> + .clientRegistrationEndpoint((clientRegistration) -> clientRegistration .clientRegistrationRequestConverter(authenticationConverter) .clientRegistrationRequestConverters(authenticationConvertersConsumer) @@ -627,11 +627,11 @@ public class OidcClientRegistrationTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) .apply(authorizationServerConfigurer); @@ -652,9 +652,9 @@ public class OidcClientRegistrationTests { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .oidc(oidc -> + .oidc((oidc) -> oidc - .clientRegistrationEndpoint(clientRegistration -> + .clientRegistrationEndpoint((clientRegistration) -> clientRegistration .authenticationProviders(configureRegisteredClientConverter()) ) @@ -663,11 +663,11 @@ public class OidcClientRegistrationTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) .apply(authorizationServerConfigurer); @@ -711,31 +711,35 @@ public class OidcClientRegistrationTests { 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()) || @@ -744,7 +748,7 @@ public class OidcClientRegistrationTests { } if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) { - builder.scopes(scopes -> + builder.scopes((scopes) -> scopes.addAll(clientRegistration.getScopes())); } @@ -758,7 +762,8 @@ public class OidcClientRegistrationTests { 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; @@ -794,21 +799,21 @@ public class OidcClientRegistrationTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .oidc(oidc -> + .oidc((oidc) -> oidc.clientRegistrationEndpoint(Customizer.withDefaults())); RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher(); http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) .apply(authorizationServerConfigurer); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationTests.java index 096cf87d..dbabeacb 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationTests.java @@ -225,14 +225,14 @@ public class OidcProviderConfigurationTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); http.apply(authorizationServerConfigurer); authorizationServerConfigurer - .oidc(oidc -> - oidc.providerConfigurationEndpoint(providerConfigurationEndpoint -> + .oidc((oidc) -> + oidc.providerConfigurationEndpoint((providerConfigurationEndpoint) -> providerConfigurationEndpoint .providerConfigurationCustomizer(providerConfigurationCustomizer()))); @@ -240,10 +240,10 @@ public class OidcProviderConfigurationTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)); + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)); return http.build(); } @@ -268,7 +268,7 @@ public class OidcProviderConfigurationTests { http.apply(authorizationServerConfigurer); authorizationServerConfigurer - .oidc(oidc -> + .oidc((oidc) -> oidc.clientRegistrationEndpoint(Customizer.withDefaults()) ); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java index b9f21bdc..ff414080 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java @@ -179,9 +179,9 @@ public class OidcTests { @AfterEach public void tearDown() { - if (jdbcOperations != null) { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + if (this.jdbcOperations != null) { + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } } @@ -552,7 +552,7 @@ public class OidcTests { @Bean OAuth2TokenCustomizer jwtCustomizer() { - return context -> { + return (context) -> { if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) { Authentication principal = context.getPrincipal(); Set authorities = new HashSet<>(); @@ -605,7 +605,7 @@ public class OidcTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); http.apply(authorizationServerConfigurer); @@ -619,10 +619,10 @@ public class OidcTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)); + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoTests.java index bdc58a11..c43af61b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoTests.java @@ -87,13 +87,13 @@ import org.springframework.test.web.servlet.ResultMatcher; import static org.assertj.core.api.Assertions.assertThat; 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.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -202,7 +202,7 @@ public class OidcUserInfoTests { OAuth2Authorization authorization = createAuthorization(); this.authorizationService.save(authorization); - when(userInfoMapper.apply(any())).thenReturn(createUserInfo()); + given(userInfoMapper.apply(any())).willReturn(createUserInfo()); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); // @formatter:off @@ -221,7 +221,7 @@ public class OidcUserInfoTests { verify(authenticationProvidersConsumer).accept(authenticationProvidersCaptor.capture()); List authenticationProviders = authenticationProvidersCaptor.getValue(); assertThat(authenticationProviders).hasSize(2) - .allMatch(provider -> provider == authenticationProvider + .allMatch((provider) -> provider == authenticationProvider || provider instanceof OidcUserInfoAuthenticationProvider); ArgumentCaptor> authenticationConvertersCaptor = ArgumentCaptor @@ -238,12 +238,12 @@ public class OidcUserInfoTests { OAuth2Authorization authorization = createAuthorization(); this.authorizationService.save(authorization); - when(authenticationProvider.supports(eq(OidcUserInfoAuthenticationToken.class))).thenReturn(true); + given(authenticationProvider.supports(eq(OidcUserInfoAuthenticationToken.class))).willReturn(true); String tokenValue = authorization.getAccessToken().getToken().getTokenValue(); Jwt jwt = this.jwtDecoder.decode(tokenValue); OidcUserInfoAuthenticationToken oidcUserInfoAuthentication = new OidcUserInfoAuthenticationToken( new JwtAuthenticationToken(jwt), createUserInfo()); - when(authenticationProvider.authenticate(any())).thenReturn(oidcUserInfoAuthentication); + given(authenticationProvider.authenticate(any())).willReturn(oidcUserInfoAuthentication); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); // @formatter:off @@ -262,13 +262,13 @@ public class OidcUserInfoTests { public void requestWhenUserInfoEndpointCustomizedWithAuthenticationFailureHandlerThenUsed() throws Exception { this.spring.register(CustomUserInfoConfiguration.class).autowire(); - when(userInfoMapper.apply(any())).thenReturn(createUserInfo()); - doAnswer(invocation -> { + given(userInfoMapper.apply(any())).willReturn(createUserInfo()); + willAnswer((invocation) -> { HttpServletResponse response = invocation.getArgument(1); response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.getWriter().write("unauthorized"); return null; - }).when(authenticationFailureHandler).onAuthenticationFailure(any(), any(), any()); + }).given(authenticationFailureHandler).onAuthenticationFailure(any(), any(), any()); OAuth2AccessToken accessToken = createAuthorization().getAccessToken().getToken(); // @formatter:off @@ -336,7 +336,7 @@ public class OidcUserInfoTests { JwsHeader headers = JwsHeader.with(SignatureAlgorithm.RS256).build(); // @formatter:off JwtClaimsSet claimSet = JwtClaimsSet.builder() - .claims(claims -> claims.putAll(createUserInfo().getClaims())) + .claims((claims) -> claims.putAll(createUserInfo().getClaims())) .build(); // @formatter:on Jwt jwt = this.jwtEncoder.encode(JwtEncoderParameters.from(headers, claimSet)); @@ -347,7 +347,7 @@ public class OidcUserInfoTests { OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, jwt.getTokenValue(), now, now.plusSeconds(300), scopes); OidcIdToken idToken = OidcIdToken.withTokenValue("id-token") - .claims(claims -> claims.putAll(createUserInfo().getClaims())) + .claims((claims) -> claims.putAll(createUserInfo().getClaims())) .build(); return TestOAuth2Authorizations.authorization().accessToken(accessToken).token(idToken).build(); @@ -393,16 +393,16 @@ public class OidcUserInfoTests { // @formatter:off http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) .apply(authorizationServerConfigurer) - .oidc(oidc -> oidc - .userInfoEndpoint(userInfo -> userInfo + .oidc((oidc) -> oidc + .userInfoEndpoint((userInfo) -> userInfo .userInfoRequestConverter(authenticationConverter) .userInfoRequestConverters(authenticationConvertersConsumer) .authenticationProvider(authenticationProvider) @@ -435,14 +435,14 @@ public class OidcUserInfoTests { // @formatter:off http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) - .securityContext(securityContext -> + .securityContext((securityContext) -> securityContext.securityContextRepository(securityContextRepository)) .apply(authorizationServerConfigurer); // @formatter:on @@ -466,11 +466,11 @@ public class OidcUserInfoTests { // @formatter:off http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) .apply(authorizationServerConfigurer); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/context/TestAuthorizationServerContext.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/context/TestAuthorizationServerContext.java index fc406ac2..e7c14db4 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/context/TestAuthorizationServerContext.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/context/TestAuthorizationServerContext.java @@ -37,7 +37,7 @@ public class TestAuthorizationServerContext implements AuthorizationServerContex @Override public String getIssuer() { - return this.issuerSupplier != null ? this.issuerSupplier.get() : getAuthorizationServerSettings().getIssuer(); + return (this.issuerSupplier != null) ? this.issuerSupplier.get() : getAuthorizationServerSettings().getIssuer(); } @Override diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2AuthorizationServerMetadataHttpMessageConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2AuthorizationServerMetadataHttpMessageConverterTests.java index 7c291e2d..f7f205d6 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2AuthorizationServerMetadataHttpMessageConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2AuthorizationServerMetadataHttpMessageConverterTests.java @@ -148,7 +148,7 @@ public class OAuth2AuthorizationServerMetadataHttpMessageConverterTests { @Test public void readInternalWhenFailingConverterThenThrowException() { String errorMessage = "this is not a valid converter"; - this.messageConverter.setAuthorizationServerMetadataConverter(source -> { + this.messageConverter.setAuthorizationServerMetadataConverter((source) -> { throw new RuntimeException(errorMessage); }); MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK); @@ -224,7 +224,7 @@ public class OAuth2AuthorizationServerMetadataHttpMessageConverterTests { @Test public void writeInternalWhenWriteFailsThenThrowException() { String errorMessage = "this is not a valid converter"; - Converter> failingConverter = source -> { + Converter> failingConverter = (source) -> { throw new RuntimeException(errorMessage); }; this.messageConverter.setAuthorizationServerMetadataParametersConverter(failingConverter); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2TokenIntrospectionHttpMessageConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2TokenIntrospectionHttpMessageConverterTests.java index ddf06789..3866f0cb 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2TokenIntrospectionHttpMessageConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2TokenIntrospectionHttpMessageConverterTests.java @@ -105,7 +105,7 @@ public class OAuth2TokenIntrospectionHttpMessageConverterTests { @Test public void readInternalWhenFailingConverterThenThrowException() { String errorMessage = "this is not a valid converter"; - this.messageConverter.setTokenIntrospectionConverter(source -> { + this.messageConverter.setTokenIntrospectionConverter((source) -> { throw new RuntimeException(errorMessage); }); MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK); @@ -156,7 +156,7 @@ public class OAuth2TokenIntrospectionHttpMessageConverterTests { @Test public void writeInternalWhenWriteFailsThenThrowsException() { String errorMessage = "this is not a valid converter"; - Converter> failingConverter = source -> { + Converter> failingConverter = (source) -> { throw new RuntimeException(errorMessage); }; this.messageConverter.setTokenIntrospectionParametersConverter(failingConverter); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistrationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistrationTests.java index 5ae9279f..96ce6cef 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistrationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistrationTests.java @@ -252,7 +252,7 @@ public class OidcClientRegistrationTests { // @formatter:off OidcClientRegistration clientRegistration = this.minimalBuilder .redirectUri("https://client1.example.com") - .redirectUris(redirectUris -> { + .redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add("https://client2.example.com"); }) @@ -285,7 +285,7 @@ public class OidcClientRegistrationTests { // @formatter:off OidcClientRegistration clientRegistration = this.minimalBuilder .postLogoutRedirectUri("https://client1.example.com/oidc-post-logout") - .postLogoutRedirectUris(postLogoutRedirectUris -> { + .postLogoutRedirectUris((postLogoutRedirectUris) -> { postLogoutRedirectUris.clear(); postLogoutRedirectUris.add("https://client2.example.com/oidc-post-logout"); }) @@ -318,7 +318,7 @@ public class OidcClientRegistrationTests { // @formatter:off OidcClientRegistration clientRegistration = this.minimalBuilder .grantType("authorization_code") - .grantTypes(grantTypes -> { + .grantTypes((grantTypes) -> { grantTypes.clear(); grantTypes.add("client_credentials"); }) @@ -350,7 +350,7 @@ public class OidcClientRegistrationTests { // @formatter:off OidcClientRegistration clientRegistration = this.minimalBuilder .responseType("token") - .responseTypes(responseTypes -> { + .responseTypes((responseTypes) -> { responseTypes.clear(); responseTypes.add("code"); }) @@ -382,7 +382,7 @@ public class OidcClientRegistrationTests { // @formatter:off OidcClientRegistration clientRegistration = this.minimalBuilder .scope("should-be-removed") - .scopes(scopes -> { + .scopes((scopes) -> { scopes.clear(); scopes.add("scope1"); }) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfigurationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfigurationTests.java index 0ff05965..cd6e33bc 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfigurationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfigurationTests.java @@ -404,7 +404,7 @@ public class OidcProviderConfigurationTests { @Test public void responseTypesWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder.responseType("should-be-removed") - .responseTypes(responseTypes -> { + .responseTypes((responseTypes) -> { responseTypes.clear(); responseTypes.add("some-response-type"); }) @@ -416,8 +416,8 @@ public class OidcProviderConfigurationTests { @Test public void responseTypesWhenNotPresentAndAddingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder - .claims(claims -> claims.remove(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED)) - .responseTypes(responseTypes -> responseTypes.add("some-response-type")) + .claims((claims) -> claims.remove(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED)) + .responseTypes((responseTypes) -> responseTypes.add("some-response-type")) .build(); assertThat(configuration.getResponseTypes()).containsExactly("some-response-type"); @@ -426,7 +426,7 @@ public class OidcProviderConfigurationTests { @Test public void subjectTypesWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder.subjectType("should-be-removed") - .subjectTypes(subjectTypes -> { + .subjectTypes((subjectTypes) -> { subjectTypes.clear(); subjectTypes.add("some-subject-type"); }) @@ -439,7 +439,7 @@ public class OidcProviderConfigurationTests { public void idTokenSigningAlgorithmsWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder .idTokenSigningAlgorithm("should-be-removed") - .idTokenSigningAlgorithms(signingAlgorithms -> { + .idTokenSigningAlgorithms((signingAlgorithms) -> { signingAlgorithms.clear(); signingAlgorithms.add("ES256"); }) @@ -451,7 +451,7 @@ public class OidcProviderConfigurationTests { @Test public void scopesWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder.scope("should-be-removed") - .scopes(scopes -> { + .scopes((scopes) -> { scopes.clear(); scopes.add("some-scope"); }) @@ -463,7 +463,7 @@ public class OidcProviderConfigurationTests { @Test public void grantTypesWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder.grantType("should-be-removed") - .grantTypes(grantTypes -> { + .grantTypes((grantTypes) -> { grantTypes.clear(); grantTypes.add("some-grant-type"); }) @@ -476,7 +476,7 @@ public class OidcProviderConfigurationTests { public void tokenEndpointAuthenticationMethodsWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder .tokenEndpointAuthenticationMethod("should-be-removed") - .tokenEndpointAuthenticationMethods(authMethods -> { + .tokenEndpointAuthenticationMethods((authMethods) -> { authMethods.clear(); authMethods.add("some-authentication-method"); }) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientConfigurationAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientConfigurationAuthenticationProviderTests.java index d7899341..364b0d9c 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientConfigurationAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientConfigurationAuthenticationProviderTests.java @@ -60,10 +60,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcClientConfigurationAuthenticationProvider}. @@ -125,7 +125,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); } @@ -139,7 +139,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); } @@ -155,7 +155,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwt.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN)); @@ -171,9 +171,9 @@ public class OidcClientConfigurationAuthenticationProviderTests { .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); authorization = OidcAuthenticationProviderUtils.invalidate(authorization, jwtAccessToken); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); @@ -183,7 +183,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -199,9 +199,9 @@ public class OidcClientConfigurationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_unauthorized.scope")); @@ -211,7 +211,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -227,9 +227,9 @@ public class OidcClientConfigurationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read", "SCOPE_scope1")); @@ -239,7 +239,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -255,9 +255,9 @@ public class OidcClientConfigurationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); @@ -267,7 +267,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -288,11 +288,11 @@ public class OidcClientConfigurationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(authorizedRegisteredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + .willReturn(authorization); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); @@ -302,7 +302,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -328,11 +328,11 @@ public class OidcClientConfigurationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + .willReturn(authorization); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); @@ -363,7 +363,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { List grantTypes = new ArrayList<>(); registeredClient.getAuthorizationGrantTypes() - .forEach(authorizationGrantType -> grantTypes.add(authorizationGrantType.getValue())); + .forEach((authorizationGrantType) -> grantTypes.add(authorizationGrantType.getValue())); assertThat(clientRegistrationResult.getGrantTypes()).containsExactlyInAnyOrderElementsOf(grantTypes); assertThat(clientRegistrationResult.getResponseTypes()) @@ -403,8 +403,8 @@ public class OidcClientConfigurationAuthenticationProviderTests { .claim(OAuth2ParameterNames.SCOPE, scopes) .build(); Jwt jwt = Jwt.withTokenValue("jwt-access-token") - .headers(headers -> headers.putAll(jwsHeader.getHeaders())) - .claims(claims -> claims.putAll(jwtClaimsSet.getClaims())) + .headers((headers) -> headers.putAll(jwsHeader.getHeaders())) + .claims((claims) -> claims.putAll(jwtClaimsSet.getClaims())) .build(); // @formatter:on return jwt; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProviderTests.java index a7e5d3e6..bd932e51 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProviderTests.java @@ -71,6 +71,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException 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.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; @@ -78,7 +79,6 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcClientRegistrationAuthenticationProvider}. @@ -193,7 +193,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); } @@ -210,7 +210,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); } @@ -229,7 +229,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwt.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN)); @@ -245,9 +245,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); authorization = OidcAuthenticationProviderUtils.invalidate(authorization, jwtAccessToken); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -260,7 +260,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -276,9 +276,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_unauthorized.scope")); @@ -291,7 +291,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -307,9 +307,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create", "SCOPE_scope1")); @@ -322,7 +322,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -338,9 +338,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -355,8 +355,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { 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_REDIRECT_URI); assertThat(error.getDescription()).contains(OidcClientMetadataClaimNames.REDIRECT_URIS); }); @@ -373,9 +373,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -390,8 +390,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { 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_REDIRECT_URI); assertThat(error.getDescription()).contains(OidcClientMetadataClaimNames.REDIRECT_URIS); }); @@ -408,9 +408,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -426,8 +426,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { 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("invalid_client_metadata"); assertThat(error.getDescription()).contains(OidcClientMetadataClaimNames.POST_LOGOUT_REDIRECT_URIS); }); @@ -444,9 +444,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -462,8 +462,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { 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("invalid_client_metadata"); assertThat(error.getDescription()).contains(OidcClientMetadataClaimNames.POST_LOGOUT_REDIRECT_URIS); }); @@ -480,9 +480,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -544,8 +544,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { 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(errorCode); assertThat(error.getDescription()).contains(errorDescription); }); @@ -560,10 +560,10 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); - when(this.jwtEncoder.encode(any())).thenReturn(createJwtClientConfiguration()); + .willReturn(authorization); + given(this.jwtEncoder.encode(any())).willReturn(createJwtClientConfiguration()); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -611,9 +611,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); doReturn(null).when(this.tokenGenerator).generate(any()); @@ -635,8 +635,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { 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 registration access token."); @@ -652,10 +652,10 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); - when(this.jwtEncoder.encode(any())).thenReturn(createJwtClientConfiguration()); + .willReturn(authorization); + given(this.jwtEncoder.encode(any())).willReturn(createJwtClientConfiguration()); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -734,7 +734,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { List grantTypes = new ArrayList<>(); registeredClientResult.getAuthorizationGrantTypes() - .forEach(authorizationGrantType -> grantTypes.add(authorizationGrantType.getValue())); + .forEach((authorizationGrantType) -> grantTypes.add(authorizationGrantType.getValue())); assertThat(clientRegistrationResult.getGrantTypes()).containsExactlyInAnyOrderElementsOf(grantTypes); assertThat(clientRegistrationResult.getResponseTypes()) @@ -774,8 +774,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { .claim(OAuth2ParameterNames.SCOPE, scopes) .build(); Jwt jwt = Jwt.withTokenValue("jwt-access-token") - .headers(headers -> headers.putAll(jwsHeader.getHeaders())) - .claims(claims -> claims.putAll(jwtClaimsSet.getClaims())) + .headers((headers) -> headers.putAll(jwsHeader.getHeaders())) + .claims((claims) -> claims.putAll(jwtClaimsSet.getClaims())) .build(); // @formatter:on return jwt; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcLogoutAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcLogoutAuthenticationProviderTests.java index 99019391..b7f91b80 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcLogoutAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcLogoutAuthenticationProviderTests.java @@ -54,9 +54,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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 OidcLogoutAuthenticationProvider}. @@ -132,8 +132,8 @@ public class OidcLogoutAuthenticationProviderTests { 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_TOKEN); assertThat(error.getDescription()).contains("id_token_hint"); }); @@ -158,16 +158,16 @@ public class OidcLogoutAuthenticationProviderTests { metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true); }) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken(idToken.getTokenValue(), principal, "session-1", null, 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_TOKEN); assertThat(error.getDescription()).contains("id_token_hint"); }); @@ -190,18 +190,18 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken(idToken.getTokenValue(), principal, "session-1", null, 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_TOKEN); assertThat(error.getDescription()).contains(IdTokenClaimNames.AUD); }); @@ -225,18 +225,18 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken(idToken.getTokenValue(), principal, "session-1", null, 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_TOKEN); assertThat(error.getDescription()).contains(IdTokenClaimNames.AUD); }); @@ -260,18 +260,18 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken(idToken.getTokenValue(), principal, "session-1", registeredClient.getClientId() + "-invalid", 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_REQUEST); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID); }); @@ -295,18 +295,18 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken(idToken.getTokenValue(), principal, "session-1", registeredClient.getClientId(), "https://example.com/callback-1-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_REQUEST); assertThat(error.getDescription()).contains("post_logout_redirect_uri"); }); @@ -329,10 +329,10 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); principal.setAuthenticated(true); @@ -341,8 +341,8 @@ public class OidcLogoutAuthenticationProviderTests { 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_TOKEN); assertThat(error.getDescription()).contains("sub"); }); @@ -367,10 +367,10 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); principal.setAuthenticated(true); @@ -382,8 +382,8 @@ public class OidcLogoutAuthenticationProviderTests { 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_TOKEN); assertThat(error.getDescription()).contains("sub"); }); @@ -407,15 +407,15 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); String sessionId = "session-1"; List sessions = Collections .singletonList(new SessionInformation(principal.getPrincipal(), sessionId, Date.from(Instant.now()))); - when(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).thenReturn(sessions); + given(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).willReturn(sessions); principal.setAuthenticated(true); @@ -424,8 +424,8 @@ public class OidcLogoutAuthenticationProviderTests { 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_TOKEN); assertThat(error.getDescription()).contains("sid"); }); @@ -450,15 +450,15 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); String sessionId = "session-1"; List sessions = Collections .singletonList(new SessionInformation(principal.getPrincipal(), sessionId, Date.from(Instant.now()))); - when(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).thenReturn(sessions); + given(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).willReturn(sessions); principal.setAuthenticated(true); @@ -467,8 +467,8 @@ public class OidcLogoutAuthenticationProviderTests { 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_TOKEN); assertThat(error.getDescription()).contains("sid"); }); @@ -516,15 +516,15 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); SessionInformation sessionInformation = new SessionInformation(principal.getPrincipal(), sessionId, Date.from(Instant.now())); List sessions = Collections.singletonList(sessionInformation); - when(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).thenReturn(sessions); + given(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).willReturn(sessions); principal.setAuthenticated(true); String postLogoutRedirectUri = registeredClient.getPostLogoutRedirectUris().toArray(new String[0])[0]; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProviderTests.java index 2cc36973..ffeb823b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProviderTests.java @@ -45,10 +45,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcUserInfoAuthenticationProvider}. @@ -91,7 +91,7 @@ public class OidcUserInfoAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); @@ -107,7 +107,7 @@ public class OidcUserInfoAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); @@ -122,7 +122,7 @@ public class OidcUserInfoAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); @@ -135,15 +135,15 @@ public class OidcUserInfoAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization().build(); authorization = OidcAuthenticationProviderUtils.invalidate(authorization, authorization.getAccessToken().getToken()); - when(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) + .willReturn(authorization); JwtAuthenticationToken principal = createJwtAuthenticationToken(tokenValue); OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); @@ -153,15 +153,15 @@ public class OidcUserInfoAuthenticationProviderTests { @Test public void authenticateWhenAccessTokenNotAuthorizedThenThrowOAuth2AuthenticationException() { String tokenValue = "token"; - when(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(TestOAuth2Authorizations.authorization().build()); + given(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) + .willReturn(TestOAuth2Authorizations.authorization().build()); JwtAuthenticationToken principal = createJwtAuthenticationToken(tokenValue); OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); @@ -174,15 +174,15 @@ public class OidcUserInfoAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization() .token(createAuthorization(tokenValue).getAccessToken().getToken()) .build(); - when(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) + .willReturn(authorization); JwtAuthenticationToken principal = createJwtAuthenticationToken(tokenValue); OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); @@ -192,8 +192,8 @@ public class OidcUserInfoAuthenticationProviderTests { @Test public void authenticateWhenValidAccessTokenThenReturnUserInfo() { String tokenValue = "access-token"; - when(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(createAuthorization(tokenValue)); + given(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) + .willReturn(createAuthorization(tokenValue)); JwtAuthenticationToken principal = createJwtAuthenticationToken(tokenValue); OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverterTests.java index 24821401..60d70e1d 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverterTests.java @@ -92,31 +92,31 @@ public class OidcClientRegistrationHttpMessageConverterTests { public void readInternalWhenValidParametersThenSuccess() throws Exception { // @formatter:off String clientRegistrationRequest = "{\n" - +" \"client_id\": \"client-id\",\n" - +" \"client_id_issued_at\": 1607633867,\n" - +" \"client_secret\": \"client-secret\",\n" - +" \"client_secret_expires_at\": 1607637467,\n" - +" \"client_name\": \"client-name\",\n" - +" \"redirect_uris\": [\n" + + " \"client_id\": \"client-id\",\n" + + " \"client_id_issued_at\": 1607633867,\n" + + " \"client_secret\": \"client-secret\",\n" + + " \"client_secret_expires_at\": 1607637467,\n" + + " \"client_name\": \"client-name\",\n" + + " \"redirect_uris\": [\n" + " \"https://client.example.com\"\n" + " ],\n" - +" \"post_logout_redirect_uris\": [\n" + + " \"post_logout_redirect_uris\": [\n" + " \"https://client.example.com/oidc-post-logout\"\n" + " ],\n" - +" \"token_endpoint_auth_method\": \"client_secret_jwt\",\n" - +" \"token_endpoint_auth_signing_alg\": \"HS256\",\n" - +" \"grant_types\": [\n" - +" \"authorization_code\",\n" - +" \"client_credentials\"\n" - +" ],\n" - +" \"response_types\":[\n" - +" \"code\"\n" - +" ],\n" - +" \"scope\": \"scope1 scope2\",\n" - +" \"jwks_uri\": \"https://client.example.com/jwks\",\n" - +" \"id_token_signed_response_alg\": \"RS256\",\n" - +" \"a-claim\": \"a-value\"\n" - +"}\n"; + + " \"token_endpoint_auth_method\": \"client_secret_jwt\",\n" + + " \"token_endpoint_auth_signing_alg\": \"HS256\",\n" + + " \"grant_types\": [\n" + + " \"authorization_code\",\n" + + " \"client_credentials\"\n" + + " ],\n" + + " \"response_types\":[\n" + + " \"code\"\n" + + " ],\n" + + " \"scope\": \"scope1 scope2\",\n" + + " \"jwks_uri\": \"https://client.example.com/jwks\",\n" + + " \"id_token_signed_response_alg\": \"RS256\",\n" + + " \"a-claim\": \"a-value\"\n" + + "}\n"; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(clientRegistrationRequest.getBytes(), HttpStatus.OK); @@ -148,13 +148,13 @@ public class OidcClientRegistrationHttpMessageConverterTests { public void readInternalWhenClientSecretNoExpiryThenSuccess() { // @formatter:off String clientRegistrationRequest = "{\n" - +" \"client_id\": \"client-id\",\n" - +" \"client_secret\": \"client-secret\",\n" - +" \"client_secret_expires_at\": 0,\n" - +" \"redirect_uris\": [\n" + + " \"client_id\": \"client-id\",\n" + + " \"client_secret\": \"client-secret\",\n" + + " \"client_secret_expires_at\": 0,\n" + + " \"redirect_uris\": [\n" + " \"https://client.example.com\"\n" + " ]\n" - +"}\n"; + + "}\n"; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(clientRegistrationRequest.getBytes(), HttpStatus.OK); @@ -171,7 +171,7 @@ public class OidcClientRegistrationHttpMessageConverterTests { @Test public void readInternalWhenFailingConverterThenThrowException() { String errorMessage = "this is not a valid converter"; - this.messageConverter.setClientRegistrationConverter(source -> { + this.messageConverter.setClientRegistrationConverter((source) -> { throw new RuntimeException(errorMessage); }); MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK); @@ -257,7 +257,7 @@ public class OidcClientRegistrationHttpMessageConverterTests { @Test public void writeInternalWhenWriteFailsThenThrowException() { String errorMessage = "this is not a valid converter"; - Converter> failingConverter = source -> { + Converter> failingConverter = (source) -> { throw new RuntimeException(errorMessage); }; this.messageConverter.setClientRegistrationParametersConverter(failingConverter); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcProviderConfigurationHttpMessageConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcProviderConfigurationHttpMessageConverterTests.java index c5cfc17a..f0eef0ca 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcProviderConfigurationHttpMessageConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcProviderConfigurationHttpMessageConverterTests.java @@ -137,7 +137,7 @@ public class OidcProviderConfigurationHttpMessageConverterTests { @Test public void readInternalWhenFailingConverterThenThrowException() { String errorMessage = "this is not a valid converter"; - this.messageConverter.setProviderConfigurationConverter(source -> { + this.messageConverter.setProviderConfigurationConverter((source) -> { throw new RuntimeException(errorMessage); }); MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK); @@ -204,7 +204,7 @@ public class OidcProviderConfigurationHttpMessageConverterTests { @Test public void writeInternalWhenWriteFailsThenThrowsException() { String errorMessage = "this is not a valid converter"; - Converter> failingConverter = source -> { + Converter> failingConverter = (source) -> { throw new RuntimeException(errorMessage); }; this.messageConverter.setProviderConfigurationParametersConverter(failingConverter); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcUserInfoHttpMessageConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcUserInfoHttpMessageConverterTests.java index b77bcf7d..a469dbc9 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcUserInfoHttpMessageConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcUserInfoHttpMessageConverterTests.java @@ -126,7 +126,7 @@ public class OidcUserInfoHttpMessageConverterTests { @Test public void readInternalWhenFailingConverterThenThrowException() { String errorMessage = "this is not a valid converter"; - this.messageConverter.setUserInfoConverter(source -> { + this.messageConverter.setUserInfoConverter((source) -> { throw new RuntimeException(errorMessage); }); MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK); @@ -185,7 +185,7 @@ public class OidcUserInfoHttpMessageConverterTests { @Test public void writeInternalWhenWriteFailsThenThrowsException() { String errorMessage = "this is not a valid converter"; - Converter> failingConverter = source -> { + Converter> failingConverter = (source) -> { throw new RuntimeException(errorMessage); }; this.messageConverter.setUserInfoParametersConverter(failingConverter); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilterTests.java index 95b43404..5b57705f 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilterTests.java @@ -23,7 +23,6 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -67,10 +66,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcClientRegistrationEndpointFilter}. @@ -199,7 +198,7 @@ public class OidcClientRegistrationEndpointFilterTests { securityContext.setAuthentication(principal); SecurityContextHolder.setContext(securityContext); - when(this.authenticationManager.authenticate(any())).thenThrow(new OAuth2AuthenticationException(errorCode)); + given(this.authenticationManager.authenticate(any())).willThrow(new OAuth2AuthenticationException(errorCode)); // @formatter:off OidcClientRegistration clientRegistrationRequest = OidcClientRegistration.builder() @@ -235,9 +234,9 @@ public class OidcClientRegistrationEndpointFilterTests { OidcClientRegistration clientRegistrationRequest = OidcClientRegistration.builder() .clientName(expectedClientRegistrationResponse.getClientName()) - .redirectUris(redirectUris -> redirectUris.addAll(expectedClientRegistrationResponse.getRedirectUris())) - .grantTypes(grantTypes -> grantTypes.addAll(expectedClientRegistrationResponse.getGrantTypes())) - .scopes(scopes -> scopes.addAll(expectedClientRegistrationResponse.getScopes())) + .redirectUris((redirectUris) -> redirectUris.addAll(expectedClientRegistrationResponse.getRedirectUris())) + .grantTypes((grantTypes) -> grantTypes.addAll(expectedClientRegistrationResponse.getGrantTypes())) + .scopes((scopes) -> scopes.addAll(expectedClientRegistrationResponse.getScopes())) .build(); // @formatter:on @@ -248,7 +247,7 @@ public class OidcClientRegistrationEndpointFilterTests { OidcClientRegistrationAuthenticationToken clientRegistrationAuthenticationResult = new OidcClientRegistrationAuthenticationToken( principal, expectedClientRegistrationResponse); - when(this.authenticationManager.authenticate(any())).thenReturn(clientRegistrationAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(clientRegistrationAuthenticationResult); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(principal); @@ -384,7 +383,7 @@ public class OidcClientRegistrationEndpointFilterTests { securityContext.setAuthentication(principal); SecurityContextHolder.setContext(securityContext); - when(this.authenticationManager.authenticate(any())).thenThrow(new OAuth2AuthenticationException(errorCode)); + given(this.authenticationManager.authenticate(any())).willThrow(new OAuth2AuthenticationException(errorCode)); String requestUri = DEFAULT_OIDC_CLIENT_REGISTRATION_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); @@ -414,7 +413,7 @@ public class OidcClientRegistrationEndpointFilterTests { OidcClientRegistrationAuthenticationToken clientConfigurationAuthenticationResult = new OidcClientRegistrationAuthenticationToken( principal, expectedClientRegistrationResponse); - when(this.authenticationManager.authenticate(any())).thenReturn(clientConfigurationAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(clientConfigurationAuthenticationResult); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(principal); @@ -489,7 +488,7 @@ public class OidcClientRegistrationEndpointFilterTests { OidcClientRegistrationAuthenticationToken clientRegistrationAuthenticationResult = new OidcClientRegistrationAuthenticationToken( principal, expectedClientRegistrationResponse); - when(this.authenticationManager.authenticate(any())).thenReturn(clientRegistrationAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(clientRegistrationAuthenticationResult); AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(successHandler); @@ -516,8 +515,8 @@ public class OidcClientRegistrationEndpointFilterTests { AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); - when(this.authenticationManager.authenticate(any())) - .thenThrow(new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN)); + given(this.authenticationManager.authenticate(any())) + .willThrow(new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN)); String requestUri = DEFAULT_OIDC_CLIENT_REGISTRATION_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); @@ -593,8 +592,8 @@ public class OidcClientRegistrationEndpointFilterTests { .claim(OAuth2ParameterNames.SCOPE, Collections.singleton(scope)) .build(); Jwt jwt = Jwt.withTokenValue("jwt-access-token") - .headers(headers -> headers.putAll(jwsHeader.getHeaders())) - .claims(claims -> claims.putAll(jwtClaimsSet.getClaims())) + .headers((headers) -> headers.putAll(jwsHeader.getHeaders())) + .claims((claims) -> claims.putAll(jwtClaimsSet.getClaims())) .build(); // @formatter:on return jwt; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcLogoutEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcLogoutEndpointFilterTests.java index 2b5417c4..ff52a429 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcLogoutEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcLogoutEndpointFilterTests.java @@ -20,7 +20,6 @@ import java.util.function.Consumer; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -51,10 +50,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.same; +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.when; /** * Tests for {@link OidcLogoutEndpointFilter}. @@ -138,14 +137,14 @@ public class OidcLogoutEndpointFilterTests { public void doFilterWhenLogoutRequestMissingIdTokenHintThenInvalidRequestError() throws Exception { doFilterWhenRequestInvalidParameterThenError( createLogoutRequest(TestRegisteredClients.registeredClient().build()), "id_token_hint", - OAuth2ErrorCodes.INVALID_REQUEST, request -> request.removeParameter("id_token_hint")); + OAuth2ErrorCodes.INVALID_REQUEST, (request) -> request.removeParameter("id_token_hint")); } @Test public void doFilterWhenLogoutRequestMultipleIdTokenHintThenInvalidRequestError() throws Exception { doFilterWhenRequestInvalidParameterThenError( createLogoutRequest(TestRegisteredClients.registeredClient().build()), "id_token_hint", - OAuth2ErrorCodes.INVALID_REQUEST, request -> request.addParameter("id_token_hint", "id-token-2")); + OAuth2ErrorCodes.INVALID_REQUEST, (request) -> request.addParameter("id_token_hint", "id-token-2")); } @Test @@ -153,7 +152,7 @@ public class OidcLogoutEndpointFilterTests { doFilterWhenRequestInvalidParameterThenError( createLogoutRequest(TestRegisteredClients.registeredClient().build()), OAuth2ParameterNames.CLIENT_ID, OAuth2ErrorCodes.INVALID_REQUEST, - request -> request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-2")); + (request) -> request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-2")); } @Test @@ -161,7 +160,7 @@ public class OidcLogoutEndpointFilterTests { doFilterWhenRequestInvalidParameterThenError( createLogoutRequest(TestRegisteredClients.registeredClient().build()), "post_logout_redirect_uri", OAuth2ErrorCodes.INVALID_REQUEST, - request -> request.addParameter("post_logout_redirect_uri", "https://example.com/callback-4")); + (request) -> request.addParameter("post_logout_redirect_uri", "https://example.com/callback-4")); } @Test @@ -169,7 +168,7 @@ public class OidcLogoutEndpointFilterTests { doFilterWhenRequestInvalidParameterThenError( createLogoutRequest(TestRegisteredClients.registeredClient().build()), OAuth2ParameterNames.STATE, OAuth2ErrorCodes.INVALID_REQUEST, - request -> request.addParameter(OAuth2ParameterNames.STATE, "state-2")); + (request) -> request.addParameter(OAuth2ParameterNames.STATE, "state-2")); } private void doFilterWhenRequestInvalidParameterThenError(MockHttpServletRequest request, String parameterName, @@ -191,7 +190,7 @@ public class OidcLogoutEndpointFilterTests { @Test public void doFilterWhenLogoutRequestAuthenticationExceptionThenErrorResponse() throws Exception { OAuth2Error error = new OAuth2Error("errorCode", "errorDescription", "errorUri"); - when(this.authenticationManager.authenticate(any())).thenThrow(new OAuth2AuthenticationException(error)); + given(this.authenticationManager.authenticate(any())).willThrow(new OAuth2AuthenticationException(error)); MockHttpServletRequest request = createLogoutRequest(TestRegisteredClients.registeredClient().build()); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -213,10 +212,10 @@ public class OidcLogoutEndpointFilterTests { null, null, null, null); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); - when(authenticationConverter.convert(any())).thenReturn(authentication); + given(authenticationConverter.convert(any())).willReturn((authentication)); this.filter.setAuthenticationConverter(authenticationConverter); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn((authentication)); MockHttpServletRequest request = createLogoutRequest(TestRegisteredClients.registeredClient().build()); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -237,7 +236,7 @@ public class OidcLogoutEndpointFilterTests { AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn((authentication)); MockHttpServletRequest request = createLogoutRequest(TestRegisteredClients.registeredClient().build()); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -255,8 +254,8 @@ public class OidcLogoutEndpointFilterTests { AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); - when(this.authenticationManager.authenticate(any())) - .thenThrow(new AuthenticationServiceException("AuthenticationServiceException")); + given(this.authenticationManager.authenticate(any())) + .willThrow(new AuthenticationServiceException("AuthenticationServiceException")); MockHttpServletRequest request = createLogoutRequest(TestRegisteredClients.registeredClient().build()); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -272,8 +271,8 @@ public class OidcLogoutEndpointFilterTests { verifyNoInteractions(filterChain); assertThat(authenticationExceptionCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); assertThat(error.getDescription()).contains("AuthenticationServiceException"); }); @@ -287,7 +286,7 @@ public class OidcLogoutEndpointFilterTests { OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken("id-token", this.principal, session.getId(), null, null, null); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn((authentication)); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); @@ -316,7 +315,7 @@ public class OidcLogoutEndpointFilterTests { session.getId(), registeredClient.getClientId(), postLogoutRedirectUri, state); authentication.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn((authentication)); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcProviderConfigurationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcProviderConfigurationEndpointFilterTests.java index 47922017..729930ae 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcProviderConfigurationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcProviderConfigurationEndpointFilterTests.java @@ -18,7 +18,6 @@ package org.springframework.security.oauth2.server.authorization.oidc.web; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcUserInfoEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcUserInfoEndpointFilterTests.java index 323595e1..d53eca48 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcUserInfoEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcUserInfoEndpointFilterTests.java @@ -19,7 +19,6 @@ import java.time.Instant; import java.util.Collections; import jakarta.servlet.FilterChain; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -51,10 +50,10 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand import static org.assertj.core.api.Assertions.assertThat; 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.when; /** * Tests for {@link OidcUserInfoEndpointFilter}. @@ -151,7 +150,7 @@ public class OidcUserInfoEndpointFilterTests { OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal, createUserInfo()); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(authentication); String requestUri = DEFAULT_OIDC_USER_INFO_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest(httpMethod, requestUri); @@ -183,8 +182,8 @@ public class OidcUserInfoEndpointFilterTests { Authentication principal = new TestingAuthenticationToken("principal", "credentials"); SecurityContextHolder.getContext().setAuthentication(principal); - when(this.authenticationManager.authenticate(any())) - .thenThrow(new OAuth2AuthenticationException(oauth2ErrorCode)); + given(this.authenticationManager.authenticate(any())) + .willThrow(new OAuth2AuthenticationException(oauth2ErrorCode)); String requestUri = DEFAULT_OIDC_USER_INFO_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); @@ -208,9 +207,9 @@ public class OidcUserInfoEndpointFilterTests { AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); this.filter.setAuthenticationConverter(authenticationConverter); - when(authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())) - .thenReturn(new OidcUserInfoAuthenticationToken(principal, createUserInfo())); + given(authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())) + .willReturn(new OidcUserInfoAuthenticationToken(principal, createUserInfo())); String requestUri = DEFAULT_OIDC_USER_INFO_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); @@ -236,7 +235,7 @@ public class OidcUserInfoEndpointFilterTests { OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal, createUserInfo()); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(authentication); String requestUri = DEFAULT_OIDC_USER_INFO_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); @@ -260,7 +259,7 @@ public class OidcUserInfoEndpointFilterTests { OAuth2AuthenticationException authenticationException = new OAuth2AuthenticationException( OAuth2ErrorCodes.INVALID_TOKEN); - when(this.authenticationManager.authenticate(any())).thenThrow(authenticationException); + given(this.authenticationManager.authenticate(any())).willThrow(authenticationException); String requestUri = DEFAULT_OIDC_USER_INFO_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettingsTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettingsTests.java index caf6b536..60bb9d95 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettingsTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettingsTests.java @@ -84,7 +84,7 @@ public class AuthorizationServerSettingsTests { public void settingWhenCustomThenSet() { AuthorizationServerSettings authorizationServerSettings = AuthorizationServerSettings.builder() .setting("name1", "value1") - .settings(settings -> settings.put("name2", "value2")) + .settings((settings) -> settings.put("name2", "value2")) .build(); assertThat(authorizationServerSettings.getSettings()).hasSize(12); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettingsTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettingsTests.java index 20a20445..5981589d 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettingsTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettingsTests.java @@ -66,7 +66,7 @@ public class ClientSettingsTests { public void settingWhenCustomThenSet() { ClientSettings clientSettings = ClientSettings.builder() .setting("name1", "value1") - .settings(settings -> settings.put("name2", "value2")) + .settings((settings) -> settings.put("name2", "value2")) .build(); assertThat(clientSettings.getSettings()).hasSize(4); assertThat(clientSettings.getSetting("name1")).isEqualTo("value1"); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettingsTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettingsTests.java index a3e1b97a..6e952738 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettingsTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettingsTests.java @@ -154,7 +154,7 @@ public class TokenSettingsTests { public void settingWhenCustomThenSet() { TokenSettings tokenSettings = TokenSettings.builder() .setting("name1", "value1") - .settings(settings -> settings.put("name2", "value2")) + .settings((settings) -> settings.put("name2", "value2")) .build(); assertThat(tokenSettings.getSettings()).hasSize(9); assertThat(tokenSettings.getSetting("name1")).isEqualTo("value1"); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/test/SpringTestContext.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/test/SpringTestContext.java index 06b377e5..f0464a11 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/test/SpringTestContext.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/test/SpringTestContext.java @@ -27,6 +27,7 @@ import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor; import org.springframework.mock.web.MockServletConfig; import org.springframework.mock.web.MockServletContext; +import org.springframework.security.config.BeanIds; import org.springframework.test.context.web.GenericXmlWebContextLoader; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; @@ -39,7 +40,6 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.filter.OncePerRequestFilter; -import static org.springframework.security.config.BeanIds.SPRING_SECURITY_FILTER_CHAIN; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; /** @@ -62,7 +62,7 @@ public class SpringTestContext implements Closeable { try { this.context.close(); } - catch (Exception e) { + catch (Exception ex) { } } @@ -120,7 +120,7 @@ public class SpringTestContext implements Closeable { this.context.setServletConfig(new MockServletConfig()); this.context.refresh(); - if (this.context.containsBean(SPRING_SECURITY_FILTER_CHAIN)) { + if (this.context.containsBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)) { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(springSecurity()) .apply(new AddFilter()) @@ -133,7 +133,7 @@ public class SpringTestContext implements Closeable { bpp.processInjection(this.test); } - private class AddFilter implements MockMvcConfigurer { + public class AddFilter implements MockMvcConfigurer { public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder builder, WebApplicationContext context) { diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/DelegatingOAuth2TokenGeneratorTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/DelegatingOAuth2TokenGeneratorTests.java index 03267b35..7ca1c6b7 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/DelegatingOAuth2TokenGeneratorTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/DelegatingOAuth2TokenGeneratorTests.java @@ -25,8 +25,8 @@ import org.springframework.security.oauth2.core.OAuth2Token; 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.mock; -import static org.mockito.Mockito.when; /** * Tests for {@link DelegatingOAuth2TokenGenerator}. @@ -60,7 +60,7 @@ public class DelegatingOAuth2TokenGeneratorTests { OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", Instant.now(), Instant.now().plusSeconds(300)); - when(tokenGenerator3.generate(any())).thenReturn(accessToken); + given(tokenGenerator3.generate(any())).willReturn(accessToken); DelegatingOAuth2TokenGenerator delegatingTokenGenerator = new DelegatingOAuth2TokenGenerator(tokenGenerator1, tokenGenerator2, tokenGenerator3); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/JwtEncodingContextTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/JwtEncodingContextTests.java index c40b7199..6625f94b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/JwtEncodingContextTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/JwtEncodingContextTests.java @@ -94,7 +94,7 @@ public class JwtEncodingContextTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrant(authorizationGrant) .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.getJwsHeader()).isEqualTo(headers); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsContextTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsContextTests.java index 78ff3dfa..cd5a1658 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsContextTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsContextTests.java @@ -96,7 +96,7 @@ public class OAuth2TokenClaimsContextTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrant(authorizationGrant) .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(); // @formatter:on diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSetTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSetTests.java index e51616dc..ea88dfea 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSetTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSetTests.java @@ -53,7 +53,7 @@ public class OAuth2TokenClaimsSetTests { .notBefore(issuedAt) .expiresAt(expiresAt) .id("id") - .claims(claims -> claims.put(customClaimName, customClaimValue)) + .claims((claims) -> claims.put(customClaimName, customClaimValue)) .build(); OAuth2TokenClaimsSet claimsSet = OAuth2TokenClaimsSet.builder() @@ -64,7 +64,7 @@ public class OAuth2TokenClaimsSetTests { .notBefore(expectedClaimsSet.getNotBefore()) .expiresAt(expectedClaimsSet.getExpiresAt()) .id(expectedClaimsSet.getId()) - .claims(claims -> claims.put(customClaimName, expectedClaimsSet.getClaim(customClaimName))) + .claims((claims) -> claims.put(customClaimName, expectedClaimsSet.getClaim(customClaimName))) .build(); // @formatter:on diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilterTests.java index baf17936..d15b4d56 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilterTests.java @@ -18,10 +18,6 @@ package org.springframework.security.oauth2.server.authorization.web; import java.util.ArrayList; import java.util.List; -import jakarta.servlet.FilterChain; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - import com.nimbusds.jose.jwk.ECKey; import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWKSet; @@ -30,6 +26,9 @@ import com.nimbusds.jose.jwk.OctetSequenceKey; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilterTests.java index 8fc31afd..ba89f50b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilterTests.java @@ -27,7 +27,7 @@ import java.util.function.Consumer; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -64,13 +64,12 @@ 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.assertj.core.api.InstanceOfAssertFactories.type; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; +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.when; /** * Tests for {@link OAuth2AuthorizationEndpointFilter}. @@ -185,7 +184,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMissingResponseTypeThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.removeParameter(OAuth2ParameterNames.RESPONSE_TYPE); updateQueryString(request); }); @@ -194,7 +193,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleResponseTypeThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(OAuth2ParameterNames.RESPONSE_TYPE, "id_token"); updateQueryString(request); }); @@ -203,7 +202,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestInvalidResponseTypeThenUnsupportedResponseTypeError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.UNSUPPORTED_RESPONSE_TYPE, request -> { + OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.UNSUPPORTED_RESPONSE_TYPE, (request) -> { request.setParameter(OAuth2ParameterNames.RESPONSE_TYPE, "id_token"); updateQueryString(request); }); @@ -212,7 +211,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMissingClientIdThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.CLIENT_ID, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.CLIENT_ID, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.removeParameter(OAuth2ParameterNames.CLIENT_ID); updateQueryString(request); }); @@ -221,7 +220,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleClientIdThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.CLIENT_ID, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.CLIENT_ID, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-2"); updateQueryString(request); }); @@ -230,7 +229,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleRedirectUriThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.REDIRECT_URI, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.REDIRECT_URI, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(OAuth2ParameterNames.REDIRECT_URI, "https://example2.com"); updateQueryString(request); }); @@ -239,7 +238,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleScopeThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.SCOPE, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.SCOPE, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(OAuth2ParameterNames.SCOPE, "scope2"); updateQueryString(request); }); @@ -248,7 +247,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleStateThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.STATE, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.STATE, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(OAuth2ParameterNames.STATE, "state2"); updateQueryString(request); }); @@ -258,7 +257,7 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenAuthorizationConsentRequestMissingStateThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationConsentRequestInvalidParameterThenError( TestRegisteredClients.registeredClient().build(), OAuth2ParameterNames.STATE, - OAuth2ErrorCodes.INVALID_REQUEST, request -> request.removeParameter(OAuth2ParameterNames.STATE)); + OAuth2ErrorCodes.INVALID_REQUEST, (request) -> request.removeParameter(OAuth2ParameterNames.STATE)); } @Test @@ -266,13 +265,13 @@ public class OAuth2AuthorizationEndpointFilterTests { doFilterWhenAuthorizationConsentRequestInvalidParameterThenError( TestRegisteredClients.registeredClient().build(), OAuth2ParameterNames.STATE, OAuth2ErrorCodes.INVALID_REQUEST, - request -> request.addParameter(OAuth2ParameterNames.STATE, "state2")); + (request) -> request.addParameter(OAuth2ParameterNames.STATE, "state2")); } @Test public void doFilterWhenAuthorizationRequestMultipleCodeChallengeThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - PkceParameterNames.CODE_CHALLENGE, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + PkceParameterNames.CODE_CHALLENGE, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(PkceParameterNames.CODE_CHALLENGE, "code-challenge"); request.addParameter(PkceParameterNames.CODE_CHALLENGE, "another-code-challenge"); updateQueryString(request); @@ -282,7 +281,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleCodeChallengeMethodThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - PkceParameterNames.CODE_CHALLENGE_METHOD, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + PkceParameterNames.CODE_CHALLENGE_METHOD, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); request.addParameter(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); updateQueryString(request); @@ -291,17 +290,17 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestAuthenticationExceptionThenErrorResponse() throws Exception { - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris(redirectUris -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add("https://example.com?param=encoded%20parameter%20value"); }).build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, registeredClient.getRedirectUris().iterator().next(), "client state", registeredClient.getScopes(), null); OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, "error description", "error uri"); - when(this.authenticationManager.authenticate(any())) - .thenThrow(new OAuth2AuthorizationCodeRequestAuthenticationException(error, + given(this.authenticationManager.authenticate(any())) + .willThrow(new OAuth2AuthorizationCodeRequestAuthenticationException(error, authorizationCodeRequestAuthentication)); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); @@ -323,14 +322,14 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenCustomAuthenticationConverterThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes(), null); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); - when(authenticationConverter.convert(any())).thenReturn(authorizationCodeRequestAuthentication); + given(authenticationConverter.convert(any())).willReturn(authorizationCodeRequestAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthentication); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -347,10 +346,10 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenCustomAuthenticationSuccessHandlerThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, this.authorizationCode, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, this.authorizationCode, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes()); authorizationCodeRequestAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthenticationResult); AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); @@ -371,12 +370,12 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenCustomAuthenticationFailureHandlerThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes(), null); OAuth2Error error = new OAuth2Error("errorCode", "errorDescription", "errorUri"); OAuth2AuthorizationCodeRequestAuthenticationException authenticationException = new OAuth2AuthorizationCodeRequestAuthenticationException( error, authorizationCodeRequestAuthentication); - when(this.authenticationManager.authenticate(any())).thenThrow(authenticationException); + given(this.authenticationManager.authenticate(any())).willThrow(authenticationException); AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); @@ -396,10 +395,10 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenCustomSessionAuthenticationStrategyThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, this.authorizationCode, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, this.authorizationCode, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes()); authorizationCodeRequestAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthenticationResult); SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class); this.filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy); @@ -420,17 +419,17 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenCustomAuthenticationDetailsSourceThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes(), null); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); AuthenticationDetailsSource authenticationDetailsSource = mock( AuthenticationDetailsSource.class); WebAuthenticationDetails webAuthenticationDetails = new WebAuthenticationDetails(request); - when(authenticationDetailsSource.buildDetails(request)).thenReturn(webAuthenticationDetails); + given(authenticationDetailsSource.buildDetails(request)).willReturn(webAuthenticationDetails); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthentication); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); @@ -447,10 +446,10 @@ public class OAuth2AuthorizationEndpointFilterTests { this.principal.setAuthenticated(false); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes(), null); authorizationCodeRequestAuthenticationResult.setAuthenticated(false); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -466,15 +465,15 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenAuthorizationRequestConsentRequiredWithCustomConsentUriThenRedirectConsentResponse() throws Exception { Set requestedScopes = new HashSet<>(Arrays.asList("scope1", "scope2")); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.addAll(requestedScopes); }).build(); // No scopes previously approved OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthenticationResult = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); authorizationConsentAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationConsentAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationConsentAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -494,15 +493,15 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestConsentRequiredThenConsentResponse() throws Exception { Set requestedScopes = new HashSet<>(Arrays.asList("scope1", "scope2")); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.addAll(requestedScopes); }).build(); // No scopes previously approved OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthenticationResult = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); authorizationConsentAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationConsentAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationConsentAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -525,15 +524,15 @@ public class OAuth2AuthorizationEndpointFilterTests { throws Exception { Set approvedScopes = new HashSet<>(Arrays.asList("scope1", "scope2")); Set requestedScopes = new HashSet<>(Arrays.asList("scope3", "scope4")); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.addAll(approvedScopes); scopes.addAll(requestedScopes); }).build(); OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthenticationResult = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, approvedScopes, null); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, approvedScopes, null); authorizationConsentAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationConsentAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationConsentAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -556,15 +555,15 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestAuthenticatedThenAuthorizationResponse() throws Exception { - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris(redirectUris -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add("https://example.com?param=encoded%20parameter%20value"); }).build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, this.authorizationCode, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, this.authorizationCode, registeredClient.getRedirectUris().iterator().next(), "client state", registeredClient.getScopes()); authorizationCodeRequestAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); request.addParameter("custom-param", "custom-value-1", "custom-value-2"); @@ -581,14 +580,14 @@ public class OAuth2AuthorizationEndpointFilterTests { verifyNoInteractions(filterChain); assertThat(authorizationCodeRequestAuthenticationCaptor.getValue().getDetails()) - .asInstanceOf(type(WebAuthenticationDetails.class)) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); // Assert that multi-valued request parameters are preserved assertThat(authorizationCodeRequestAuthenticationCaptor.getValue().getAdditionalParameters()) - .extracting(params -> params.get("custom-param")) - .asInstanceOf(type(String[].class)) + .extracting((params) -> params.get("custom-param")) + .asInstanceOf(InstanceOfAssertFactories.type(String[].class)) .isEqualTo(new String[] { "custom-value-1", "custom-value-2" }); assertThat(response.getStatus()).isEqualTo(HttpStatus.FOUND.value()); assertThat(response.getRedirectedUrl()) @@ -598,15 +597,15 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthenticationRequestAuthenticatedThenAuthorizationResponse() throws Exception { // Setup OpenID Connect request - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add(OidcScopes.OPENID); }).build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, this.authorizationCode, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, this.authorizationCode, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes()); authorizationCodeRequestAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); request.setMethod("POST"); // OpenID Connect supports POST method diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationServerMetadataEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationServerMetadataEndpointFilterTests.java index f3e5dbc0..fed24e8c 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationServerMetadataEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationServerMetadataEndpointFilterTests.java @@ -18,7 +18,6 @@ package org.springframework.security.oauth2.server.authorization.web; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2ClientAuthenticationFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2ClientAuthenticationFilterTests.java index 918b9d6b..97dc1750 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2ClientAuthenticationFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2ClientAuthenticationFilterTests.java @@ -20,7 +20,7 @@ import java.nio.charset.StandardCharsets; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -51,12 +51,11 @@ import org.springframework.security.web.util.matcher.RequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.InstanceOfAssertFactories.type; 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.when; /** * Tests for {@link OAuth2ClientAuthenticationFilter}. @@ -156,8 +155,8 @@ public class OAuth2ClientAuthenticationFilterTests { @Test public void doFilterWhenRequestMatchesAndInvalidCredentialsThenInvalidRequestError() throws Exception { - when(this.authenticationConverter.convert(any(HttpServletRequest.class))).thenThrow( - new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST)); + given(this.authenticationConverter.convert(any(HttpServletRequest.class))) + .willThrow(new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST)); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); @@ -196,8 +195,9 @@ public class OAuth2ClientAuthenticationFilterTests { } private void assertWhenInvalidClientIdThenInvalidRequestError(String clientId) throws Exception { - when(this.authenticationConverter.convert(any(HttpServletRequest.class))).thenReturn( - new OAuth2ClientAuthenticationToken(clientId, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, "secret", null)); + given(this.authenticationConverter.convert(any(HttpServletRequest.class))) + .willReturn(new OAuth2ClientAuthenticationToken(clientId, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, + "secret", null)); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); @@ -217,10 +217,11 @@ public class OAuth2ClientAuthenticationFilterTests { @Test public void doFilterWhenRequestMatchesAndBadCredentialsThenInvalidClientError() throws Exception { - when(this.authenticationConverter.convert(any(HttpServletRequest.class))).thenReturn( - new OAuth2ClientAuthenticationToken("clientId", ClientAuthenticationMethod.CLIENT_SECRET_BASIC, "invalid-secret", null)); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenThrow( - new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT)); + given(this.authenticationConverter.convert(any(HttpServletRequest.class))) + .willReturn(new OAuth2ClientAuthenticationToken("clientId", ClientAuthenticationMethod.CLIENT_SECRET_BASIC, + "invalid-secret", null)); + given(this.authenticationManager.authenticate(any(Authentication.class))) + .willThrow(new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT)); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); @@ -243,11 +244,11 @@ public class OAuth2ClientAuthenticationFilterTests { final String remoteAddress = "remote-address"; RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.authenticationConverter.convert(any(HttpServletRequest.class))) - .thenReturn(new OAuth2ClientAuthenticationToken(registeredClient.getClientId(), + given(this.authenticationConverter.convert(any(HttpServletRequest.class))) + .willReturn(new OAuth2ClientAuthenticationToken(registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null)); - when(this.authenticationManager.authenticate(any(Authentication.class))) - .thenReturn(new OAuth2ClientAuthenticationToken(registeredClient, + given(this.authenticationManager.authenticate(any(Authentication.class))) + .willReturn(new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret())); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); @@ -270,7 +271,7 @@ public class OAuth2ClientAuthenticationFilterTests { verify(this.authenticationManager).authenticate(authenticationRequestCaptor.capture()); assertThat(authenticationRequestCaptor).extracting(ArgumentCaptor::getValue) .extracting(OAuth2ClientAuthenticationToken::getDetails) - .asInstanceOf(type(WebAuthenticationDetails.class)) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(remoteAddress); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceAuthorizationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceAuthorizationEndpointFilterTests.java index 3a27e2b6..2d39cff7 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceAuthorizationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceAuthorizationEndpointFilterTests.java @@ -18,9 +18,11 @@ package org.springframework.security.oauth2.server.authorization.web; import java.io.IOException; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.Map; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -56,15 +58,13 @@ import org.springframework.security.web.authentication.AuthenticationFailureHand import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.WebAuthenticationDetails; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.InstanceOfAssertFactories.type; 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.when; /** * Tests for {@link OAuth2DeviceAuthorizationEndpointFilter}. @@ -195,7 +195,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @Test public void doFilterWhenDeviceAuthorizationRequestThenDeviceAuthorizationResponse() throws Exception { Authentication authenticationResult = createAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -219,11 +219,11 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { assertThat(deviceAuthorizationRequestAuthentication.getPrincipal()).isEqualTo(clientPrincipal); assertThat(deviceAuthorizationRequestAuthentication.getScopes()).isEmpty(); assertThat(deviceAuthorizationRequestAuthentication.getAdditionalParameters()).containsExactly( - entry("custom-param-1", "custom-value-1"), - entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); + Map.entry("custom-param-1", "custom-value-1"), + Map.entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); // @formatter:off assertThat(deviceAuthorizationRequestAuthentication.getDetails()) - .asInstanceOf(type(WebAuthenticationDetails.class)) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); // @formatter:on @@ -246,7 +246,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); OAuth2AuthenticationException authenticationException = new OAuth2AuthenticationException( new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, "Invalid request", "error-uri")); - when(authenticationConverter.convert(any(HttpServletRequest.class))).thenThrow(authenticationException); + given(authenticationConverter.convert(any(HttpServletRequest.class))).willThrow(authenticationException); this.filter.setAuthenticationConverter(authenticationConverter); MockHttpServletRequest request = createRequest(); @@ -267,7 +267,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @Test public void doFilterWhenCustomDeviceAuthorizationEndpointUriThenUsed() throws Exception { Authentication authenticationResult = createAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -288,7 +288,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthenticationConverterSetThenUsed() throws Exception { Authentication authenticationResult = createAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -296,7 +296,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); OAuth2DeviceAuthorizationRequestAuthenticationToken authenticationRequest = new OAuth2DeviceAuthorizationRequestAuthenticationToken( clientPrincipal, AUTHORIZATION_URI, null, null); - when(authenticationConverter.convert(any(HttpServletRequest.class))).thenReturn(authenticationRequest); + given(authenticationConverter.convert(any(HttpServletRequest.class))).willReturn(authenticationRequest); this.filter.setAuthenticationConverter(authenticationConverter); MockHttpServletRequest request = createRequest(); @@ -313,7 +313,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthenticationDetailsSourceSetThenUsed() throws Exception { Authentication authenticationResult = createAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -325,8 +325,8 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @SuppressWarnings("unchecked") AuthenticationDetailsSource authenticationDetailsSource = mock( AuthenticationDetailsSource.class); - when(authenticationDetailsSource.buildDetails(any(HttpServletRequest.class))) - .thenReturn(new WebAuthenticationDetails(request)); + given(authenticationDetailsSource.buildDetails(any(HttpServletRequest.class))) + .willReturn(new WebAuthenticationDetails(request)); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); this.filter.doFilter(request, response, filterChain); @@ -340,7 +340,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthenticationSuccessHandlerSetThenUsed() throws Exception { Authentication authenticationResult = createAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -363,7 +363,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { public void doFilterWhenAuthenticationFailureHandlerSetThenUsed() throws Exception { OAuth2AuthenticationException authenticationException = new OAuth2AuthenticationException( OAuth2ErrorCodes.INVALID_REQUEST); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenThrow(authenticationException); + given(this.authenticationManager.authenticate(any(Authentication.class))).willThrow(authenticationException); Authentication clientPrincipal = (Authentication) createAuthentication().getPrincipal(); mockSecurityContext(clientPrincipal); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilterTests.java index fcabda39..f755e75c 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilterTests.java @@ -19,11 +19,11 @@ import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.util.Collections; import java.util.HashSet; +import java.util.Map; import java.util.Set; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -55,14 +55,13 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.web.util.UriComponentsBuilder; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; 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.when; /** * Tests for {@link OAuth2DeviceVerificationEndpointFilter}. @@ -169,7 +168,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @Test public void doFilterWhenUnauthenticatedThenPassThrough() throws Exception { TestingAuthenticationToken unauthenticatedResult = new TestingAuthenticationToken("user", null); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(unauthenticatedResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(unauthenticatedResult); MockHttpServletRequest request = createRequest(); request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE); @@ -184,7 +183,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @Test public void doFilterWhenDeviceAuthorizationConsentRequestThenSuccess() throws Exception { Authentication authenticationResult = createDeviceVerificationAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -218,14 +217,14 @@ public class OAuth2DeviceVerificationEndpointFilterTests { assertThat(deviceAuthorizationConsentAuthentication.getUserCode()).isEqualTo(USER_CODE); assertThat(deviceAuthorizationConsentAuthentication.getScopes()).containsExactly("scope-1", "scope-2"); assertThat(deviceAuthorizationConsentAuthentication.getAdditionalParameters()).containsExactly( - entry("custom-param-1", "custom-value-1"), - entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); + Map.entry("custom-param-1", "custom-value-1"), + Map.entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); } @Test public void doFilterWhenDeviceVerificationRequestAndConsentNotRequiredThenSuccess() throws Exception { Authentication authenticationResult = createDeviceVerificationAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -249,13 +248,13 @@ public class OAuth2DeviceVerificationEndpointFilterTests { assertThat(deviceVerificationAuthentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class); assertThat(deviceVerificationAuthentication.getUserCode()).isEqualTo(USER_CODE); assertThat(deviceVerificationAuthentication.getAdditionalParameters()) - .containsExactly(entry("custom-param-1", "custom-value-1")); + .containsExactly(Map.entry("custom-param-1", "custom-value-1")); } @Test public void doFilterWhenDeviceVerificationRequestAndConsentRequiredThenConsentScreen() throws Exception { Authentication authenticationResult = createDeviceAuthorizationConsentAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); MockHttpServletRequest request = createRequest(); request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE); @@ -277,7 +276,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { public void doFilterWhenDeviceVerificationRequestAndConsentRequiredWithPreviouslyApprovedThenConsentScreen() throws Exception { Authentication authenticationResult = createDeviceAuthorizationConsentAuthenticationWithAuthorizedScopes(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); MockHttpServletRequest request = createRequest(); request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE); @@ -299,7 +298,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { public void doFilterWhenDeviceVerificationRequestAndConsentRequiredAndConsentPageSetThenRedirect() throws Exception { Authentication authentication = createDeviceAuthorizationConsentAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authentication); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authentication); MockHttpServletRequest request = createRequest(); request.setScheme("https"); @@ -327,13 +326,13 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @Test public void doFilterWhenAuthenticationConverterSetThenUsed() throws Exception { Authentication authenticationResult = createDeviceVerificationAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); OAuth2DeviceVerificationAuthenticationToken deviceVerificationAuthentication = new OAuth2DeviceVerificationAuthenticationToken( (Authentication) authenticationResult.getPrincipal(), USER_CODE, Collections.emptyMap()); - when(authenticationConverter.convert(any(HttpServletRequest.class))) - .thenReturn(deviceVerificationAuthentication); + given(authenticationConverter.convert(any(HttpServletRequest.class))) + .willReturn(deviceVerificationAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); MockHttpServletRequest request = createRequest(); @@ -353,7 +352,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @Test public void doFilterWhenAuthenticationDetailsSourceSetThenUsed() throws Exception { Authentication authenticationResult = createDeviceVerificationAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); MockHttpServletRequest request = createRequest(); request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE); @@ -364,8 +363,8 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @SuppressWarnings("unchecked") AuthenticationDetailsSource authenticationDetailsSource = mock( AuthenticationDetailsSource.class); - when(authenticationDetailsSource.buildDetails(any(HttpServletRequest.class))) - .thenReturn(new WebAuthenticationDetails(request)); + given(authenticationDetailsSource.buildDetails(any(HttpServletRequest.class))) + .willReturn(new WebAuthenticationDetails(request)); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); this.filter.doFilter(request, response, filterChain); @@ -380,7 +379,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @Test public void doFilterWhenAuthenticationSuccessHandlerSetThenUsed() throws Exception { Authentication authenticationResult = createDeviceVerificationAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); @@ -402,7 +401,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { public void doFilterWhenAuthenticationFailureHandlerSetThenUsed() throws Exception { OAuth2AuthenticationException authenticationException = new OAuth2AuthenticationException( OAuth2ErrorCodes.INVALID_REQUEST); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenThrow(authenticationException); + given(this.authenticationManager.authenticate(any(Authentication.class))).willThrow(authenticationException); AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenEndpointFilterTests.java index 21cc8f56..fc3bce20 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenEndpointFilterTests.java @@ -21,11 +21,11 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Map; +import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - -import com.fasterxml.jackson.databind.ObjectMapper; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -67,12 +67,11 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; -import static org.assertj.core.api.InstanceOfAssertFactories.type; 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.when; /** * Tests for {@link OAuth2TokenEndpointFilter}. @@ -247,7 +246,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken, refreshToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -275,7 +274,8 @@ public class OAuth2TokenEndpointFilterTests { assertThat(authorizationCodeAuthentication.getAdditionalParameters()).containsExactly( entry("custom-param-1", "custom-value-1"), entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); - assertThat(authorizationCodeAuthentication.getDetails()).asInstanceOf(type(WebAuthenticationDetails.class)) + assertThat(authorizationCodeAuthentication.getDetails()) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); @@ -314,7 +314,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -339,7 +339,8 @@ public class OAuth2TokenEndpointFilterTests { assertThat(clientCredentialsAuthentication.getAdditionalParameters()).containsExactly( entry("custom-param-1", "custom-value-1"), entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); - assertThat(clientCredentialsAuthentication.getDetails()).asInstanceOf(type(WebAuthenticationDetails.class)) + assertThat(clientCredentialsAuthentication.getDetails()) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); @@ -401,7 +402,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken, refreshToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -427,7 +428,8 @@ public class OAuth2TokenEndpointFilterTests { assertThat(refreshTokenAuthenticationToken.getAdditionalParameters()).containsExactly( entry("custom-param-1", "custom-value-1"), entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); - assertThat(refreshTokenAuthenticationToken.getDetails()).asInstanceOf(type(WebAuthenticationDetails.class)) + assertThat(refreshTokenAuthenticationToken.getDetails()) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); @@ -458,7 +460,7 @@ public class OAuth2TokenEndpointFilterTests { AuthenticationDetailsSource authenticationDetailsSource = mock( AuthenticationDetailsSource.class); WebAuthenticationDetails webAuthenticationDetails = new WebAuthenticationDetails(request); - when(authenticationDetailsSource.buildDetails(any())).thenReturn(webAuthenticationDetails); + given(authenticationDetailsSource.buildDetails(any())).willReturn(webAuthenticationDetails); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", @@ -467,7 +469,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -491,7 +493,7 @@ public class OAuth2TokenEndpointFilterTests { "code", clientPrincipal, null, null); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); - when(authenticationConverter.convert(any())).thenReturn(authorizationCodeAuthentication); + given(authenticationConverter.convert(any())).willReturn(authorizationCodeAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", @@ -500,7 +502,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -529,7 +531,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilterTests.java index 4a90ed80..37fc4b86 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilterTests.java @@ -23,7 +23,6 @@ import java.util.HashSet; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -60,10 +59,10 @@ import static org.assertj.core.api.Assertions.assertThat; 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.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.when; /** * Tests for {@link OAuth2TokenIntrospectionEndpointFilter}. @@ -199,7 +198,7 @@ public class OAuth2TokenIntrospectionEndpointFilterTests { .username("authorizing-username") .issuedAt(accessToken.getIssuedAt()) .expiresAt(accessToken.getExpiresAt()) - .scopes(scopes -> scopes.addAll(accessToken.getScopes())) + .scopes((scopes) -> scopes.addAll(accessToken.getScopes())) .tokenType(accessToken.getTokenType().getValue()) .notBefore(accessToken.getIssuedAt()) .subject("authorizing-subject") @@ -211,7 +210,7 @@ public class OAuth2TokenIntrospectionEndpointFilterTests { OAuth2TokenIntrospectionAuthenticationToken tokenIntrospectionAuthenticationResult = new OAuth2TokenIntrospectionAuthenticationToken( accessToken.getTokenValue(), clientPrincipal, tokenClaims); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenIntrospectionAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(tokenIntrospectionAuthenticationResult); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -269,10 +268,10 @@ public class OAuth2TokenIntrospectionEndpointFilterTests { accessToken.getTokenValue(), clientPrincipal, OAuth2TokenType.ACCESS_TOKEN.getValue(), null); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); - when(authenticationConverter.convert(any())).thenReturn(tokenIntrospectionAuthentication); + given(authenticationConverter.convert(any())).willReturn(tokenIntrospectionAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenIntrospectionAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(tokenIntrospectionAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -302,7 +301,7 @@ public class OAuth2TokenIntrospectionEndpointFilterTests { AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenIntrospectionAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(tokenIntrospectionAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -330,7 +329,7 @@ public class OAuth2TokenIntrospectionEndpointFilterTests { AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); - when(this.authenticationManager.authenticate(any())).thenThrow(OAuth2AuthenticationException.class); + given(this.authenticationManager.authenticate(any())).willThrow(OAuth2AuthenticationException.class); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilterTests.java index 5940e3a2..6b5bbb6b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilterTests.java @@ -24,7 +24,6 @@ import java.util.function.Consumer; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -57,10 +56,10 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand 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.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2TokenRevocationEndpointFilter}. @@ -153,21 +152,21 @@ public class OAuth2TokenRevocationEndpointFilterTests { @Test public void doFilterWhenTokenRevocationRequestMissingTokenThenInvalidRequestError() throws Exception { doFilterWhenTokenRevocationRequestInvalidParameterThenError(OAuth2ParameterNames.TOKEN, - OAuth2ErrorCodes.INVALID_REQUEST, request -> request.removeParameter(OAuth2ParameterNames.TOKEN)); + OAuth2ErrorCodes.INVALID_REQUEST, (request) -> request.removeParameter(OAuth2ParameterNames.TOKEN)); } @Test public void doFilterWhenTokenRevocationRequestMultipleTokenThenInvalidRequestError() throws Exception { doFilterWhenTokenRevocationRequestInvalidParameterThenError(OAuth2ParameterNames.TOKEN, OAuth2ErrorCodes.INVALID_REQUEST, - request -> request.addParameter(OAuth2ParameterNames.TOKEN, "token-2")); + (request) -> request.addParameter(OAuth2ParameterNames.TOKEN, "token-2")); } @Test public void doFilterWhenTokenRevocationRequestMultipleTokenTypeHintThenInvalidRequestError() throws Exception { doFilterWhenTokenRevocationRequestInvalidParameterThenError(OAuth2ParameterNames.TOKEN_TYPE_HINT, - OAuth2ErrorCodes.INVALID_REQUEST, request -> request.addParameter(OAuth2ParameterNames.TOKEN_TYPE_HINT, - OAuth2TokenType.ACCESS_TOKEN.getValue())); + OAuth2ErrorCodes.INVALID_REQUEST, (request) -> request + .addParameter(OAuth2ParameterNames.TOKEN_TYPE_HINT, OAuth2TokenType.ACCESS_TOKEN.getValue())); } @Test @@ -181,7 +180,7 @@ public class OAuth2TokenRevocationEndpointFilterTests { OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication = new OAuth2TokenRevocationAuthenticationToken( accessToken, clientPrincipal); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenRevocationAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(tokenRevocationAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -211,10 +210,10 @@ public class OAuth2TokenRevocationEndpointFilterTests { accessToken, clientPrincipal); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); - when(authenticationConverter.convert(any())).thenReturn(tokenRevocationAuthentication); + given(authenticationConverter.convert(any())).willReturn(tokenRevocationAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenRevocationAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(tokenRevocationAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -243,7 +242,7 @@ public class OAuth2TokenRevocationEndpointFilterTests { AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenRevocationAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(tokenRevocationAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -267,7 +266,7 @@ public class OAuth2TokenRevocationEndpointFilterTests { AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); - when(this.authenticationManager.authenticate(any())).thenThrow(OAuth2AuthenticationException.class); + given(this.authenticationManager.authenticate(any())).willThrow(OAuth2AuthenticationException.class); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretBasicAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretBasicAuthenticationConverterTests.java index 028abe14..133ffd39 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretBasicAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretBasicAuthenticationConverterTests.java @@ -66,7 +66,7 @@ public class ClientSecretBasicAuthenticationConverterTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.AUTHORIZATION, "Basic "); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @@ -76,7 +76,7 @@ public class ClientSecretBasicAuthenticationConverterTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.AUTHORIZATION, "Basic clientId:secret"); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @@ -87,7 +87,7 @@ public class ClientSecretBasicAuthenticationConverterTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth("clientId", "")); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretPostAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretPostAuthenticationConverterTests.java index e1d91eca..95148b90 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretPostAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretPostAuthenticationConverterTests.java @@ -53,7 +53,7 @@ public class ClientSecretPostAuthenticationConverterTests { request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-1"); request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-2"); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @@ -73,7 +73,7 @@ public class ClientSecretPostAuthenticationConverterTests { request.addParameter(OAuth2ParameterNames.CLIENT_SECRET, "client-secret-1"); request.addParameter(OAuth2ParameterNames.CLIENT_SECRET, "client-secret-2"); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/JwtClientAssertionAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/JwtClientAssertionAuthenticationConverterTests.java index 1dcf3cf5..7874be2c 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/JwtClientAssertionAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/JwtClientAssertionAuthenticationConverterTests.java @@ -124,7 +124,7 @@ public class JwtClientAssertionAuthenticationConverterTests { private void assertThrown(MockHttpServletRequest request, String errorCode) { assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(errorCode); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationConsentAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationConsentAuthenticationConverterTests.java index dec8f509..c7ec48ae 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationConsentAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationConsentAuthenticationConverterTests.java @@ -15,6 +15,8 @@ */ package org.springframework.security.oauth2.server.authorization.web.authentication; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,7 +33,6 @@ import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceAuthorizationConsentAuthenticationToken; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -280,8 +281,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationConverterTests { assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class); assertThat(authentication.getUserCode()).isEqualTo(USER_CODE); assertThat(authentication.getScopes()).containsExactly("message.read", "message.write"); - assertThat(authentication.getAdditionalParameters()).containsExactly(entry("param-1", "value-1"), - entry("param-2", new String[] { "value-1", "value-2" })); + assertThat(authentication.getAdditionalParameters()).containsExactly(Map.entry("param-1", "value-1"), + Map.entry("param-2", new String[] { "value-1", "value-2" })); } @Test diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationRequestAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationRequestAuthenticationConverterTests.java index ab641ce2..7296e35d 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationRequestAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationRequestAuthenticationConverterTests.java @@ -15,6 +15,8 @@ */ package org.springframework.security.oauth2.server.authorization.web.authentication; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,7 +32,6 @@ import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceAuthorizationRequestAuthenticationToken; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -109,8 +110,8 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationConverterTests { assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class); assertThat(authentication.getAuthorizationUri()).endsWith(AUTHORIZATION_URI); assertThat(authentication.getScopes()).containsExactly("message.read", "message.write"); - assertThat(authentication.getAdditionalParameters()).containsExactly(entry("param-1", "value-1"), - entry("param-2", new String[] { "value-1", "value-2" })); + assertThat(authentication.getAdditionalParameters()).containsExactly(Map.entry("param-1", "value-1"), + Map.entry("param-2", new String[] { "value-1", "value-2" })); } private static MockHttpServletRequest createRequest() { diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceCodeAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceCodeAuthenticationConverterTests.java index 4aed04fa..bb84e9f2 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceCodeAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceCodeAuthenticationConverterTests.java @@ -15,6 +15,8 @@ */ package org.springframework.security.oauth2.server.authorization.web.authentication; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -32,7 +34,6 @@ import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceCodeAuthenticationToken; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -116,8 +117,8 @@ public class OAuth2DeviceCodeAuthenticationConverterTests { assertThat(authentication).isNotNull(); assertThat(authentication.getDeviceCode()).isEqualTo(DEVICE_CODE); assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class); - assertThat(authentication.getAdditionalParameters()).containsExactly(entry("param-1", "value-1"), - entry("param-2", new String[] { "value-1", "value-2" })); + assertThat(authentication.getAdditionalParameters()).containsExactly(Map.entry("param-1", "value-1"), + Map.entry("param-2", new String[] { "value-1", "value-2" })); } private static MockHttpServletRequest createRequest() { diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceVerificationAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceVerificationAuthenticationConverterTests.java index a8e2b7ad..5ab5731f 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceVerificationAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceVerificationAuthenticationConverterTests.java @@ -15,6 +15,8 @@ */ package org.springframework.security.oauth2.server.authorization.web.authentication; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -33,7 +35,6 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceVerificationAuthenticationToken; import org.springframework.web.util.UriComponentsBuilder; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -179,8 +180,8 @@ public class OAuth2DeviceVerificationAuthenticationConverterTests { assertThat(authentication).isNotNull(); assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class); assertThat(authentication.getUserCode()).isEqualTo(USER_CODE); - assertThat(authentication.getAdditionalParameters()).containsExactly(entry("param-1", "value-1"), - entry("param-2", new String[] { "value-1", "value-2" })); + assertThat(authentication.getAdditionalParameters()).containsExactly(Map.entry("param-1", "value-1"), + Map.entry("param-2", new String[] { "value-1", "value-2" })); } private static MockHttpServletRequest createRequest() { diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/PublicClientAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/PublicClientAuthenticationConverterTests.java index 5106e240..c522b3e6 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/PublicClientAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/PublicClientAuthenticationConverterTests.java @@ -52,7 +52,7 @@ public class PublicClientAuthenticationConverterTests { MockHttpServletRequest request = createPkceTokenRequest(); request.removeParameter(OAuth2ParameterNames.CLIENT_ID); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @@ -62,7 +62,7 @@ public class PublicClientAuthenticationConverterTests { MockHttpServletRequest request = createPkceTokenRequest(); request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-2"); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @@ -72,7 +72,7 @@ public class PublicClientAuthenticationConverterTests { MockHttpServletRequest request = createPkceTokenRequest(); request.addParameter(PkceParameterNames.CODE_VERIFIER, "code-verifier-2"); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } From 365ae4e56aa3e8f3bfd5e71b4ae391a81d3381fc Mon Sep 17 00:00:00 2001 From: Joe Grandja <10884212+jgrandja@users.noreply.github.com> Date: Thu, 23 May 2024 08:29:08 -0400 Subject: [PATCH 4/5] Fix checkstyle violations for main module in 1.2.x Issue gh-1624 --- ...JdbcOAuth2AuthorizationConsentService.java | 22 ++++++++-------- .../JdbcOAuth2AuthorizationService.java | 22 ++++++++-------- ...ionServerBeanRegistrationAotProcessor.java | 10 ++++---- .../JdbcRegisteredClientRepository.java | 22 ++++++++-------- ...RegistrationRegisteredClientConverter.java | 25 +++++++++++-------- ...uth2ErrorAuthenticationFailureHandler.java | 3 +-- 6 files changed, 54 insertions(+), 50 deletions(-) diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentService.java index b7bffe68..bf8660ac 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentService.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentService.java @@ -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 } + 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")); + } + + } + } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java index 9e1e7d22..316a1b0e 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java @@ -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, " @@ -822,4 +811,15 @@ public class JdbcOAuth2AuthorizationService implements OAuth2AuthorizationServic } + 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")); + } + + } + } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/aot/hint/OAuth2AuthorizationServerBeanRegistrationAotProcessor.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/aot/hint/OAuth2AuthorizationServerBeanRegistrationAotProcessor.java index f5739ba9..70bbef85 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/aot/hint/OAuth2AuthorizationServerBeanRegistrationAotProcessor.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/aot/hint/OAuth2AuthorizationServerBeanRegistrationAotProcessor.java @@ -69,10 +69,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 @@ -113,7 +113,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 @@ -122,7 +122,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 @@ -162,7 +162,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)); diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java index b521cdc7..4fe3a52f 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java @@ -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, " @@ -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")); + } + + } + } diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/converter/OidcClientRegistrationRegisteredClientConverter.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/converter/OidcClientRegistrationRegisteredClientConverter.java index ffd76019..2253bb58 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/converter/OidcClientRegistrationRegisteredClientConverter.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/converter/OidcClientRegistrationRegisteredClientConverter.java @@ -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 } if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) { - builder.scopes(scopes -> + builder.scopes((scopes) -> scopes.addAll(clientRegistration.getScopes())); } @@ -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; diff --git a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2ErrorAuthenticationFailureHandler.java b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2ErrorAuthenticationFailureHandler.java index 07c27a3a..30c9bf11 100644 --- a/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2ErrorAuthenticationFailureHandler.java +++ b/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2ErrorAuthenticationFailureHandler.java @@ -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; * Error Response}. * * @author Dmitriy Dubson + * @since 1.2 * @see AuthenticationFailureHandler * @see OAuth2ErrorHttpMessageConverter - * @since 1.2 */ public final class OAuth2ErrorAuthenticationFailureHandler implements AuthenticationFailureHandler { From 9d336ebd6515996611246899fa18ba3c76428cd0 Mon Sep 17 00:00:00 2001 From: Joe Grandja <10884212+jgrandja@users.noreply.github.com> Date: Thu, 23 May 2024 08:34:35 -0400 Subject: [PATCH 5/5] Fix checkstyle violations for test module in 1.2.x Issue gh-1624 --- .../web/configurers/OAuth2RefreshTokenGrantTests.java | 9 ++++----- .../web/configurers/OidcClientRegistrationTests.java | 9 ++++----- .../config/annotation/web/configurers/OidcTests.java | 6 +++--- 3 files changed, 11 insertions(+), 13 deletions(-) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java index c70876fb..2153b774 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java @@ -23,11 +23,10 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import jakarta.servlet.http.HttpServletRequest; - import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -376,7 +375,7 @@ public class OAuth2RefreshTokenGrantTests { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .clientAuthentication(clientAuthentication -> + .clientAuthentication((clientAuthentication) -> clientAuthentication .authenticationConverter( new PublicClientRefreshTokenAuthenticationConverter()) @@ -387,10 +386,10 @@ public class OAuth2RefreshTokenGrantTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java index 736bdd4c..fb81cef3 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java @@ -25,11 +25,10 @@ import java.util.function.Consumer; import javax.crypto.spec.SecretKeySpec; -import jakarta.servlet.http.HttpServletResponse; - import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; +import jakarta.servlet.http.HttpServletResponse; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterAll; @@ -685,7 +684,7 @@ public class OidcClientRegistrationTests { private Consumer> configureClientRegistrationConverters() { // @formatter:off return (authenticationProviders) -> - authenticationProviders.forEach(authenticationProvider -> { + authenticationProviders.forEach((authenticationProvider) -> { List supportedCustomClientMetadata = List.of("custom-metadata-name-1", "custom-metadata-name-2"); if (authenticationProvider instanceof OidcClientRegistrationAuthenticationProvider provider) { provider.setRegisteredClientConverter(new CustomRegisteredClientConverter(supportedCustomClientMetadata)); @@ -769,7 +768,7 @@ public class OidcClientRegistrationTests { } - private static class CustomRegisteredClientConverter + private static final class CustomRegisteredClientConverter implements Converter { private final OidcClientRegistrationRegisteredClientConverter delegate = new OidcClientRegistrationRegisteredClientConverter(); @@ -799,7 +798,7 @@ public class OidcClientRegistrationTests { } - private static class CustomClientRegistrationConverter + private static final class CustomClientRegistrationConverter implements Converter { private final RegisteredClientOidcClientRegistrationConverter delegate = new RegisteredClientOidcClientRegistrationConverter(); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java index 5a3e8d17..82c7e6c4 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java @@ -737,7 +737,7 @@ public class OidcTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); http.apply(authorizationServerConfigurer); @@ -750,10 +750,10 @@ public class OidcTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)); + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)); return http.build(); }