Skip to content

Commit 5536dd9

Browse files
committed
Add JWK Set Endpoint Filter
Closes spring-projectsgh-82
1 parent 3cef381 commit 5536dd9

File tree

4 files changed

+323
-0
lines changed

4 files changed

+323
-0
lines changed

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

+4
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationProvider;
3333
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationProvider;
3434
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
35+
import org.springframework.security.oauth2.server.authorization.web.JwkSetEndpointFilter;
3536
import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter;
3637
import org.springframework.security.oauth2.server.authorization.web.OAuth2ClientAuthenticationFilter;
3738
import org.springframework.security.oauth2.server.authorization.web.OAuth2TokenEndpointFilter;
@@ -130,6 +131,9 @@ public void init(B builder) {
130131

131132
@Override
132133
public void configure(B builder) {
134+
JwkSetEndpointFilter jwkSetEndpointFilter = new JwkSetEndpointFilter(getKeyManager(builder));
135+
builder.addFilterBefore(postProcess(jwkSetEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class);
136+
133137
AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class);
134138

135139
OAuth2ClientAuthenticationFilter clientAuthenticationFilter =

oauth2-authorization-server/spring-security-oauth2-authorization-server.gradle

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ dependencies {
99
compile springCoreDependency
1010
compile 'com.fasterxml.jackson.core:jackson-databind'
1111

12+
testCompile project(path: ':spring-security-crypto2', configuration: 'tests')
1213
testCompile 'org.springframework:spring-webmvc'
1314
testCompile 'junit:junit'
1415
testCompile 'org.assertj:assertj-core'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
/*
2+
* Copyright 2020 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.security.oauth2.server.authorization.web;
17+
18+
import com.nimbusds.jose.JWSAlgorithm;
19+
import com.nimbusds.jose.jwk.Curve;
20+
import com.nimbusds.jose.jwk.ECKey;
21+
import com.nimbusds.jose.jwk.JWK;
22+
import com.nimbusds.jose.jwk.JWKSet;
23+
import com.nimbusds.jose.jwk.KeyUse;
24+
import com.nimbusds.jose.jwk.RSAKey;
25+
import org.springframework.http.HttpMethod;
26+
import org.springframework.http.MediaType;
27+
import org.springframework.security.crypto.keys.KeyManager;
28+
import org.springframework.security.crypto.keys.ManagedKey;
29+
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
30+
import org.springframework.security.web.util.matcher.RequestMatcher;
31+
import org.springframework.util.Assert;
32+
import org.springframework.web.filter.OncePerRequestFilter;
33+
34+
import javax.servlet.FilterChain;
35+
import javax.servlet.ServletException;
36+
import javax.servlet.http.HttpServletRequest;
37+
import javax.servlet.http.HttpServletResponse;
38+
import java.io.IOException;
39+
import java.io.Writer;
40+
import java.security.interfaces.ECPublicKey;
41+
import java.security.interfaces.RSAPublicKey;
42+
import java.util.Objects;
43+
import java.util.stream.Collectors;
44+
45+
/**
46+
* A {@code Filter} that processes JWK Set requests.
47+
*
48+
* @author Joe Grandja
49+
* @since 0.0.1
50+
* @see KeyManager
51+
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7517">JSON Web Key (JWK)</a>
52+
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7517#section-5">Section 5 JWK Set Format</a>
53+
*/
54+
public class JwkSetEndpointFilter extends OncePerRequestFilter {
55+
/**
56+
* The default endpoint {@code URI} for JWK Set requests.
57+
*/
58+
public static final String DEFAULT_JWK_SET_ENDPOINT_URI = "/oauth2/jwks";
59+
60+
private final KeyManager keyManager;
61+
private final RequestMatcher requestMatcher;
62+
63+
/**
64+
* Constructs a {@code JwkSetEndpointFilter} using the provided parameters.
65+
*
66+
* @param keyManager the key manager
67+
*/
68+
public JwkSetEndpointFilter(KeyManager keyManager) {
69+
this(keyManager, DEFAULT_JWK_SET_ENDPOINT_URI);
70+
}
71+
72+
/**
73+
* Constructs a {@code JwkSetEndpointFilter} using the provided parameters.
74+
*
75+
* @param keyManager the key manager
76+
* @param jwkSetEndpointUri the endpoint {@code URI} for JWK Set requests
77+
*/
78+
public JwkSetEndpointFilter(KeyManager keyManager, String jwkSetEndpointUri) {
79+
Assert.notNull(keyManager, "keyManager cannot be null");
80+
Assert.hasText(jwkSetEndpointUri, "jwkSetEndpointUri cannot be empty");
81+
this.keyManager = keyManager;
82+
this.requestMatcher = new AntPathRequestMatcher(jwkSetEndpointUri, HttpMethod.GET.name());
83+
}
84+
85+
@Override
86+
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
87+
throws ServletException, IOException {
88+
89+
if (!this.requestMatcher.matches(request)) {
90+
filterChain.doFilter(request, response);
91+
return;
92+
}
93+
94+
JWKSet jwkSet = buildJwkSet();
95+
96+
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
97+
try (Writer writer = response.getWriter()) {
98+
writer.write(jwkSet.toJSONObject().toString());
99+
}
100+
}
101+
102+
private JWKSet buildJwkSet() {
103+
return new JWKSet(
104+
this.keyManager.getKeys().stream()
105+
.filter(managedKey -> managedKey.isActive() && managedKey.isAsymmetric())
106+
.map(this::convert)
107+
.filter(Objects::nonNull)
108+
.collect(Collectors.toList())
109+
);
110+
}
111+
112+
private JWK convert(ManagedKey managedKey) {
113+
JWK jwk = null;
114+
if (managedKey.getPublicKey() instanceof RSAPublicKey) {
115+
RSAPublicKey publicKey = (RSAPublicKey) managedKey.getPublicKey();
116+
jwk = new RSAKey.Builder(publicKey)
117+
.keyUse(KeyUse.SIGNATURE)
118+
.algorithm(JWSAlgorithm.RS256)
119+
.keyID(managedKey.getKeyId())
120+
.build();
121+
} else if (managedKey.getPublicKey() instanceof ECPublicKey) {
122+
ECPublicKey publicKey = (ECPublicKey) managedKey.getPublicKey();
123+
Curve curve = Curve.forECParameterSpec(publicKey.getParams());
124+
jwk = new ECKey.Builder(curve, publicKey)
125+
.keyUse(KeyUse.SIGNATURE)
126+
.algorithm(JWSAlgorithm.ES256)
127+
.keyID(managedKey.getKeyId())
128+
.build();
129+
}
130+
return jwk;
131+
}
132+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
/*
2+
* Copyright 2020 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.security.oauth2.server.authorization.web;
17+
18+
import com.nimbusds.jose.JWSAlgorithm;
19+
import com.nimbusds.jose.jwk.ECKey;
20+
import com.nimbusds.jose.jwk.JWKSet;
21+
import com.nimbusds.jose.jwk.KeyUse;
22+
import com.nimbusds.jose.jwk.RSAKey;
23+
import org.junit.Before;
24+
import org.junit.Test;
25+
import org.springframework.http.MediaType;
26+
import org.springframework.mock.web.MockHttpServletRequest;
27+
import org.springframework.mock.web.MockHttpServletResponse;
28+
import org.springframework.security.crypto.keys.KeyManager;
29+
import org.springframework.security.crypto.keys.ManagedKey;
30+
import org.springframework.security.crypto.keys.TestManagedKeys;
31+
32+
import javax.servlet.FilterChain;
33+
import javax.servlet.http.HttpServletRequest;
34+
import javax.servlet.http.HttpServletResponse;
35+
import java.time.Instant;
36+
import java.util.Collections;
37+
import java.util.HashSet;
38+
import java.util.stream.Collectors;
39+
import java.util.stream.Stream;
40+
41+
import static org.assertj.core.api.Assertions.assertThat;
42+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
43+
import static org.mockito.ArgumentMatchers.any;
44+
import static org.mockito.Mockito.mock;
45+
import static org.mockito.Mockito.verify;
46+
import static org.mockito.Mockito.verifyNoInteractions;
47+
import static org.mockito.Mockito.when;
48+
49+
/**
50+
* Tests for {@link JwkSetEndpointFilter}.
51+
*
52+
* @author Joe Grandja
53+
*/
54+
public class JwkSetEndpointFilterTests {
55+
private KeyManager keyManager;
56+
private JwkSetEndpointFilter filter;
57+
58+
@Before
59+
public void setUp() {
60+
this.keyManager = mock(KeyManager.class);
61+
this.filter = new JwkSetEndpointFilter(this.keyManager);
62+
}
63+
64+
@Test
65+
public void constructorWhenKeyManagerNullThenThrowIllegalArgumentException() {
66+
assertThatThrownBy(() -> new JwkSetEndpointFilter(null))
67+
.isInstanceOf(IllegalArgumentException.class)
68+
.hasMessage("keyManager cannot be null");
69+
}
70+
71+
@Test
72+
public void constructorWhenJwkSetEndpointUriNullThenThrowIllegalArgumentException() {
73+
assertThatThrownBy(() -> new JwkSetEndpointFilter(this.keyManager, null))
74+
.isInstanceOf(IllegalArgumentException.class)
75+
.hasMessage("jwkSetEndpointUri cannot be empty");
76+
}
77+
78+
@Test
79+
public void doFilterWhenNotJwkSetRequestThenNotProcessed() throws Exception {
80+
String requestUri = "/path";
81+
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
82+
request.setServletPath(requestUri);
83+
MockHttpServletResponse response = new MockHttpServletResponse();
84+
FilterChain filterChain = mock(FilterChain.class);
85+
86+
this.filter.doFilter(request, response, filterChain);
87+
88+
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
89+
}
90+
91+
@Test
92+
public void doFilterWhenJwkSetRequestPostThenNotProcessed() throws Exception {
93+
String requestUri = JwkSetEndpointFilter.DEFAULT_JWK_SET_ENDPOINT_URI;
94+
MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri);
95+
request.setServletPath(requestUri);
96+
MockHttpServletResponse response = new MockHttpServletResponse();
97+
FilterChain filterChain = mock(FilterChain.class);
98+
99+
this.filter.doFilter(request, response, filterChain);
100+
101+
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
102+
}
103+
104+
@Test
105+
public void doFilterWhenAsymmetricKeysThenJwkSetResponse() throws Exception {
106+
ManagedKey rsaManagedKey = TestManagedKeys.rsaManagedKey().build();
107+
ManagedKey ecManagedKey = TestManagedKeys.ecManagedKey().build();
108+
when(this.keyManager.getKeys()).thenReturn(
109+
Stream.of(rsaManagedKey, ecManagedKey).collect(Collectors.toSet()));
110+
111+
String requestUri = JwkSetEndpointFilter.DEFAULT_JWK_SET_ENDPOINT_URI;
112+
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
113+
request.setServletPath(requestUri);
114+
MockHttpServletResponse response = new MockHttpServletResponse();
115+
FilterChain filterChain = mock(FilterChain.class);
116+
117+
this.filter.doFilter(request, response, filterChain);
118+
119+
verifyNoInteractions(filterChain);
120+
121+
assertThat(response.getContentType()).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
122+
123+
JWKSet jwkSet = JWKSet.parse(response.getContentAsString());
124+
assertThat(jwkSet.getKeys()).hasSize(2);
125+
126+
RSAKey rsaJwk = (RSAKey) jwkSet.getKeyByKeyId(rsaManagedKey.getKeyId());
127+
assertThat(rsaJwk).isNotNull();
128+
assertThat(rsaJwk.toRSAPublicKey()).isEqualTo(rsaManagedKey.getPublicKey());
129+
assertThat(rsaJwk.toRSAPrivateKey()).isNull();
130+
assertThat(rsaJwk.getKeyUse()).isEqualTo(KeyUse.SIGNATURE);
131+
assertThat(rsaJwk.getAlgorithm()).isEqualTo(JWSAlgorithm.RS256);
132+
133+
ECKey ecJwk = (ECKey) jwkSet.getKeyByKeyId(ecManagedKey.getKeyId());
134+
assertThat(ecJwk).isNotNull();
135+
assertThat(ecJwk.toECPublicKey()).isEqualTo(ecManagedKey.getPublicKey());
136+
assertThat(ecJwk.toECPublicKey()).isEqualTo(ecManagedKey.getPublicKey());
137+
assertThat(ecJwk.toECPrivateKey()).isNull();
138+
assertThat(ecJwk.getKeyUse()).isEqualTo(KeyUse.SIGNATURE);
139+
assertThat(ecJwk.getAlgorithm()).isEqualTo(JWSAlgorithm.ES256);
140+
}
141+
142+
@Test
143+
public void doFilterWhenSymmetricKeysThenJwkSetResponseEmpty() throws Exception {
144+
ManagedKey secretManagedKey = TestManagedKeys.secretManagedKey().build();
145+
when(this.keyManager.getKeys()).thenReturn(
146+
new HashSet<>(Collections.singleton(secretManagedKey)));
147+
148+
String requestUri = JwkSetEndpointFilter.DEFAULT_JWK_SET_ENDPOINT_URI;
149+
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
150+
request.setServletPath(requestUri);
151+
MockHttpServletResponse response = new MockHttpServletResponse();
152+
FilterChain filterChain = mock(FilterChain.class);
153+
154+
this.filter.doFilter(request, response, filterChain);
155+
156+
verifyNoInteractions(filterChain);
157+
158+
assertThat(response.getContentType()).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
159+
160+
JWKSet jwkSet = JWKSet.parse(response.getContentAsString());
161+
assertThat(jwkSet.getKeys()).isEmpty();
162+
}
163+
164+
@Test
165+
public void doFilterWhenNoActiveKeysThenJwkSetResponseEmpty() throws Exception {
166+
ManagedKey rsaManagedKey = TestManagedKeys.rsaManagedKey().deactivatedOn(Instant.now()).build();
167+
ManagedKey ecManagedKey = TestManagedKeys.ecManagedKey().deactivatedOn(Instant.now()).build();
168+
when(this.keyManager.getKeys()).thenReturn(
169+
Stream.of(rsaManagedKey, ecManagedKey).collect(Collectors.toSet()));
170+
171+
String requestUri = JwkSetEndpointFilter.DEFAULT_JWK_SET_ENDPOINT_URI;
172+
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
173+
request.setServletPath(requestUri);
174+
MockHttpServletResponse response = new MockHttpServletResponse();
175+
FilterChain filterChain = mock(FilterChain.class);
176+
177+
this.filter.doFilter(request, response, filterChain);
178+
179+
verifyNoInteractions(filterChain);
180+
181+
assertThat(response.getContentType()).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
182+
183+
JWKSet jwkSet = JWKSet.parse(response.getContentAsString());
184+
assertThat(jwkSet.getKeys()).isEmpty();
185+
}
186+
}

0 commit comments

Comments
 (0)