使い方: マルチテナントを実装する

このガイドでは、マルチテナントホスティング構成でホストごとに複数の発行者をサポートするように Spring Authorization Server をカスタマイズする方法を説明します。このガイドの目的は、Spring Authorization Server のマルチテナント対応コンポーネントを構築するための一般的なパターンを示すことです。このパターンは、ニーズに合わせて他のコンポーネントにも適用できます。

テナント識別子を定義する

OpenID Connect 1.0 プロバイダー構成エンドポイントおよび OAuth2 認証サーバーメタデータエンドポイントでは、発行者識別子の値にパスコンポーネントが許可されるため、ホストごとに複数の発行者を効果的にサポートできます。

例: OpenID プロバイダー構成リクエスト (英語) "http://localhost:9000/issuer1/.well-known/openid-configuration" または認可サーバーのメタデータリクエスト [IETF] (英語) "http://localhost:9000/.well-known/oauth-authorization-server/issuer1" は次の構成メタデータを返します。

{
  "issuer": "http://localhost:9000/issuer1",
  "authorization_endpoint": "http://localhost:9000/issuer1/oauth2/authorize",
  "token_endpoint": "http://localhost:9000/issuer1/oauth2/token",
  "jwks_uri": "http://localhost:9000/issuer1/oauth2/jwks",
  "revocation_endpoint": "http://localhost:9000/issuer1/oauth2/revoke",
  "introspection_endpoint": "http://localhost:9000/issuer1/oauth2/introspect",
  ...
}
プロトコルエンドポイントのベース URL は発行者識別子の値です。

基本的に、パスコンポーネントを持つ発行者識別子は「テナント識別子」を表します。

複数の発行者を有効にする

ホストごとに複数の発行者を使用するサポートは、デフォルトでは無効になっています。有効にするには、次の構成を追加します。

AuthorizationServerSettingsConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;

@Configuration(proxyBeanMethods = false)
public class AuthorizationServerSettingsConfig {

	@Bean
	public AuthorizationServerSettings authorizationServerSettings() {
		return AuthorizationServerSettings.builder()
				.multipleIssuersAllowed(true)	(1)
				.build();
	}

}
1 ホストごとに複数の発行者を使用できるようにするには、true に設定します。

コンポーネントレジストリを作成する

まず、各テナントの具体的なコンポーネントを管理するためのシンプルなレジストリを構築します。レジストリには、発行者識別子の値を使用して特定のクラスの具体的な実装を取得するためのロジックが含まれています。

以下の各委譲実装では、次のクラスを使用します。

TenantPerIssuerComponentRegistry
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContext;
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Component
public class TenantPerIssuerComponentRegistry {
	private final ConcurrentMap<String, Map<Class<?>, Object>> registry = new ConcurrentHashMap<>();

	public <T> void register(String tenantId, Class<T> componentClass, T component) {	(1)
		Assert.hasText(tenantId, "tenantId cannot be empty");
		Assert.notNull(componentClass, "componentClass cannot be null");
		Assert.notNull(component, "component cannot be null");
		Map<Class<?>, Object> components = this.registry.computeIfAbsent(tenantId, (key) -> new ConcurrentHashMap<>());
		components.put(componentClass, component);
	}

	@Nullable
	public <T> T get(Class<T> componentClass) {
		AuthorizationServerContext context = AuthorizationServerContextHolder.getContext();
		if (context == null || context.getIssuer() == null) {
			return null;
		}
		for (Map.Entry<String, Map<Class<?>, Object>> entry : this.registry.entrySet()) {
			if (context.getIssuer().endsWith(entry.getKey())) {
				return componentClass.cast(entry.getValue().get(componentClass));
			}
		}
		return null;
	}
}
1 コンポーネントを登録すると、使用できる承認済み発行者の許可リストが暗黙的に有効になります。
This registry is designed to allow components to be easily registered at startup to support adding tenants statically, but also supports adding tenants dynamically at runtime.

マルチテナントコンポーネントを作成する

マルチテナント機能を必要とするコンポーネントは次のとおりです。

これらのコンポーネントごとに、「リクエストされた」発行者識別子に関連付けられた具体的なコンポーネントに委譲する複合実装を提供できます。

