Skip to content

Commit 80416c4

Browse files
committed
PKCE configuration - enabled by default
Signed-off-by: Rohan Naik <[email protected]>
1 parent 7a7d2ca commit 80416c4

File tree

8 files changed

+166
-83
lines changed

8 files changed

+166
-83
lines changed

config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurerTests.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ public void configureWhenAuthorizationCodeRequestThenRedirectForAuthorization()
156156
.andExpect(status().is3xxRedirection()).andReturn();
157157
assertThat(mvcResult.getResponse().getRedirectedUrl())
158158
.matches("https://provider.com/oauth2/authorize\\?" + "response_type=code&client_id=client-1&"
159-
+ "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1");
159+
+ "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
160160
// @formatter:on
161161
}
162162

@@ -166,9 +166,9 @@ public void configureWhenOauth2ClientInLambdaThenRedirectForAuthorization() thro
166166
MvcResult mvcResult = this.mockMvc.perform(get("/oauth2/authorization/registration-1"))
167167
.andExpect(status().is3xxRedirection())
168168
.andReturn();
169-
assertThat(mvcResult.getResponse().getRedirectedUrl())
170-
.matches("https://provider.com/oauth2/authorize\\?" + "response_type=code&client_id=client-1&"
171-
+ "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1");
169+
assertThat(mvcResult.getResponse().getRedirectedUrl()).matches("https://provider.com/oauth2/authorize\\?"
170+
+ "response_type=code&client_id=client-1&" + "scope=user&state=.{15,}&"
171+
+ "redirect_uri=http://localhost/client-1&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
172172
}
173173

