multitenancy.adoc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. = OAuth 2.0 Resource Server Multitenancy
  2. [[oauth2reourceserver-opaqueandjwt]]
  3. == Supporting both JWT and Opaque Token
  4. In some cases, you may have a need to access both kinds of tokens.
  5. For example, you may support more than one tenant where one tenant issues JWTs and the other issues opaque tokens.
  6. If this decision must be made at request-time, then you can use an `AuthenticationManagerResolver` to achieve it, like so:
  7. ====
  8. .Java
  9. [source,java,role="primary"]
  10. ----
  11. @Bean
  12. AuthenticationManagerResolver<HttpServletRequest> tokenAuthenticationManagerResolver
  13. (JwtDecoder jwtDecoder, OpaqueTokenIntrospector opaqueTokenIntrospector) {
  14. AuthenticationManager jwt = new ProviderManager(new JwtAuthenticationProvider(jwtDecoder));
  15. AuthenticationManager opaqueToken = new ProviderManager(
  16. new OpaqueTokenAuthenticationProvider(opaqueTokenIntrospector));
  17. return (request) -> useJwt(request) ? jwt : opaqueToken;
  18. }
  19. ----
  20. .Kotlin
  21. [source,kotlin,role="secondary"]
  22. ----
  23. @Bean
  24. fun tokenAuthenticationManagerResolver
  25. (jwtDecoder: JwtDecoder, opaqueTokenIntrospector: OpaqueTokenIntrospector):
  26. AuthenticationManagerResolver<HttpServletRequest> {
  27. val jwt = ProviderManager(JwtAuthenticationProvider(jwtDecoder))
  28. val opaqueToken = ProviderManager(OpaqueTokenAuthenticationProvider(opaqueTokenIntrospector));
  29. return AuthenticationManagerResolver { request ->
  30. if (useJwt(request)) {
  31. jwt
  32. } else {
  33. opaqueToken
  34. }
  35. }
  36. }
  37. ----
  38. ====
  39. NOTE: The implementation of `useJwt(HttpServletRequest)` will likely depend on custom request material like the path.
  40. And then specify this `AuthenticationManagerResolver` in the DSL:
  41. .Authentication Manager Resolver
  42. ====
  43. .Java
  44. [source,java,role="primary"]
  45. ----
  46. http
  47. .authorizeHttpRequests(authorize -> authorize
  48. .anyRequest().authenticated()
  49. )
  50. .oauth2ResourceServer(oauth2 -> oauth2
  51. .authenticationManagerResolver(this.tokenAuthenticationManagerResolver)
  52. );
  53. ----
  54. .Kotlin
  55. [source,kotlin,role="secondary"]
  56. ----
  57. http {
  58. authorizeRequests {
  59. authorize(anyRequest, authenticated)
  60. }
  61. oauth2ResourceServer {
  62. authenticationManagerResolver = tokenAuthenticationManagerResolver()
  63. }
  64. }
  65. ----
  66. .Xml
  67. [source,xml,role="secondary"]
  68. ----
  69. <http>
  70. <oauth2-resource-server authentication-manager-resolver-ref="tokenAuthenticationManagerResolver"/>
  71. </http>
  72. ----
  73. ====
  74. [[oauth2resourceserver-multitenancy]]
  75. == Multi-tenancy
  76. A resource server is considered multi-tenant when there are multiple strategies for verifying a bearer token, keyed by some tenant identifier.
  77. For example, your resource server may accept bearer tokens from two different authorization servers.
  78. Or, your authorization server may represent a multiplicity of issuers.
  79. In each case, there are two things that need to be done and trade-offs associated with how you choose to do them:
  80. 1. Resolve the tenant
  81. 2. Propagate the tenant
  82. === Resolving the Tenant By Claim
  83. One way to differentiate tenants is by the issuer claim. Since the issuer claim accompanies signed JWTs, this can be done with the `JwtIssuerAuthenticationManagerResolver`, like so:
  84. .Multitenancy Tenant by JWT Claim
  85. ====
  86. .Java
  87. [source,java,role="primary"]
  88. ----
  89. JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver
  90. ("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo");
  91. http
  92. .authorizeHttpRequests(authorize -> authorize
  93. .anyRequest().authenticated()
  94. )
  95. .oauth2ResourceServer(oauth2 -> oauth2
  96. .authenticationManagerResolver(authenticationManagerResolver)
  97. );
  98. ----
  99. .Kotlin
  100. [source,kotlin,role="secondary"]
  101. ----
  102. val customAuthenticationManagerResolver = JwtIssuerAuthenticationManagerResolver
  103. ("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo")
  104. http {
  105. authorizeRequests {
  106. authorize(anyRequest, authenticated)
  107. }
  108. oauth2ResourceServer {
  109. authenticationManagerResolver = customAuthenticationManagerResolver
  110. }
  111. }
  112. ----
  113. .Xml
  114. [source,xml,role="secondary"]
  115. ----
  116. <http>
  117. <oauth2-resource-server authentication-manager-resolver-ref="authenticationManagerResolver"/>
  118. </http>
  119. <bean id="authenticationManagerResolver"
  120. class="org.springframework.security.oauth2.server.resource.authentication.JwtIssuerAuthenticationManagerResolver">
  121. <constructor-arg>
  122. <list>
  123. <value>https://idp.example.org/issuerOne</value>
  124. <value>https://idp.example.org/issuerTwo</value>
  125. </list>
  126. </constructor-arg>
  127. </bean>
  128. ----
  129. ====
  130. This is nice because the issuer endpoints are loaded lazily.
  131. In fact, the corresponding `JwtAuthenticationProvider` is instantiated only when the first request with the corresponding issuer is sent.
  132. This allows for an application startup that is independent from those authorization servers being up and available.
  133. ==== Dynamic Tenants
  134. Of course, you may not want to restart the application each time a new tenant is added.
  135. In this case, you can configure the `JwtIssuerAuthenticationManagerResolver` with a repository of `AuthenticationManager` instances, which you can edit at runtime, like so:
  136. ====
  137. .Java
  138. [source,java,role="primary"]
  139. ----
  140. private void addManager(Map<String, AuthenticationManager> authenticationManagers, String issuer) {
  141. JwtAuthenticationProvider authenticationProvider = new JwtAuthenticationProvider
  142. (JwtDecoders.fromIssuerLocation(issuer));
  143. authenticationManagers.put(issuer, authenticationProvider::authenticate);
  144. }
  145. // ...
  146. JwtIssuerAuthenticationManagerResolver authenticationManagerResolver =
  147. new JwtIssuerAuthenticationManagerResolver(authenticationManagers::get);
  148. http
  149. .authorizeHttpRequests(authorize -> authorize
  150. .anyRequest().authenticated()
  151. )
  152. .oauth2ResourceServer(oauth2 -> oauth2
  153. .authenticationManagerResolver(authenticationManagerResolver)
  154. );
  155. ----
  156. .Kotlin
  157. [source,kotlin,role="secondary"]
  158. ----
  159. private fun addManager(authenticationManagers: MutableMap<String, AuthenticationManager>, issuer: String) {
  160. val authenticationProvider = JwtAuthenticationProvider(JwtDecoders.fromIssuerLocation(issuer))
  161. authenticationManagers[issuer] = AuthenticationManager {
  162. authentication: Authentication? -> authenticationProvider.authenticate(authentication)
  163. }
  164. }
  165. // ...
  166. val customAuthenticationManagerResolver: JwtIssuerAuthenticationManagerResolver =
  167. JwtIssuerAuthenticationManagerResolver(authenticationManagers::get)
  168. http {
  169. authorizeRequests {
  170. authorize(anyRequest, authenticated)
  171. }
  172. oauth2ResourceServer {
  173. authenticationManagerResolver = customAuthenticationManagerResolver
  174. }
  175. }
  176. ----
  177. ====
  178. In this case, you construct `JwtIssuerAuthenticationManagerResolver` with a strategy for obtaining the `AuthenticationManager` given the issuer.
  179. This approach allows us to add and remove elements from the repository (shown as a `Map` in the snippet) at runtime.
  180. NOTE: It would be unsafe to simply take any issuer and construct an `AuthenticationManager` from it.
  181. The issuer should be one that the code can verify from a trusted source like a list of allowed issuers.
  182. ==== Parsing the Claim Only Once
  183. You may have observed that this strategy, while simple, comes with the trade-off that the JWT is parsed once by the `AuthenticationManagerResolver` and then again by the xref:servlet/oauth2/resource-server/jwt.adoc#oauth2resourceserver-jwt-architecture-jwtdecoder[`JwtDecoder`] later on in the request.
  184. This extra parsing can be alleviated by configuring the xref:servlet/oauth2/resource-server/jwt.adoc#oauth2resourceserver-jwt-architecture-jwtdecoder[`JwtDecoder`] directly with a `JWTClaimsSetAwareJWSKeySelector` from Nimbus:
  185. ====
  186. .Java
  187. [source,java,role="primary"]
  188. ----
  189. @Component
  190. public class TenantJWSKeySelector
  191. implements JWTClaimsSetAwareJWSKeySelector<SecurityContext> {
  192. private final TenantRepository tenants; <1>
  193. private final Map<String, JWSKeySelector<SecurityContext>> selectors = new ConcurrentHashMap<>(); <2>
  194. public TenantJWSKeySelector(TenantRepository tenants) {
  195. this.tenants = tenants;
  196. }
  197. @Override
  198. public List<? extends Key> selectKeys(JWSHeader jwsHeader, JWTClaimsSet jwtClaimsSet, SecurityContext securityContext)
  199. throws KeySourceException {
  200. return this.selectors.computeIfAbsent(toTenant(jwtClaimsSet), this::fromTenant)
  201. .selectJWSKeys(jwsHeader, securityContext);
  202. }
  203. private String toTenant(JWTClaimsSet claimSet) {
  204. return (String) claimSet.getClaim("iss");
  205. }
  206. private JWSKeySelector<SecurityContext> fromTenant(String tenant) {
  207. return Optional.ofNullable(this.tenantRepository.findById(tenant)) <3>
  208. .map(t -> t.getAttrbute("jwks_uri"))
  209. .map(this::fromUri)
  210. .orElseThrow(() -> new IllegalArgumentException("unknown tenant"));
  211. }
  212. private JWSKeySelector<SecurityContext> fromUri(String uri) {
  213. try {
  214. return JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(new URL(uri)); <4>
  215. } catch (Exception ex) {
  216. throw new IllegalArgumentException(ex);
  217. }
  218. }
  219. }
  220. ----
  221. .Kotlin
  222. [source,kotlin,role="secondary"]
  223. ----
  224. @Component
  225. class TenantJWSKeySelector(tenants: TenantRepository) : JWTClaimsSetAwareJWSKeySelector<SecurityContext> {
  226. private val tenants: TenantRepository <1>
  227. private val selectors: MutableMap<String, JWSKeySelector<SecurityContext>> = ConcurrentHashMap() <2>
  228. init {
  229. this.tenants = tenants
  230. }
  231. fun selectKeys(jwsHeader: JWSHeader?, jwtClaimsSet: JWTClaimsSet, securityContext: SecurityContext): List<Key?> {
  232. return selectors.computeIfAbsent(toTenant(jwtClaimsSet)) { tenant: String -> fromTenant(tenant) }
  233. .selectJWSKeys(jwsHeader, securityContext)
  234. }
  235. private fun toTenant(claimSet: JWTClaimsSet): String {
  236. return claimSet.getClaim("iss") as String
  237. }
  238. private fun fromTenant(tenant: String): JWSKeySelector<SecurityContext> {
  239. return Optional.ofNullable(this.tenants.findById(tenant)) <3>
  240. .map { t -> t.getAttrbute("jwks_uri") }
  241. .map { uri: String -> fromUri(uri) }
  242. .orElseThrow { IllegalArgumentException("unknown tenant") }
  243. }
  244. private fun fromUri(uri: String): JWSKeySelector<SecurityContext?> {
  245. return try {
  246. JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(URL(uri)) <4>
  247. } catch (ex: Exception) {
  248. throw IllegalArgumentException(ex)
  249. }
  250. }
  251. }
  252. ----
  253. ====
  254. <1> A hypothetical source for tenant information
  255. <2> A cache for `JWKKeySelector`s, keyed by tenant identifier
  256. <3> Looking up the tenant is more secure than simply calculating the JWK Set endpoint on the fly - the lookup acts as a list of allowed tenants
  257. <4> Create a `JWSKeySelector` via the types of keys that come back from the JWK Set endpoint - the lazy lookup here means that you don't need to configure all tenants at startup
  258. The above key selector is a composition of many key selectors.
  259. It chooses which key selector to use based on the `iss` claim in the JWT.
  260. NOTE: To use this approach, make sure that the authorization server is configured to include the claim set as part of the token's signature.
  261. Without this, you have no guarantee that the issuer hasn't been altered by a bad actor.
  262. Next, we can construct a `JWTProcessor`:
  263. ====
  264. .Java
  265. [source,java,role="primary"]
  266. ----
  267. @Bean
  268. JWTProcessor jwtProcessor(JWTClaimSetJWSKeySelector keySelector) {
  269. ConfigurableJWTProcessor<SecurityContext> jwtProcessor =
  270. new DefaultJWTProcessor();
  271. jwtProcessor.setJWTClaimSetJWSKeySelector(keySelector);
  272. return jwtProcessor;
  273. }
  274. ----
  275. .Kotlin
  276. [source,kotlin,role="secondary"]
  277. ----
  278. @Bean
  279. fun jwtProcessor(keySelector: JWTClaimsSetAwareJWSKeySelector<SecurityContext>): JWTProcessor<SecurityContext> {
  280. val jwtProcessor = DefaultJWTProcessor<SecurityContext>()
  281. jwtProcessor.jwtClaimsSetAwareJWSKeySelector = keySelector
  282. return jwtProcessor
  283. }
  284. ----
  285. ====
  286. As you are already seeing, the trade-off for moving tenant-awareness down to this level is more configuration.
  287. We have just a bit more.
  288. Next, we still want to make sure you are validating the issuer.
  289. But, since the issuer may be different per JWT, then you'll need a tenant-aware validator, too:
  290. ====
  291. .Java
  292. [source,java,role="primary"]
  293. ----
  294. @Component
  295. public class TenantJwtIssuerValidator implements OAuth2TokenValidator<Jwt> {
  296. private final TenantRepository tenants;
  297. private final Map<String, JwtIssuerValidator> validators = new ConcurrentHashMap<>();
  298. public TenantJwtIssuerValidator(TenantRepository tenants) {
  299. this.tenants = tenants;
  300. }
  301. @Override
  302. public OAuth2TokenValidatorResult validate(Jwt token) {
  303. return this.validators.computeIfAbsent(toTenant(token), this::fromTenant)
  304. .validate(token);
  305. }
  306. private String toTenant(Jwt jwt) {
  307. return jwt.getIssuer();
  308. }
  309. private JwtIssuerValidator fromTenant(String tenant) {
  310. return Optional.ofNullable(this.tenants.findById(tenant))
  311. .map(t -> t.getAttribute("issuer"))
  312. .map(JwtIssuerValidator::new)
  313. .orElseThrow(() -> new IllegalArgumentException("unknown tenant"));
  314. }
  315. }
  316. ----
  317. .Kotlin
  318. [source,kotlin,role="secondary"]
  319. ----
  320. @Component
  321. class TenantJwtIssuerValidator(tenants: TenantRepository) : OAuth2TokenValidator<Jwt> {
  322. private val tenants: TenantRepository
  323. private val validators: MutableMap<String, JwtIssuerValidator> = ConcurrentHashMap()
  324. override fun validate(token: Jwt): OAuth2TokenValidatorResult {
  325. return validators.computeIfAbsent(toTenant(token)) { tenant: String -> fromTenant(tenant) }
  326. .validate(token)
  327. }
  328. private fun toTenant(jwt: Jwt): String {
  329. return jwt.issuer.toString()
  330. }
  331. private fun fromTenant(tenant: String): JwtIssuerValidator {
  332. return Optional.ofNullable(tenants.findById(tenant))
  333. .map({ t -> t.getAttribute("issuer") })
  334. .map({ JwtIssuerValidator() })
  335. .orElseThrow({ IllegalArgumentException("unknown tenant") })
  336. }
  337. init {
  338. this.tenants = tenants
  339. }
  340. }
  341. ----
  342. ====
  343. Now that we have a tenant-aware processor and a tenant-aware validator, we can proceed with creating our xref:servlet/oauth2/resource-server/jwt.adoc#oauth2resourceserver-jwt-architecture-jwtdecoder[`JwtDecoder`]:
  344. ====
  345. .Java
  346. [source,java,role="primary"]
  347. ----
  348. @Bean
  349. JwtDecoder jwtDecoder(JWTProcessor jwtProcessor, OAuth2TokenValidator<Jwt> jwtValidator) {
  350. NimbusJwtDecoder decoder = new NimbusJwtDecoder(processor);
  351. OAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<>
  352. (JwtValidators.createDefault(), this.jwtValidator);
  353. decoder.setJwtValidator(validator);
  354. return decoder;
  355. }
  356. ----
  357. .Kotlin
  358. [source,kotlin,role="secondary"]
  359. ----
  360. @Bean
  361. fun jwtDecoder(jwtProcessor: JWTProcessor<SecurityContext>?, jwtValidator: OAuth2TokenValidator<Jwt>?): JwtDecoder {
  362. val decoder = NimbusJwtDecoder(jwtProcessor)
  363. val validator: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(JwtValidators.createDefault(), jwtValidator)
  364. decoder.setJwtValidator(validator)
  365. return decoder
  366. }
  367. ----
  368. ====
  369. We've finished talking about resolving the tenant.
  370. If you've chosen to resolve the tenant by something other than a JWT claim, then you'll need to make sure you address your downstream resource servers in the same way.
  371. For example, if you are resolving it by subdomain, you may need to address the downstream resource server using the same subdomain.
  372. However, if you resolve it by a claim in the bearer token, read on to learn about xref:servlet/oauth2/resource-server/bearer-tokens.adoc#oauth2resourceserver-bearertoken-resolver[Spring Security's support for bearer token propagation].