マルチテナント対応コンポーネントごとに 2x テナントをサポートするように Spring Authorization Server をカスタマイズする方法のシナリオを段階的に見ていきましょう。

マルチテナント RegisteredClientRepository

次の例は、2x JdbcRegisteredClientRepository インスタンスで構成される RegisteredClientRepository のサンプル実装を示しています。各インスタンスは発行者識別子にマップされています。

RegisteredClientRepositoryConfig
import java.util.UUID;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.util.Assert;

@Configuration(proxyBeanMethods = false)
public class RegisteredClientRepositoryConfig {

	@Bean
	public RegisteredClientRepository registeredClientRepository(
			@Qualifier("issuer1-data-source") DataSource issuer1DataSource,
			@Qualifier("issuer2-data-source") DataSource issuer2DataSource,
			TenantPerIssuerComponentRegistry componentRegistry) {

		JdbcRegisteredClientRepository issuer1RegisteredClientRepository =
				new JdbcRegisteredClientRepository(new JdbcTemplate(issuer1DataSource));	(1)

		issuer1RegisteredClientRepository.save(
				RegisteredClient.withId(UUID.randomUUID().toString())
						.clientId("client-1")
						.clientSecret("{noop}secret")
						.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
						.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
						.scope("scope-1")
						.build()
		);

		JdbcRegisteredClientRepository issuer2RegisteredClientRepository =
				new JdbcRegisteredClientRepository(new JdbcTemplate(issuer2DataSource));	(2)

		issuer2RegisteredClientRepository.save(
				RegisteredClient.withId(UUID.randomUUID().toString())
						.clientId("client-2")
						.clientSecret("{noop}secret")
						.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
						.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
						.scope("scope-2")
						.build()
		);

		componentRegistry.register("issuer1", RegisteredClientRepository.class, issuer1RegisteredClientRepository);
		componentRegistry.register("issuer2", RegisteredClientRepository.class, issuer2RegisteredClientRepository);

		return new DelegatingRegisteredClientRepository(componentRegistry);
	}

	private static class DelegatingRegisteredClientRepository implements RegisteredClientRepository {	(3)

		private final TenantPerIssuerComponentRegistry componentRegistry;

		private DelegatingRegisteredClientRepository(TenantPerIssuerComponentRegistry componentRegistry) {
			this.componentRegistry = componentRegistry;
		}

		@Override
		public void save(RegisteredClient registeredClient) {
			getRegisteredClientRepository().save(registeredClient);
		}

		@Override
		public RegisteredClient findById(String id) {
			return getRegisteredClientRepository().findById(id);
		}

		@Override
		public RegisteredClient findByClientId(String clientId) {
			return getRegisteredClientRepository().findByClientId(clientId);
		}

		private RegisteredClientRepository getRegisteredClientRepository() {
			RegisteredClientRepository registeredClientRepository =
					this.componentRegistry.get(RegisteredClientRepository.class);	(4)
			Assert.state(registeredClientRepository != null,
					"RegisteredClientRepository not found for \"requested\" issuer identifier.");	(5)
			return registeredClientRepository;
		}

	}

}
完全な例を表示するには、上のコードサンプルの 折りたたまれたテキストを展開する アイコンをクリックします。
1 発行者識別子 issuer1 にマップされ、専用の DataSource を使用する JdbcRegisteredClientRepository インスタンス。
2 発行者識別子 issuer2 にマップされ、専用の DataSource を使用する JdbcRegisteredClientRepository インスタンス。
3「リクエストされた」発行者識別子にマップされた JdbcRegisteredClientRepository に委譲する RegisteredClientRepository の複合実装。
4AuthorizationServerContext.getIssuer() によって示される「リクエストされた」発行者識別子にマップされている JdbcRegisteredClientRepository を取得します。
5JdbcRegisteredClientRepository が見つからない場合は、「リクエストされた」発行者識別子が承認された発行者の許可リストにないため、エラーが発生します。
AuthorizationServerSettings.builder().issuer("http://localhost:9000") を介して発行者識別子を明示的に構成すると、単一テナント構成が強制されます。マルチテナントホスティング構成を使用する場合は、発行者識別子を明示的に構成しないでください。

前の例では、各 JdbcRegisteredClientRepository インスタンスは、JdbcTemplate と関連する DataSource を使用して構成されています。主な要件は各テナントからデータを分離できることであるため、これはマルチテナント構成では重要です。