174174
@Test
@@ -215,9 +215,9 @@ public void configureWhenRequestCacheProvidedAndClientAuthorizationRequiredExcep
215215
MvcResult mvcResult = this.mockMvc.perform(get("/resource1").with(user("user1")))
216216
.andExpect(status().is3xxRedirection())
217217
.andReturn();
218-
assertThat(mvcResult.getResponse().getRedirectedUrl())
219-
.matches("https://provider.com/oauth2/authorize\\?" + "response_type=code&client_id=client-1&"
220-
+ "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1");
218+
assertThat(mvcResult.getResponse().getRedirectedUrl()).matches("https://provider.com/oauth2/authorize\\?"
219+
+ "response_type=code&client_id=client-1&" + "scope=user&state=.{15,}&"
220+
+ "redirect_uri=http://localhost/client-1&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
221221
verify(requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
222222
}
223223

config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,9 @@ public void requestWhenAuthorizeThenRedirect() throws Exception {
112112
.andExpect(status().is3xxRedirection())
113113
.andReturn();
114114
// @formatter:on
115-
assertThat(result.getResponse().getRedirectedUrl()).matches(
116-
"https://accounts.google.com/o/oauth2/v2/auth\\?" + "response_type=code&client_id=google-client-id&"
117-
+ "scope=scope1%20scope2&state=.{15,}&redirect_uri=http://localhost/callback/google");
115+
assertThat(result.getResponse().getRedirectedUrl()).matches("https://accounts.google.com/o/oauth2/v2/auth\\?"
116+
+ "response_type=code&client_id=google-client-id&"
117+
+ "scope=scope1%20scope2&state=.{15,}&redirect_uri=http://localhost/callback/google&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
118118
}
119119

120120
@Test
@@ -134,9 +134,9 @@ public void requestWhenCustomClientRegistrationRepositoryThenCalled() throws Exc
134134
.andExpect(status().is3xxRedirection())
135135
.andReturn();
136136
// @formatter:on
137-
assertThat(result.getResponse().getRedirectedUrl()).matches(
138-
"https://accounts.google.com/o/oauth2/v2/auth\\?" + "response_type=code&client_id=google-client-id&"
139-
+ "scope=scope1%20scope2&state=.{15,}&redirect_uri=http://localhost/callback/google");
137+
assertThat(result.getResponse().getRedirectedUrl()).matches("https://accounts.google.com/o/oauth2/v2/auth\\?"
138+
+ "response_type=code&client_id=google-client-id&"
139+
+ "scope=scope1%20scope2&state=.{15,}&redirect_uri=http://localhost/callback/google&code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&code_challenge_method=S256");
140140
verify(this.clientRegistrationRepository).findByRegistrationId(any());
141141
}
142142

docs/modules/ROOT/pages/servlet/oauth2/client/core.adoc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ This information is available only if the Spring Boot property `spring.security.
6969
<15> `(userInfoEndpoint)authenticationMethod`: The authentication method used when sending the access token to the UserInfo Endpoint.
7070
The supported values are *header*, *form*, and *query*.
7171
<16> `userNameAttributeName`: The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user.
72-
<17> [[oauth2Client-client-registration-requireProofKey]]`requireProofKey`: If `true` or if `authorizationGrantType` is `none`, then PKCE will be enabled by default.
72+
<17> [[oauth2Client-client-registration-requireProofKey]]`requireProofKey`: If `true` or if `authorizationGrantType` is `none`, then PKCE will be enabled.
7373

7474
You can initially configure a `ClientRegistration` by using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint].
7575

oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistration.java

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -655,6 +655,10 @@ private ClientRegistration create() {
655655
clientRegistration.clientName = StringUtils.hasText(this.clientName) ? this.clientName
656656
: this.registrationId;
657657
clientRegistration.clientSettings = this.clientSettings;
658+
if (clientRegistration.clientSettings.requireProofKey) {
659+
clientRegistration.clientSettings.requireProofKey = AuthorizationGrantType.AUTHORIZATION_CODE
660+
.equals(this.authorizationGrantType);
661+
}
658662
return clientRegistration;
659663
}
660664

@@ -713,12 +717,6 @@ private void validateAuthorizationGrantTypes() {
713717
"AuthorizationGrantType: %s does not match the pre-defined constant %s and won't match a valid OAuth2AuthorizedClientProvider",
714718
this.authorizationGrantType, authorizationGrantType));
715719
}
716-
if (!AuthorizationGrantType.AUTHORIZATION_CODE.equals(this.authorizationGrantType)
717-
&& this.clientSettings.isRequireProofKey()) {
718-
throw new IllegalStateException(
719-
"clientSettings.isRequireProofKey=true is only valid with authorizationGrantType=AUTHORIZATION_CODE. Got authorizationGrantType="
720-
+ this.authorizationGrantType);
721-
}
722720
}
723721
}
724722

@@ -754,7 +752,7 @@ public static final class ClientSettings implements Serializable {
754752
@Serial
755753
private static final long serialVersionUID = 7495627155437124692L;
756754

757-
private boolean requireProofKey;
755+
private boolean requireProofKey = true;
758756

759757
private ClientSettings() {
760758

@@ -791,7 +789,7 @@ public static Builder builder() {
791789

792790
public static final class Builder {
793791

794-
private boolean requireProofKey;
792+
private boolean requireProofKey = true;
795793

796794
private Builder() {
797795
}

oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java

Lines changed: 71 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,10 @@
3434
import org.springframework.security.oauth2.core.AuthenticationMethod;
3535
import org.springframework.security.oauth2.core.AuthorizationGrantType;
3636
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
37+
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
38+
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
3739

38-
import static org.assertj.core.api.Assertions.assertThat;
39-
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
40-
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
40+
import static org.assertj.core.api.Assertions.*;
4141

4242
/**
4343
* Tests for {@link ClientRegistration}.
@@ -780,7 +780,7 @@ void buildWhenDefaultClientSettingsThenDefaulted() {
780780
// should not be null
781781
assertThat(clientRegistration.getClientSettings()).isNotNull();
782782
// proof key should be false for passivity
783-
assertThat(clientRegistration.getClientSettings().isRequireProofKey()).isFalse();
783+
assertThat(clientRegistration.getClientSettings().isRequireProofKey()).isTrue();
784784
}
785785

786786
// gh-16382
@@ -798,10 +798,64 @@ void buildWhenNewAuthorizationCodeAndPkceThenBuilds() {
798798
.tokenUri(TOKEN_URI)
799799
.build();
800800

801-
// proof key should be false for passivity
802801
assertThat(clientRegistration.getClientSettings().isRequireProofKey()).isTrue();
803802
}
804803

804+
@Test
805+
void buildWhenNewAuthorizationCodeAndPkceDisabledThenBuilds() {
806+
ClientRegistration.ClientSettings pkceEnabled = ClientRegistration.ClientSettings.builder()
807+
.requireProofKey(false)
808+
.build();
809+
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
810+
.clientId(CLIENT_ID)
811+
.clientSettings(pkceEnabled)
812+
.authorizationGrantType(new AuthorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()))
813+
.redirectUri(REDIRECT_URI)
814+
.authorizationUri(AUTHORIZATION_URI)
815+
.tokenUri(TOKEN_URI)
816+
.build();
817+
818+
assertThat(clientRegistration.getClientSettings().isRequireProofKey()).isFalse();
819+
}
820+
821+
@ParameterizedTest
822+
@MethodSource("privateClientAuthenticationMethods")
823+
void buildWhenNewAuthorizationCodeAndPrivateClientThenPkceEnabledAndBuilds(
824+
ClientAuthenticationMethod clientAuthenticationMethod) {
825+
ClientRegistration.ClientSettings pkceEnabled = ClientRegistration.ClientSettings.builder()
826+
.requireProofKey(true)
827+
.build();
828+
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
829+
.clientId(CLIENT_ID)
830+
.clientSettings(pkceEnabled)
831+
.authorizationGrantType(new AuthorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()))
832+
.clientAuthenticationMethod(clientAuthenticationMethod)
833+
.redirectUri(REDIRECT_URI)
834+
.authorizationUri(AUTHORIZATION_URI)
835+
.tokenUri(TOKEN_URI)
836+
.build();
837+
838+
assertThat(clientRegistration.getClientSettings().isRequireProofKey()).isTrue();
839+
}
840+
841+
@Test
842+
void buildWhenNewAuthorizationCodeAndPublicClientAndPkceDisabledThenBuilds() {
843+
ClientRegistration.ClientSettings pkceEnabled = ClientRegistration.ClientSettings.builder()
844+
.requireProofKey(false)
845+
.build();
846+
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
847+
.clientId(CLIENT_ID)
848+
.clientSettings(pkceEnabled)
849+
.authorizationGrantType(new AuthorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()))
850+
.clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
851+
.redirectUri(REDIRECT_URI)
852+
.authorizationUri(AUTHORIZATION_URI)
853+
.tokenUri(TOKEN_URI)
854+
.build();
855+
// even if this is an invalid state pkce will be applied later
856+
assertThat(clientRegistration.getClientSettings().isRequireProofKey()).isFalse();
857+
}
858+
805859
@ParameterizedTest
806860
@MethodSource("invalidPkceGrantTypes")
807861
void buildWhenInvalidGrantTypeForPkceThenException(AuthorizationGrantType invalidGrantType) {
@@ -816,10 +870,18 @@ void buildWhenInvalidGrantTypeForPkceThenException(AuthorizationGrantType invali
816870
.authorizationUri(AUTHORIZATION_URI)
817871
.tokenUri(TOKEN_URI);
818872

819-
assertThatIllegalStateException().describedAs(
820-
"clientSettings.isRequireProofKey=true is only valid with authorizationGrantType=AUTHORIZATION_CODE. Got authorizationGrantType={}",
821-
invalidGrantType)
822-
.isThrownBy(builder::build);
873+
ClientRegistration clientRegistration = builder.build();
874+
assertThat(clientRegistration.getClientSettings().isRequireProofKey()).isFalse();
875+
}
876+
877+
static List<ClientAuthenticationMethod> privateClientAuthenticationMethods() {
878+
return Arrays.stream(ClientAuthenticationMethod.class.getFields())
879+
.filter((field) -> Modifier.isFinal(field.getModifiers())
880+
&& field.getType() == ClientAuthenticationMethod.class)
881+
.map((field) -> getStaticValue(field, ClientAuthenticationMethod.class))
882+
.filter((authenticationMethod) -> authenticationMethod != ClientAuthenticationMethod.NONE)
883+
.map((authenticationMethod) -> new ClientAuthenticationMethod(authenticationMethod.getValue()))
884+
.collect(Collectors.toList());
823885
}
824886

825887
static List<AuthorizationGrantType> invalidPkceGrantTypes() {

0 commit comments

Comments
 (0)