4 changed files with 492 additions and 88 deletions
@ -0,0 +1,180 @@
@@ -0,0 +1,180 @@
|
||||
/* |
||||
* Copyright 2002-2019 the original author or authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
*/ |
||||
|
||||
package org.springframework.security.oauth2.server.resource.authentication; |
||||
|
||||
import java.util.Arrays; |
||||
import java.util.Collection; |
||||
import java.util.Collections; |
||||
import java.util.Map; |
||||
import java.util.concurrent.ConcurrentHashMap; |
||||
import java.util.function.Predicate; |
||||
import javax.servlet.http.HttpServletRequest; |
||||
|
||||
import com.nimbusds.jwt.JWTParser; |
||||
|
||||
import org.springframework.core.convert.converter.Converter; |
||||
import org.springframework.http.HttpStatus; |
||||
import org.springframework.lang.NonNull; |
||||
import org.springframework.security.authentication.AuthenticationManager; |
||||
import org.springframework.security.authentication.AuthenticationManagerResolver; |
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException; |
||||
import org.springframework.security.oauth2.core.OAuth2Error; |
||||
import org.springframework.security.oauth2.jwt.JwtDecoder; |
||||
import org.springframework.security.oauth2.jwt.JwtDecoders; |
||||
import org.springframework.security.oauth2.server.resource.BearerTokenError; |
||||
import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes; |
||||
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver; |
||||
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver; |
||||
import org.springframework.util.Assert; |
||||
|
||||
/** |
||||
* An implementation of {@link AuthenticationManagerResolver} that resolves a JWT-based {@link AuthenticationManager} |
||||
* based on the <a href="https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a> in a |
||||
* signed JWT (JWS). |
||||
* |
||||
* To use, this class must be able to determine whether or not the `iss` claim is trusted. Recall that |
||||
* anyone can stand up an authorization server and issue valid tokens to a resource server. The simplest way |
||||
* to achieve this is to supply a whitelist of trusted issuers in the constructor. |
||||
* |
||||
* This class derives the Issuer from the `iss` claim found in the {@link HttpServletRequest}'s |
||||
* <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer Token</a>. |
||||
* |
||||
* @author Josh Cummings |
||||
* @since 5.3 |
||||
*/ |
||||
public final class JwtIssuerAuthenticationManagerResolver implements AuthenticationManagerResolver<HttpServletRequest> { |
||||
private static final OAuth2Error DEFAULT_INVALID_TOKEN = invalidToken("Invalid token"); |
||||
|
||||
private final AuthenticationManagerResolver<String> issuerAuthenticationManagerResolver; |
||||
private final Converter<HttpServletRequest, String> issuerConverter = new JwtClaimIssuerConverter(); |
||||
|
||||
/** |
||||
* Construct a {@link JwtIssuerAuthenticationManagerResolver} using the provided parameters |
||||
* |
||||
* @param trustedIssuers a whitelist of trusted issuers |
||||
*/ |
||||
public JwtIssuerAuthenticationManagerResolver(String... trustedIssuers) { |
||||
this(Arrays.asList(trustedIssuers)); |
||||
} |
||||
|
||||
/** |
||||
* Construct a {@link JwtIssuerAuthenticationManagerResolver} using the provided parameters |
||||
* |
||||
* @param trustedIssuers a whitelist of trusted issuers |
||||
*/ |
||||
public JwtIssuerAuthenticationManagerResolver(Collection<String> trustedIssuers) { |
||||
Assert.notEmpty(trustedIssuers, "trustedIssuers cannot be empty"); |
||||
this.issuerAuthenticationManagerResolver = |
||||
new TrustedIssuerJwtAuthenticationManagerResolver |
||||
(Collections.unmodifiableCollection(trustedIssuers)::contains); |
||||
} |
||||
|
||||
/** |
||||
* Construct a {@link JwtIssuerAuthenticationManagerResolver} using the provided parameters |
||||
* |
||||
* Note that the {@link AuthenticationManagerResolver} provided in this constructor will need to |
||||
* verify that the issuer is trusted. This should be done via a whitelist. |
||||
* |
||||
* One way to achieve this is with a {@link Map} where the keys are the known issuers: |
||||
* <pre> |
||||
* Map<String, AuthenticationManager> authenticationManagers = new HashMap<>(); |
||||
* authenticationManagers.put("https://issuerOne.example.org", managerOne); |
||||
* authenticationManagers.put("https://issuerTwo.example.org", managerTwo); |
||||
* JwtAuthenticationManagerResolver resolver = new JwtAuthenticationManagerResolver |
||||
* (authenticationManagers::get); |
||||
* </pre> |
||||
* |
||||
* The keys in the {@link Map} are the whitelist. |
||||
* |
||||
* @param issuerAuthenticationManagerResolver a strategy for resolving the {@link AuthenticationManager} by the issuer |
||||
*/ |
||||
public JwtIssuerAuthenticationManagerResolver(AuthenticationManagerResolver<String> issuerAuthenticationManagerResolver) { |
||||
Assert.notNull(issuerAuthenticationManagerResolver, "issuerAuthenticationManagerResolver cannot be null"); |
||||
this.issuerAuthenticationManagerResolver = issuerAuthenticationManagerResolver; |
||||
} |
||||
|
||||
/** |
||||
* Return an {@link AuthenticationManager} based off of the `iss` claim found in the request's bearer token |
||||
* |
||||
* @throws OAuth2AuthenticationException if the bearer token is malformed or an {@link AuthenticationManager} |
||||
* can't be derived from the issuer |
||||
*/ |
||||
@Override |
||||
public AuthenticationManager resolve(HttpServletRequest request) { |
||||
String issuer = this.issuerConverter.convert(request); |
||||
AuthenticationManager authenticationManager = this.issuerAuthenticationManagerResolver.resolve(issuer); |
||||
if (authenticationManager == null) { |
||||
throw new OAuth2AuthenticationException(invalidToken("Invalid issuer " + issuer)); |
||||
} |
||||
return authenticationManager; |
||||
} |
||||
|
||||
private static class JwtClaimIssuerConverter |
||||
implements Converter<HttpServletRequest, String> { |
||||
|
||||
private final BearerTokenResolver resolver = new DefaultBearerTokenResolver(); |
||||
|
||||
@Override |
||||
public String convert(@NonNull HttpServletRequest request) { |
||||
String token = this.resolver.resolve(request); |
||||
try { |
||||
String issuer = JWTParser.parse(token).getJWTClaimsSet().getIssuer(); |
||||
if (issuer != null) { |
||||
return issuer; |
||||
} |
||||
} catch (Exception e) { |
||||
throw new OAuth2AuthenticationException(invalidToken(e.getMessage())); |
||||
} |
||||
throw new OAuth2AuthenticationException(invalidToken("Missing issuer")); |
||||
} |
||||
} |
||||
|
||||
private static class TrustedIssuerJwtAuthenticationManagerResolver |
||||
implements AuthenticationManagerResolver<String> { |
||||
|
||||
private final Map<String, AuthenticationManager> authenticationManagers = new ConcurrentHashMap<>(); |
||||
private final Predicate<String> trustedIssuer; |
||||
|
||||
TrustedIssuerJwtAuthenticationManagerResolver(Predicate<String> trustedIssuer) { |
||||
this.trustedIssuer = trustedIssuer; |
||||
} |
||||
|
||||
@Override |
||||
public AuthenticationManager resolve(String issuer) { |
||||
if (this.trustedIssuer.test(issuer)) { |
||||
return this.authenticationManagers.computeIfAbsent(issuer, k -> { |
||||
JwtDecoder jwtDecoder = JwtDecoders.fromIssuerLocation(issuer); |
||||
return new JwtAuthenticationProvider(jwtDecoder)::authenticate; |
||||
}); |
||||
} |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
private static OAuth2Error invalidToken(String message) { |
||||
try { |
||||
return new BearerTokenError( |
||||
BearerTokenErrorCodes.INVALID_TOKEN, |
||||
HttpStatus.UNAUTHORIZED, |
||||
message, |
||||
"https://tools.ietf.org/html/rfc6750#section-3.1"); |
||||
} catch (IllegalArgumentException malformed) { |
||||
// some third-party library error messages are not suitable for RFC 6750's error message charset
|
||||
return DEFAULT_INVALID_TOKEN; |
||||
} |
||||
} |
||||
} |
||||
@ -0,0 +1,186 @@
@@ -0,0 +1,186 @@
|
||||
/* |
||||
* Copyright 2002-2019 the original author or authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
*/ |
||||
|
||||
package org.springframework.security.oauth2.server.resource.authentication; |
||||
|
||||
import java.util.Collection; |
||||
import java.util.Collections; |
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
import com.nimbusds.jose.JWSAlgorithm; |
||||
import com.nimbusds.jose.JWSHeader; |
||||
import com.nimbusds.jose.JWSObject; |
||||
import com.nimbusds.jose.Payload; |
||||
import com.nimbusds.jose.crypto.RSASSASigner; |
||||
import com.nimbusds.jwt.JWTClaimsSet; |
||||
import com.nimbusds.jwt.PlainJWT; |
||||
import net.minidev.json.JSONObject; |
||||
import okhttp3.mockwebserver.MockResponse; |
||||
import okhttp3.mockwebserver.MockWebServer; |
||||
import org.junit.Test; |
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest; |
||||
import org.springframework.security.authentication.AuthenticationManager; |
||||
import org.springframework.security.authentication.AuthenticationManagerResolver; |
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException; |
||||
import org.springframework.security.oauth2.jose.TestKeys; |
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat; |
||||
import static org.assertj.core.api.Assertions.assertThatCode; |
||||
import static org.mockito.Mockito.mock; |
||||
import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS; |
||||
|
||||
/** |
||||
* Tests for {@link JwtIssuerAuthenticationManagerResolver} |
||||
*/ |
||||
public class JwtIssuerAuthenticationManagerResolverTests { |
||||
private static final String DEFAULT_RESPONSE_TEMPLATE = "{\n" |
||||
+ " \"issuer\": \"%s\", \n" |
||||
+ " \"jwks_uri\": \"%s/.well-known/jwks.json\" \n" |
||||
+ "}"; |
||||
|
||||
private String jwt = jwt("iss", "trusted"); |
||||
private String evil = jwt("iss", "\""); |
||||
private String noIssuer = jwt("sub", "sub"); |
||||
|
||||
@Test |
||||
public void resolveWhenUsingTrustedIssuerThenReturnsAuthenticationManager() throws Exception { |
||||
try (MockWebServer server = new MockWebServer()) { |
||||
server.start(); |
||||
String issuer = server.url("").toString(); |
||||
server.enqueue(new MockResponse() |
||||
.setResponseCode(200) |
||||
.setHeader("Content-Type", "application/json") |
||||
.setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); |
||||
JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), |
||||
new Payload(new JSONObject(Collections.singletonMap(ISS, issuer)))); |
||||
jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); |
||||
|
||||
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = |
||||
new JwtIssuerAuthenticationManagerResolver(issuer); |
||||
MockHttpServletRequest request = new MockHttpServletRequest(); |
||||
request.addHeader("Authorization", "Bearer " + jws.serialize()); |
||||
|
||||
AuthenticationManager authenticationManager = |
||||
authenticationManagerResolver.resolve(request); |
||||
assertThat(authenticationManager).isNotNull(); |
||||
|
||||
AuthenticationManager cachedAuthenticationManager = |
||||
authenticationManagerResolver.resolve(request); |
||||
assertThat(authenticationManager).isSameAs(cachedAuthenticationManager); |
||||
} |
||||
} |
||||
|
||||
@Test |
||||
public void resolveWhenUsingUntrustedIssuerThenException() { |
||||
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = |
||||
new JwtIssuerAuthenticationManagerResolver("other", "issuers"); |
||||
MockHttpServletRequest request = new MockHttpServletRequest(); |
||||
request.addHeader("Authorization", "Bearer " + this.jwt); |
||||
|
||||
assertThatCode(() -> authenticationManagerResolver.resolve(request)) |
||||
.isInstanceOf(OAuth2AuthenticationException.class) |
||||
.hasMessageContaining("Invalid issuer"); |
||||
} |
||||
|
||||
@Test |
||||
public void resolveWhenUsingCustomIssuerAuthenticationManagerResolverThenUses() { |
||||
AuthenticationManager authenticationManager = mock(AuthenticationManager.class); |
||||
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = |
||||
new JwtIssuerAuthenticationManagerResolver(issuer -> authenticationManager); |
||||
MockHttpServletRequest request = new MockHttpServletRequest(); |
||||
request.addHeader("Authorization", "Bearer " + this.jwt); |
||||
|
||||
assertThat(authenticationManagerResolver.resolve(request)) |
||||
.isSameAs(authenticationManager); |
||||
} |
||||
|
||||
@Test |
||||
public void resolveWhenUsingExternalSourceThenRespondsToChanges() { |
||||
MockHttpServletRequest request = new MockHttpServletRequest(); |
||||
request.addHeader("Authorization", "Bearer " + this.jwt); |
||||
|
||||
Map<String, AuthenticationManager> authenticationManagers = new HashMap<>(); |
||||
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = |
||||
new JwtIssuerAuthenticationManagerResolver(authenticationManagers::get); |
||||
assertThatCode(() -> authenticationManagerResolver.resolve(request)) |
||||
.isInstanceOf(OAuth2AuthenticationException.class) |
||||
.hasMessageContaining("Invalid issuer"); |
||||
|
||||
AuthenticationManager authenticationManager = mock(AuthenticationManager.class); |
||||
authenticationManagers.put("trusted", authenticationManager); |
||||
assertThat(authenticationManagerResolver.resolve(request)) |
||||
.isSameAs(authenticationManager); |
||||
|
||||
authenticationManagers.clear(); |
||||
assertThatCode(() -> authenticationManagerResolver.resolve(request)) |
||||
.isInstanceOf(OAuth2AuthenticationException.class) |
||||
.hasMessageContaining("Invalid issuer"); |
||||
} |
||||
|
||||
@Test |
||||
public void resolveWhenBearerTokenMalformedThenException() { |
||||
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = |
||||
new JwtIssuerAuthenticationManagerResolver("trusted"); |
||||
MockHttpServletRequest request = new MockHttpServletRequest(); |
||||
request.addHeader("Authorization", "Bearer jwt"); |
||||
assertThatCode(() -> authenticationManagerResolver.resolve(request)) |
||||
.isInstanceOf(OAuth2AuthenticationException.class) |
||||
.hasMessageNotContaining("Invalid issuer"); |
||||
} |
||||
|
||||
@Test |
||||
public void resolveWhenBearerTokenNoIssuerThenException() { |
||||
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = |
||||
new JwtIssuerAuthenticationManagerResolver("trusted"); |
||||
MockHttpServletRequest request = new MockHttpServletRequest(); |
||||
request.addHeader("Authorization", "Bearer " + this.noIssuer); |
||||
assertThatCode(() -> authenticationManagerResolver.resolve(request)) |
||||
.isInstanceOf(OAuth2AuthenticationException.class) |
||||
.hasMessageContaining("Missing issuer"); |
||||
} |
||||
|
||||
@Test |
||||
public void resolveWhenBearerTokenEvilThenGenericException() { |
||||
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = |
||||
new JwtIssuerAuthenticationManagerResolver("trusted"); |
||||
MockHttpServletRequest request = new MockHttpServletRequest(); |
||||
request.addHeader("Authorization", "Bearer " + this.evil); |
||||
assertThatCode(() -> authenticationManagerResolver.resolve(request)) |
||||
.isInstanceOf(OAuth2AuthenticationException.class) |
||||
.hasMessage("Invalid token"); |
||||
} |
||||
|
||||
@Test |
||||
public void constructorWhenNullOrEmptyIssuersThenException() { |
||||
assertThatCode(() -> new JwtIssuerAuthenticationManagerResolver((Collection) null)) |
||||
.isInstanceOf(IllegalArgumentException.class); |
||||
assertThatCode(() -> new JwtIssuerAuthenticationManagerResolver(Collections.emptyList())) |
||||
.isInstanceOf(IllegalArgumentException.class); |
||||
} |
||||
|
||||
@Test |
||||
public void constructorWhenNullAuthenticationManagerResolverThenException() { |
||||
assertThatCode(() -> new JwtIssuerAuthenticationManagerResolver((AuthenticationManagerResolver) null)) |
||||
.isInstanceOf(IllegalArgumentException.class); |
||||
} |
||||
|
||||
private String jwt(String claim, String value) { |
||||
PlainJWT jwt = new PlainJWT(new JWTClaimsSet.Builder().claim(claim, value).build()); |
||||
return jwt.serialize(); |
||||
} |
||||
} |
||||
Loading…
Reference in new issue