各コンポーネントインスタンスに専用の DataSource を構成すると、同じデータベースインスタンス内の独自のスキーマにデータを分離したり、別のデータベースインスタンスにデータを完全に分離したりする柔軟性が得られます。

次の例は、マルチテナント対応コンポーネントによって使用される 2x DataSource@Bean (テナントごとに 1 つ) のサンプル構成を示しています。

DataSourceConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;

@Configuration(proxyBeanMethods = false)
public class DataSourceConfig {

	@Bean("issuer1-data-source")
	public EmbeddedDatabase issuer1DataSource() {
		return new EmbeddedDatabaseBuilder()
				.setName("issuer1-db")	(1)
				.setType(EmbeddedDatabaseType.H2)
				.setScriptEncoding("UTF-8")
				.addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql")
				.addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql")
				.addScript("org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql")
				.build();
	}

	@Bean("issuer2-data-source")
	public EmbeddedDatabase issuer2DataSource() {
		return new EmbeddedDatabaseBuilder()
				.setName("issuer2-db")	(2)
				.setType(EmbeddedDatabaseType.H2)
				.setScriptEncoding("UTF-8")
				.addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql")
				.addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql")
				.addScript("org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql")
				.build();
	}

}
1 名前として issuer1-db を使用して、別の H2 データベースインスタンスを使用します。
2 名前として issuer2-db を使用して、別の H2 データベースインスタンスを使用します。

マルチテナント OAuth2AuthorizationService

次の例は、2x JdbcOAuth2AuthorizationService インスタンスで構成される OAuth2AuthorizationService のサンプル実装を示しています。各インスタンスは発行者識別子にマップされています。

OAuth2AuthorizationServiceConfig
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.util.Assert;

@Configuration(proxyBeanMethods = false)
public class OAuth2AuthorizationServiceConfig {

	@Bean
	public OAuth2AuthorizationService authorizationService(
			@Qualifier("issuer1-data-source") DataSource issuer1DataSource,
			@Qualifier("issuer2-data-source") DataSource issuer2DataSource,
			TenantPerIssuerComponentRegistry componentRegistry,
			RegisteredClientRepository registeredClientRepository) {

		componentRegistry.register("issuer1", OAuth2AuthorizationService.class,
				new JdbcOAuth2AuthorizationService(	(1)
						new JdbcTemplate(issuer1DataSource), registeredClientRepository));
		componentRegistry.register("issuer2", OAuth2AuthorizationService.class,
				new JdbcOAuth2AuthorizationService(	(2)
						new JdbcTemplate(issuer2DataSource), registeredClientRepository));

		return new DelegatingOAuth2AuthorizationService(componentRegistry);
	}

	private static class DelegatingOAuth2AuthorizationService implements OAuth2AuthorizationService {	(3)

		private final TenantPerIssuerComponentRegistry componentRegistry;

		private DelegatingOAuth2AuthorizationService(TenantPerIssuerComponentRegistry componentRegistry) {
			this.componentRegistry = componentRegistry;
		}

		@Override
		public void save(OAuth2Authorization authorization) {
			getAuthorizationService().save(authorization);
		}

		@Override
		public void remove(OAuth2Authorization authorization) {
			getAuthorizationService().remove(authorization);
		}

		@Override
		public OAuth2Authorization findById(String id) {
			return getAuthorizationService().findById(id);
		}

		@Override
		public OAuth2Authorization findByToken(String token, OAuth2TokenType tokenType) {
			return getAuthorizationService().findByToken(token, tokenType);
		}

		private OAuth2AuthorizationService getAuthorizationService() {
			OAuth2AuthorizationService authorizationService =
					this.componentRegistry.get(OAuth2AuthorizationService.class);	(4)
			Assert.state(authorizationService != null,
					"OAuth2AuthorizationService not found for \"requested\" issuer identifier.");	(5)
			return authorizationService;
		}

	}

}
1 発行者識別子 issuer1 にマップされ、専用の DataSource を使用する JdbcOAuth2AuthorizationService インスタンス。
2 発行者識別子 issuer2 にマップされ、専用の DataSource を使用する JdbcOAuth2AuthorizationService インスタンス。
3「リクエストされた」発行者識別子にマップされた JdbcOAuth2AuthorizationService に委譲する OAuth2AuthorizationService の複合実装。
4AuthorizationServerContext.getIssuer() によって示される「リクエストされた」発行者識別子にマップされている JdbcOAuth2AuthorizationService を取得します。
5JdbcOAuth2AuthorizationService が見つからない場合は、「リクエストされた」発行者識別子が承認された発行者の許可リストにないため、エラーが発生します。

