multitenancy.adoc 15 KB

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