操作指南:實現多租戶

本指南展示瞭如何定製 Spring Authorization Server,以在多租戶託管配置中支援每個主機多個頒發者。本指南的目的是演示為 Spring Authorization Server 構建多租戶元件的通用模式,該模式也可應用於其他元件以滿足您的需求。

定義租戶識別符號

OpenID Connect 1.0 Provider Configuration EndpointOAuth2 Authorization Server Metadata Endpoint 允許在頒發者識別符號值中使用路徑元件,這有效地實現了每個主機支援多個頒發者。

例如,一個 OpenID Provider Configuration Request "https://:9000/issuer1/.well-known/openid-configuration" 或一個 Authorization Server Metadata Request "https://:9000/.well-known/oauth-authorization-server/issuer1" 將返回以下配置元資料:

{
  "issuer": "https://:9000/issuer1",
  "authorization_endpoint": "https://:9000/issuer1/oauth2/authorize",
  "token_endpoint": "https://:9000/issuer1/oauth2/token",
  "jwks_uri": "https://:9000/issuer1/oauth2/jwks",
  "revocation_endpoint": "https://:9000/issuer1/oauth2/revoke",
  "introspection_endpoint": "https://: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 元件註冊隱式啟用了一個可使用的批准頒發者白名單。
此登錄檔旨在允許在啟動時輕鬆註冊元件以支援靜態新增租戶,同時也支援在執行時 動態新增租戶

建立多租戶元件

需要多租戶能力的元件有:

對於這些元件中的每一個,都可以提供一個組合實現,該實現將委託給與 *"請求的"* 頒發者識別符號關聯的具體元件。

讓我們一步一步地瞭解一個場景,演示如何定製 Spring Authorization Server 以支援每個多租戶元件的 2 個租戶。

多租戶 RegisteredClientRepository

以下示例展示了一個 RegisteredClientRepository 的示例實現,它由 2 個 JdbcRegisteredClientRepository 例項組成,其中每個例項都對映到一個頒發者識別符號:

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 一個 JdbcRegisteredClientRepository 例項,對映到頒發者識別符號 issuer1 並使用專用的 DataSource
2 一個 JdbcRegisteredClientRepository 例項,對映到頒發者識別符號 issuer2 並使用專用的 DataSource
3 一個 RegisteredClientRepository 的組合實現,它委託給對映到 *"請求的"* 頒發者識別符號的 JdbcRegisteredClientRepository
4 獲取對映到由 AuthorizationServerContext.getIssuer() 指示的 *"請求的"* 頒發者識別符號的 JdbcRegisteredClientRepository
5 如果找不到 JdbcRegisteredClientRepository,則報錯,因為 *"請求的"* 頒發者識別符號不在批准頒發者的白名單中。
透過 AuthorizationServerSettings.builder().issuer("https://:9000") 顯式配置頒發者識別符號會強制使用單租戶配置。在使用多租戶託管配置時,避免顯式配置頒發者識別符號。

在前面的示例中,每個 JdbcRegisteredClientRepository 例項都配置了 JdbcTemplate 和關聯的 DataSource。這在多租戶配置中很重要,因為一個主要要求是能夠隔離每個租戶的資料。

為每個元件例項配置專用的 DataSource 提供了靈活性,可以將資料隔離在同一資料庫例項內的獨立模式中,或者完全隔離到獨立的資料庫例項中。

以下示例展示了 2 個 DataSource @Bean(每個租戶一個)的示例配置,這些 DataSource 由多租戶元件使用:

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 使用獨立的 H2 資料庫例項,名稱為 issuer1-db
2 使用獨立的 H2 資料庫例項,名稱為 issuer2-db

多租戶 OAuth2AuthorizationService

以下示例展示了一個 OAuth2AuthorizationService 的示例實現,它由 2 個 JdbcOAuth2AuthorizationService 例項組成,其中每個例項都對映到一個頒發者識別符號:

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 一個 JdbcOAuth2AuthorizationService 例項,對映到頒發者識別符號 issuer1 並使用專用的 DataSource
2 一個 JdbcOAuth2AuthorizationService 例項,對映到頒發者識別符號 issuer2 並使用專用的 DataSource
3 一個 OAuth2AuthorizationService 的組合實現,它委託給對映到 *"請求的"* 頒發者識別符號的 JdbcOAuth2AuthorizationService
4 獲取對映到由 AuthorizationServerContext.getIssuer() 指示的 *"請求的"* 頒發者識別符號的 JdbcOAuth2AuthorizationService
5 如果找不到 JdbcOAuth2AuthorizationService,則報錯,因為 *"請求的"* 頒發者識別符號不在批准頒發者的白名單中。

以下示例展示了一個 OAuth2AuthorizationConsentService 的示例實現,它由 2 個 JdbcOAuth2AuthorizationConsentService 例項組成,其中每個例項都對映到一個頒發者識別符號:

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 一個 JdbcOAuth2AuthorizationConsentService 例項,對映到頒發者識別符號 issuer1 並使用專用的 DataSource
2 一個 JdbcOAuth2AuthorizationConsentService 例項,對映到頒發者識別符號 issuer2 並使用專用的 DataSource
3 一個 OAuth2AuthorizationConsentService 的組合實現,它委託給對映到 *"請求的"* 頒發者識別符號的 JdbcOAuth2AuthorizationConsentService
4 獲取對映到由 AuthorizationServerContext.getIssuer() 指示的 *"請求的"* 頒發者識別符號的 JdbcOAuth2AuthorizationConsentService
5 如果找不到 JdbcOAuth2AuthorizationConsentService,則報錯,因為 *"請求的"* 頒發者識別符號不在批准頒發者的白名單中。

多租戶 JWKSource

最後,以下示例展示了一個 JWKSource<SecurityContext> 的示例實現,它由 2 個 JWKSet 例項組成,其中每個例項都對映到一個頒發者識別符號:

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;
		}

	}

}
1 一個 JWKSet 例項,對映到頒發者識別符號 issuer1
2 一個 JWKSet 例項,對映到頒發者識別符號 issuer2
3 一個 JWKSource<SecurityContext> 的組合實現,它使用對映到 *"請求的"* 頒發者識別符號的 JWKSet
4 獲取對映到由 AuthorizationServerContext.getIssuer() 指示的 *"請求的"* 頒發者識別符號的 JWKSet
5 如果找不到 JWKSet,則報錯,因為 *"請求的"* 頒發者識別符號不在批准頒發者的白名單中。

動態新增租戶

如果租戶數量是動態的並在執行時可能發生變化,將每個 DataSource 定義為 @Bean 可能不可行。在這種情況下,可以在應用程式啟動和/或執行時透過其他方式註冊 DataSource 和相應的元件。

以下示例展示了一個能夠動態新增租戶的 Spring @Service

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();
	}

}