The following example shows a sample implementation of an OAuth2AuthorizationConsentService that is composed of 2x JdbcOAuth2AuthorizationConsentService instances, where each instance is mapped to an issuer identifier:

OAuth2AuthorizationConsentServiceConfig
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.util.Assert;

@Configuration(proxyBeanMethods = false)
public class OAuth2AuthorizationConsentServiceConfig {

	@Bean
	public OAuth2AuthorizationConsentService authorizationConsentService(
			@Qualifier("issuer1-data-source") DataSource issuer1DataSource,
			@Qualifier("issuer2-data-source") DataSource issuer2DataSource,
			TenantPerIssuerComponentRegistry componentRegistry,
			RegisteredClientRepository registeredClientRepository) {

		componentRegistry.register("issuer1", OAuth2AuthorizationConsentService.class,
				new JdbcOAuth2AuthorizationConsentService(	(1)
						new JdbcTemplate(issuer1DataSource), registeredClientRepository));
		componentRegistry.register("issuer2", OAuth2AuthorizationConsentService.class,
				new JdbcOAuth2AuthorizationConsentService(	(2)
						new JdbcTemplate(issuer2DataSource), registeredClientRepository));

		return new DelegatingOAuth2AuthorizationConsentService(componentRegistry);
	}

	private static class DelegatingOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {	(3)

		private final TenantPerIssuerComponentRegistry componentRegistry;

		private DelegatingOAuth2AuthorizationConsentService(TenantPerIssuerComponentRegistry componentRegistry) {
			this.componentRegistry = componentRegistry;
		}

		@Override
		public void save(OAuth2AuthorizationConsent authorizationConsent) {
			getAuthorizationConsentService().save(authorizationConsent);
		}

		@Override
		public void remove(OAuth2AuthorizationConsent authorizationConsent) {
			getAuthorizationConsentService().remove(authorizationConsent);
		}

		@Override
		public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) {
			return getAuthorizationConsentService().findById(registeredClientId, principalName);
		}

		private OAuth2AuthorizationConsentService getAuthorizationConsentService() {
			OAuth2AuthorizationConsentService authorizationConsentService =
					this.componentRegistry.get(OAuth2AuthorizationConsentService.class);	(4)
			Assert.state(authorizationConsentService != null,
					"OAuth2AuthorizationConsentService not found for \"requested\" issuer identifier.");	(5)
			return authorizationConsentService;
		}

	}

}
1 発行者識別子 issuer1 にマップされ、専用の DataSource を使用する JdbcOAuth2AuthorizationConsentService インスタンス。
2 発行者識別子 issuer2 にマップされ、専用の DataSource を使用する JdbcOAuth2AuthorizationConsentService インスタンス。
3A composite implementation of an OAuth2AuthorizationConsentService that delegates to a JdbcOAuth2AuthorizationConsentService mapped to the "requested" issuer identifier.
4AuthorizationServerContext.getIssuer() によって示される「リクエストされた」発行者識別子にマップされている JdbcOAuth2AuthorizationConsentService を取得します。
5JdbcOAuth2AuthorizationConsentService が見つからない場合は、「リクエストされた」発行者識別子が承認された発行者の許可リストにないため、エラーが発生します。

Multi-tenant JWKSource

And finally, the following example shows a sample implementation of a JWKSource<SecurityContext> that is composed of 2x JWKSet instances, where each instance is mapped to an issuer identifier:

JWKSourceConfig
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.List;
import java.util.UUID;

import com.nimbusds.jose.KeySourceException;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

@Configuration(proxyBeanMethods = false)
public class JWKSourceConfig {

	@Bean
	public JWKSource<SecurityContext> jwkSource(TenantPerIssuerComponentRegistry componentRegistry) {
		componentRegistry.register("issuer1", JWKSet.class, new JWKSet(generateRSAJwk()));	(1)
		componentRegistry.register("issuer2", JWKSet.class, new JWKSet(generateRSAJwk()));	(2)

		return new DelegatingJWKSource(componentRegistry);
	}

