Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resource Server - Multi-Tenant Jwt Decoder by Issuer #6817

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* Copyright 2002-2018 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.jwt;

import com.nimbusds.jose.JOSEObject;
import com.nimbusds.jose.util.Base64URL;
import com.nimbusds.jose.util.JSONObjectUtils;
import net.minidev.json.JSONObject;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.Map;

/**
* Delegating JWT decoder that parses JWT and based off {code iss} claim delegates
* further processing to respective underlying decoder.
*
* @author Gladwin Burboz
* @since 5.2
*/
public class MultiTenantDelegatingJwtDecoder implements JwtDecoder {
private static final String DECODING_ERROR_MESSAGE_TEMPLATE =
"An error occurred while attempting to decode the Jwt: %s";

private JwtDecoder decoderDefault;

private Map<String, JwtDecoder> decoderByIssuer;

/**
* Constructs a {@code MultiTenantDelegatingJwtDecoder} using the provided parameters.
*
* @param decoderDefault the default decoder to use for JWT
*/
public MultiTenantDelegatingJwtDecoder(JwtDecoder decoderDefault) {
this(decoderDefault, null);
}

/**
* Constructs a {@code MultiTenantDelegatingJwtDecoder} using the provided parameters.
*
* @param decoderByIssuer the decoder to use for JWT based off issuer as a key
*/
public MultiTenantDelegatingJwtDecoder(
Map<String, JwtDecoder> decoderByIssuer) {
this(null, decoderByIssuer);
}

/**
* Constructs a {@code MultiTenantDelegatingJwtDecoder} using the provided parameters.
*
* @param decoderDefault the default decoder to use for JWT
* @param decoderByIssuer the decoder to use for JWT based off issuer as a key
*/
public MultiTenantDelegatingJwtDecoder(
JwtDecoder decoderDefault,
Map<String, JwtDecoder> decoderByIssuer) {
Assert.isTrue(decoderDefault != null || !CollectionUtils.isEmpty(decoderByIssuer),
"At least one of decoderDefault or decoderByIssuer must be provided");
this.decoderDefault = decoderDefault;
this.decoderByIssuer = decoderByIssuer;
}

@Override
public Jwt decode(String token) throws JwtException {
JwtDecoder jwtDecoder = null;
if (!CollectionUtils.isEmpty(decoderByIssuer)) {
String issuer = parseAndFindIssuer(token);
if (issuer == null && decoderDefault == null) {
throw new JwtException(
"Unable to determine issuer for the token");
} else {
jwtDecoder = decoderByIssuer.get(issuer);
if (jwtDecoder == null && decoderDefault == null) {
throw new JwtException(String.format(
"JwtDecoder has not been configured for issuer %s", issuer));
}
}
}
if (jwtDecoder == null && decoderDefault != null) {
jwtDecoder = decoderDefault;
} else {
throw new JwtException(String.format("Unable to determine JwtDecoder"));
}
return jwtDecoder.decode(token);
}

private String parseAndFindIssuer(String token) {
try {
Base64URL[] parts = JOSEObject.split(token);
JSONObject payload = JSONObjectUtils.parse(parts[1].decodeToString());
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately this parsing is repeated again when NimbusJwtDecoder is invoked. If we limit this delegates to NimbusJwtDecoder and refactor the these two class we may be able to avoid double parsing.

return payload.getAsString("iss");
} catch (ArrayIndexOutOfBoundsException
| NullPointerException
| ParseException ex) {
throw new JwtException(String.format(
DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* 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 sample;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.context.annotation.Configuration;

import java.util.HashSet;
import java.util.Set;

/**
* @author Gladwin Burboz
*/
@Configuration
@ConfigurationProperties("spring.security.oauth2.resourceserver")
public class OAuth2ResourceServerConfig {

@NestedConfigurationProperty
private JwtConfig jwt;

@NestedConfigurationProperty
private Set<JwtConfig> multiTenantJwt = new HashSet<>();

@NestedConfigurationProperty
private OpaqueConfig opaque;

public JwtConfig getJwt() {
return jwt;
}

public void setJwt(JwtConfig jwt) {
this.jwt = jwt;
}

public Set<JwtConfig> getMultiTenantJwt() {
return multiTenantJwt;
}

public OpaqueConfig getOpaque() {
return opaque;
}

public void setOpaque(OpaqueConfig opaque) {
this.opaque = opaque;
}

public static class JwtConfig {
private String issuerUri;
private String jwkSetUri;

public String getIssuerUri() {
return issuerUri;
}

public void setIssuerUri(String issuerUri) {
this.issuerUri = issuerUri;
}

public String getJwkSetUri() {
return jwkSetUri;
}

public void setJwkSetUri(String jwkSetUri) {
this.jwkSetUri = jwkSetUri;
}
}

public static class OpaqueConfig {

private String introspectionUri;

public String getIntrospectionUri() {
return introspectionUri;
}

public void setIntrospectionUri(String introspectionUri) {
this.introspectionUri = introspectionUri;
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,31 +18,31 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationManagerResolver;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.MultiTenantDelegatingJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
import org.springframework.security.oauth2.server.resource.authentication.OAuth2IntrospectionAuthenticationProvider;

/**
* @author Josh Cummings
*/
@Configuration
@EnableWebSecurity
public class OAuth2ResourceServerSecurityConfiguration extends WebSecurityConfigurerAdapter {

@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
String jwkSetUri;

@Value("${spring.security.oauth2.resourceserver.opaque.introspection-uri}")
String introspectionUri;
@Autowired
OAuth2ResourceServerConfig config;

@Override
protected void configure(HttpSecurity http) throws Exception {
Expand Down Expand Up @@ -70,11 +70,22 @@ AuthenticationManagerResolver<HttpServletRequest> multitenantAuthenticationManag
}

AuthenticationManager jwt() {
JwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
JwtDecoder jwtDecoder = null;
if (this.config.getJwt() != null) {
jwtDecoder = NimbusJwtDecoder.withJwkSetUri(this.config.getJwt().getJwkSetUri()).build();
}
if (!this.config.getMultiTenantJwt().isEmpty()) {
Map<String, JwtDecoder> jwtDecoderByIssuer = this.config.getMultiTenantJwt().stream()
.collect(Collectors.toMap(e -> e.getIssuerUri(),
e -> NimbusJwtDecoder.withJwkSetUri(e.getJwkSetUri()).build()));
jwtDecoder = new MultiTenantDelegatingJwtDecoder(jwtDecoder, jwtDecoderByIssuer);
}
return new JwtAuthenticationProvider(jwtDecoder)::authenticate;
}

AuthenticationManager opaque() {
return new OAuth2IntrospectionAuthenticationProvider(this.introspectionUri, "client", "secret")::authenticate;
return new OAuth2IntrospectionAuthenticationProvider(
this.config.getOpaque().getIntrospectionUri(), "client", "secret")::authenticate;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ spring:
oauth2:
resourceserver:
jwt:
issuer-uri: ${mockwebserver.url}
jwk-set-uri: ${mockwebserver.url}/.well-known/jwks.json
multi-tenant-jwt:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not have mock server that supports JWTs with iss claims hence have put these as sample. They need not necessarily support JWT access tokens with iss claim in it. Please suggest how to use mock JWTs here w/ iss claim

-
issuer-uri: "https://accounts.google.com"
jwk-set-uri: "https://www.googleapis.com/oauth2/v3/certs"
-
issuer-uri: "https://contoso.auth0.com/"
jwk-set-uri: "https://contoso.auth0.com/.well-known/jwks.json"
opaque:
introspection-uri: ${mockwebserver.url}/introspect