	private static RSAKey generateRSAJwk() {
		KeyPair keyPair;
		try {
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
			keyPairGenerator.initialize(2048);
			keyPair = keyPairGenerator.generateKeyPair();
		} catch (Exception ex) {
			throw new IllegalStateException(ex);
		}

		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		return new RSAKey.Builder(publicKey)
				.privateKey(privateKey)
				.keyID(UUID.randomUUID().toString())
				.build();
	}

	private static class DelegatingJWKSource implements JWKSource<SecurityContext> {	(3)

		private final TenantPerIssuerComponentRegistry componentRegistry;

		private DelegatingJWKSource(TenantPerIssuerComponentRegistry componentRegistry) {
			this.componentRegistry = componentRegistry;
		}

		@Override
		public List<JWK> get(JWKSelector jwkSelector, SecurityContext context) throws KeySourceException {
			return jwkSelector.select(getJwkSet());
		}

		private JWKSet getJwkSet() {
			JWKSet jwkSet = this.componentRegistry.get(JWKSet.class);	(4)
			Assert.state(jwkSet != null, "JWKSet not found for \"requested\" issuer identifier.");	(5)
			return jwkSet;
		}

	}

}
1JWKSet instance mapped to issuer identifier issuer1.
2JWKSet instance mapped to issuer identifier issuer2.
3A composite implementation of an JWKSource<SecurityContext> that uses the JWKSet mapped to the "requested" issuer identifier.
4AuthorizationServerContext.getIssuer() によって示される「リクエストされた」発行者識別子にマップされている JWKSet を取得します。
5JWKSet が見つからない場合は、「リクエストされた」発行者識別子が承認された発行者の許可リストにないため、エラーが発生します。

Add Tenants Dynamically

If the number of tenants is dynamic and can change at runtime, defining each DataSource as a @Bean may not be feasible. In this case, the DataSource and corresponding components can be registered through other means at application startup and/or runtime.

The following example shows a Spring @Service capable of adding tenants dynamically:

TenantService
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.UUID;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.stereotype.Service;

@Service
public class TenantService {

	private final TenantPerIssuerComponentRegistry componentRegistry;

	public TenantService(TenantPerIssuerComponentRegistry componentRegistry) {
		this.componentRegistry = componentRegistry;
	}

	public void createTenant(String tenantId) {
		EmbeddedDatabase dataSource = createDataSource(tenantId);
		JdbcTemplate jdbcOperations = new JdbcTemplate(dataSource);

		RegisteredClientRepository registeredClientRepository =
				new JdbcRegisteredClientRepository(jdbcOperations);
		this.componentRegistry.register(tenantId, RegisteredClientRepository.class, registeredClientRepository);

		OAuth2AuthorizationService authorizationService =
				new JdbcOAuth2AuthorizationService(jdbcOperations, registeredClientRepository);
		this.componentRegistry.register(tenantId, OAuth2AuthorizationService.class, authorizationService);

		OAuth2AuthorizationConsentService authorizationConsentService =
				new JdbcOAuth2AuthorizationConsentService(jdbcOperations, registeredClientRepository);
		this.componentRegistry.register(tenantId, OAuth2AuthorizationConsentService.class, authorizationConsentService);

		JWKSet jwkSet = new JWKSet(generateRSAJwk());
		this.componentRegistry.register(tenantId, JWKSet.class, jwkSet);
	}

	private EmbeddedDatabase createDataSource(String tenantId) {
		return new EmbeddedDatabaseBuilder()
				.setName(tenantId)
				.setType(EmbeddedDatabaseType.H2)
				.setScriptEncoding("UTF-8")
				.addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql")
				.addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql")
				.addScript("org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql")
				.build();
	}

	private static RSAKey generateRSAJwk() {
		KeyPair keyPair;
		try {
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
			keyPairGenerator.initialize(2048);
			keyPair = keyPairGenerator.generateKeyPair();
		} catch (Exception ex) {
			throw new IllegalStateException(ex);
		}

		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		return new RSAKey.Builder(publicKey)
				.privateKey(privateKey)
				.keyID(UUID.randomUUID().toString())
				.build();
	}

}