opaque-token.adoc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. = OAuth 2.0 Resource Server Opaque Token
  2. [[webflux-oauth2resourceserver-opaque-minimaldependencies]]
  3. == Minimal Dependencies for Introspection
  4. As described in xref:servlet/oauth2/resource-server/jwt.adoc#oauth2resourceserver-jwt-minimaldependencies[Minimal Dependencies for JWT] most of Resource Server support is collected in `spring-security-oauth2-resource-server`.
  5. However unless a custom <<webflux-oauth2resourceserver-opaque-introspector-bean,`ReactiveOpaqueTokenIntrospector`>> is provided, the Resource Server will fallback to ReactiveOpaqueTokenIntrospector.
  6. Meaning that both `spring-security-oauth2-resource-server` and `oauth2-oidc-sdk` are necessary in order to have a working minimal Resource Server that supports opaque Bearer Tokens.
  7. Please refer to `spring-security-oauth2-resource-server` in order to determin the correct version for `oauth2-oidc-sdk`.
  8. [[webflux-oauth2resourceserver-opaque-minimalconfiguration]]
  9. == Minimal Configuration for Introspection
  10. Typically, an opaque token can be verified via an https://tools.ietf.org/html/rfc7662[OAuth 2.0 Introspection Endpoint], hosted by the authorization server.
  11. This can be handy when revocation is a requirement.
  12. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server that uses introspection consists of two basic steps.
  13. First, include the needed dependencies and second, indicate the introspection endpoint details.
  14. [[webflux-oauth2resourceserver-opaque-introspectionuri]]
  15. === Specifying the Authorization Server
  16. To specify where the introspection endpoint is, simply do:
  17. [source,yaml]
  18. ----
  19. spring:
  20. security:
  21. oauth2:
  22. resourceserver:
  23. opaque-token:
  24. introspection-uri: https://idp.example.com/introspect
  25. client-id: client
  26. client-secret: secret
  27. ----
  28. Where `https://idp.example.com/introspect` is the introspection endpoint hosted by your authorization server and `client-id` and `client-secret` are the credentials needed to hit that endpoint.
  29. Resource Server will use these properties to further self-configure and subsequently validate incoming JWTs.
  30. [NOTE]
  31. When using introspection, the authorization server's word is the law.
  32. If the authorization server responses that the token is valid, then it is.
  33. And that's it!
  34. === Startup Expectations
  35. When this property and these dependencies are used, Resource Server will automatically configure itself to validate Opaque Bearer Tokens.
  36. This startup process is quite a bit simpler than for JWTs since no endpoints need to be discovered and no additional validation rules get added.
  37. === Runtime Expectations
  38. Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header:
  39. [source,http]
  40. ----
  41. GET / HTTP/1.1
  42. Authorization: Bearer some-token-value # Resource Server will process this
  43. ----
  44. So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification.
  45. Given an Opaque Token, Resource Server will
  46. 1. Query the provided introspection endpoint using the provided credentials and the token
  47. 2. Inspect the response for an `{ 'active' : true }` attribute
  48. 3. Map each scope to an authority with the prefix `SCOPE_`
  49. The resulting `Authentication#getPrincipal`, by default, is a Spring Security `{security-api-url}org/springframework/security/oauth2/core/OAuth2AuthenticatedPrincipal.html[OAuth2AuthenticatedPrincipal]` object, and `Authentication#getName` maps to the token's `sub` property, if one is present.
  50. From here, you may want to jump to:
  51. * <<webflux-oauth2resourceserver-opaque-attributes,Looking Up Attributes Post-Authentication>>
  52. * <<webflux-oauth2resourceserver-opaque-authorization-extraction,Extracting Authorities Manually>>
  53. * <<webflux-oauth2resourceserver-opaque-jwt-introspector,Using Introspection with JWTs>>
  54. [[webflux-oauth2resourceserver-opaque-attributes]]
  55. == Looking Up Attributes Post-Authentication
  56. Once a token is authenticated, an instance of `BearerTokenAuthentication` is set in the `SecurityContext`.
  57. This means that it's available in `@Controller` methods when using `@EnableWebFlux` in your configuration:
  58. ====
  59. .Java
  60. [source,java,role="primary"]
  61. ----
  62. @GetMapping("/foo")
  63. public Mono<String> foo(BearerTokenAuthentication authentication) {
  64. return Mono.just(authentication.getTokenAttributes().get("sub") + " is the subject");
  65. }
  66. ----
  67. .Kotlin
  68. [source,kotlin,role="secondary"]
  69. ----
  70. @GetMapping("/foo")
  71. fun foo(authentication: BearerTokenAuthentication): Mono<String> {
  72. return Mono.just(authentication.tokenAttributes["sub"].toString() + " is the subject")
  73. }
  74. ----
  75. ====
  76. Since `BearerTokenAuthentication` holds an `OAuth2AuthenticatedPrincipal`, that also means that it's available to controller methods, too:
  77. ====
  78. .Java
  79. [source,java,role="primary"]
  80. ----
  81. @GetMapping("/foo")
  82. public Mono<String> foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
  83. return Mono.just(principal.getAttribute("sub") + " is the subject");
  84. }
  85. ----
  86. .Kotlin
  87. [source,kotlin,role="secondary"]
  88. ----
  89. @GetMapping("/foo")
  90. fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): Mono<String> {
  91. return Mono.just(principal.getAttribute<Any>("sub").toString() + " is the subject")
  92. }
  93. ----
  94. ====
  95. === Looking Up Attributes Via SpEL
  96. Of course, this also means that attributes can be accessed via SpEL.
  97. For example, if using `@EnableReactiveMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do:
  98. ====
  99. .Java
  100. [source,java,role="primary"]
  101. ----
  102. @PreAuthorize("principal?.attributes['sub'] = 'foo'")
  103. public Mono<String> forFoosEyesOnly() {
  104. return Mono.just("foo");
  105. }
  106. ----
  107. .Kotlin
  108. [source,kotlin,role="secondary"]
  109. ----
  110. @PreAuthorize("principal.attributes['sub'] = 'foo'")
  111. fun forFoosEyesOnly(): Mono<String> {
  112. return Mono.just("foo")
  113. }
  114. ----
  115. ====
  116. [[webflux-oauth2resourceserver-opaque-sansboot]]
  117. == Overriding or Replacing Boot Auto Configuration
  118. There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf.
  119. The first is a `SecurityWebFilterChain` that configures the app as a resource server.
  120. When use Opaque Token, this `SecurityWebFilterChain` looks like:
  121. ====
  122. .Java
  123. [source,java,role="primary"]
  124. ----
  125. @Bean
  126. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  127. http
  128. .authorizeExchange(exchanges -> exchanges
  129. .anyExchange().authenticated()
  130. )
  131. .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken)
  132. return http.build();
  133. }
  134. ----
  135. .Kotlin
  136. [source,kotlin,role="secondary"]
  137. ----
  138. @Bean
  139. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  140. return http {
  141. authorizeExchange {
  142. authorize(anyExchange, authenticated)
  143. }
  144. oauth2ResourceServer {
  145. opaqueToken { }
  146. }
  147. }
  148. }
  149. ----
  150. ====
  151. If the application doesn't expose a `SecurityWebFilterChain` bean, then Spring Boot will expose the above default one.
  152. Replacing this is as simple as exposing the bean within the application:
  153. .Replacing SecurityWebFilterChain
  154. ====
  155. .Java
  156. [source,java,role="primary"]
  157. ----
  158. @EnableWebFluxSecurity
  159. public class MyCustomSecurityConfiguration {
  160. @Bean
  161. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  162. http
  163. .authorizeExchange(exchanges -> exchanges
  164. .pathMatchers("/messages/**").hasAuthority("SCOPE_message:read")
  165. .anyExchange().authenticated()
  166. )
  167. .oauth2ResourceServer(oauth2 -> oauth2
  168. .opaqueToken(opaqueToken -> opaqueToken
  169. .introspector(myIntrospector())
  170. )
  171. );
  172. return http.build();
  173. }
  174. }
  175. ----
  176. .Kotlin
  177. [source,kotlin,role="secondary"]
  178. ----
  179. @Bean
  180. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  181. return http {
  182. authorizeExchange {
  183. authorize("/messages/**", hasAuthority("SCOPE_message:read"))
  184. authorize(anyExchange, authenticated)
  185. }
  186. oauth2ResourceServer {
  187. opaqueToken {
  188. introspector = myIntrospector()
  189. }
  190. }
  191. }
  192. }
  193. ----
  194. ====
  195. The above requires the scope of `message:read` for any URL that starts with `/messages/`.
  196. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration.
  197. For example, the second `@Bean` Spring Boot creates is a `ReactiveOpaqueTokenIntrospector`, which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`:
  198. ====
  199. .Java
  200. [source,java,role="primary"]
  201. ----
  202. @Bean
  203. public ReactiveOpaqueTokenIntrospector introspector() {
  204. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  205. }
  206. ----
  207. .Kotlin
  208. [source,kotlin,role="secondary"]
  209. ----
  210. @Bean
  211. fun introspector(): ReactiveOpaqueTokenIntrospector {
  212. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  213. }
  214. ----
  215. ====
  216. If the application doesn't expose a `ReactiveOpaqueTokenIntrospector` bean, then Spring Boot will expose the above default one.
  217. And its configuration can be overridden using `introspectionUri()` and `introspectionClientCredentials()` or replaced using `introspector()`.
  218. [[webflux-oauth2resourceserver-opaque-introspectionuri-dsl]]
  219. === Using `introspectionUri()`
  220. An authorization server's Introspection Uri can be configured <<webflux-oauth2resourceserver-opaque-introspectionuri,as a configuration property>> or it can be supplied in the DSL:
  221. ====
  222. .Java
  223. [source,java,role="primary"]
  224. ----
  225. @EnableWebFluxSecurity
  226. public class DirectlyConfiguredIntrospectionUri {
  227. @Bean
  228. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  229. http
  230. .authorizeExchange(exchanges -> exchanges
  231. .anyExchange().authenticated()
  232. )
  233. .oauth2ResourceServer(oauth2 -> oauth2
  234. .opaqueToken(opaqueToken -> opaqueToken
  235. .introspectionUri("https://idp.example.com/introspect")
  236. .introspectionClientCredentials("client", "secret")
  237. )
  238. );
  239. return http.build();
  240. }
  241. }
  242. ----
  243. .Kotlin
  244. [source,kotlin,role="secondary"]
  245. ----
  246. @Bean
  247. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  248. return http {
  249. authorizeExchange {
  250. authorize(anyExchange, authenticated)
  251. }
  252. oauth2ResourceServer {
  253. opaqueToken {
  254. introspectionUri = "https://idp.example.com/introspect"
  255. introspectionClientCredentials("client", "secret")
  256. }
  257. }
  258. }
  259. }
  260. ----
  261. ====
  262. Using `introspectionUri()` takes precedence over any configuration property.
  263. [[webflux-oauth2resourceserver-opaque-introspector-dsl]]
  264. === Using `introspector()`
  265. More powerful than `introspectionUri()` is `introspector()`, which will completely replace any Boot auto configuration of `ReactiveOpaqueTokenIntrospector`:
  266. ====
  267. .Java
  268. [source,java,role="primary"]
  269. ----
  270. @EnableWebFluxSecurity
  271. public class DirectlyConfiguredIntrospector {
  272. @Bean
  273. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  274. http
  275. .authorizeExchange(exchanges -> exchanges
  276. .anyExchange().authenticated()
  277. )
  278. .oauth2ResourceServer(oauth2 -> oauth2
  279. .opaqueToken(opaqueToken -> opaqueToken
  280. .introspector(myCustomIntrospector())
  281. )
  282. );
  283. return http.build();
  284. }
  285. }
  286. ----
  287. .Kotlin
  288. [source,kotlin,role="secondary"]
  289. ----
  290. @Bean
  291. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  292. return http {
  293. authorizeExchange {
  294. authorize(anyExchange, authenticated)
  295. }
  296. oauth2ResourceServer {
  297. opaqueToken {
  298. introspector = myCustomIntrospector()
  299. }
  300. }
  301. }
  302. }
  303. ----
  304. ====
  305. This is handy when deeper configuration, like <<webflux-oauth2resourceserver-opaque-authorization-extraction,authority mapping>>or <<webflux-oauth2resourceserver-opaque-jwt-introspector,JWT revocation>> is necessary.
  306. [[webflux-oauth2resourceserver-opaque-introspector-bean]]
  307. === Exposing a `ReactiveOpaqueTokenIntrospector` `@Bean`
  308. Or, exposing a `ReactiveOpaqueTokenIntrospector` `@Bean` has the same effect as `introspector()`:
  309. ====
  310. .Java
  311. [source,java,role="primary"]
  312. ----
  313. @Bean
  314. public ReactiveOpaqueTokenIntrospector introspector() {
  315. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  316. }
  317. ----
  318. .Kotlin
  319. [source,kotlin,role="secondary"]
  320. ----
  321. @Bean
  322. fun introspector(): ReactiveOpaqueTokenIntrospector {
  323. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  324. }
  325. ----
  326. ====
  327. [[webflux-oauth2resourceserver-opaque-authorization]]
  328. == Configuring Authorization
  329. An OAuth 2.0 Introspection endpoint will typically return a `scope` attribute, indicating the scopes (or authorities) it's been granted, for example:
  330. `{ ..., "scope" : "messages contacts"}`
  331. When this is the case, Resource Server will attempt to coerce these scopes into a list of granted authorities, prefixing each scope with the string "SCOPE_".
  332. This means that to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix:
  333. ====
  334. .Java
  335. [source,java,role="primary"]
  336. ----
  337. @EnableWebFluxSecurity
  338. public class MappedAuthorities {
  339. @Bean
  340. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  341. http
  342. .authorizeExchange(exchange -> exchange
  343. .pathMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  344. .pathMatchers("/messages/**").hasAuthority("SCOPE_messages")
  345. .anyExchange().authenticated()
  346. )
  347. .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken);
  348. return http.build();
  349. }
  350. }
  351. ----
  352. .Kotlin
  353. [source,kotlin,role="secondary"]
  354. ----
  355. @Bean
  356. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  357. return http {
  358. authorizeExchange {
  359. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  360. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  361. authorize(anyExchange, authenticated)
  362. }
  363. oauth2ResourceServer {
  364. opaqueToken { }
  365. }
  366. }
  367. }
  368. ----
  369. ====
  370. Or similarly with method security:
  371. ====
  372. .Java
  373. [source,java,role="primary"]
  374. ----
  375. @PreAuthorize("hasAuthority('SCOPE_messages')")
  376. public Flux<Message> getMessages(...) {}
  377. ----
  378. .Kotlin
  379. [source,kotlin,role="secondary"]
  380. ----
  381. @PreAuthorize("hasAuthority('SCOPE_messages')")
  382. fun getMessages(): Flux<Message> { }
  383. ----
  384. ====
  385. [[webflux-oauth2resourceserver-opaque-authorization-extraction]]
  386. === Extracting Authorities Manually
  387. By default, Opaque Token support will extract the scope claim from an introspection response and parse it into individual `GrantedAuthority` instances.
  388. For example, if the introspection response were:
  389. [source,json]
  390. ----
  391. {
  392. "active" : true,
  393. "scope" : "message:read message:write"
  394. }
  395. ----
  396. Then Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`.
  397. This can, of course, be customized using a custom `ReactiveOpaqueTokenIntrospector` that takes a look at the attribute set and converts in its own way:
  398. ====
  399. .Java
  400. [source,java,role="primary"]
  401. ----
  402. public class CustomAuthoritiesOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  403. private ReactiveOpaqueTokenIntrospector delegate =
  404. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  405. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  406. return this.delegate.introspect(token)
  407. .map(principal -> new DefaultOAuth2AuthenticatedPrincipal(
  408. principal.getName(), principal.getAttributes(), extractAuthorities(principal)));
  409. }
  410. private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
  411. List<String> scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE);
  412. return scopes.stream()
  413. .map(SimpleGrantedAuthority::new)
  414. .collect(Collectors.toList());
  415. }
  416. }
  417. ----
  418. .Kotlin
  419. [source,kotlin,role="secondary"]
  420. ----
  421. class CustomAuthoritiesOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  422. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  423. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  424. return delegate.introspect(token)
  425. .map { principal: OAuth2AuthenticatedPrincipal ->
  426. DefaultOAuth2AuthenticatedPrincipal(
  427. principal.name, principal.attributes, extractAuthorities(principal))
  428. }
  429. }
  430. private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
  431. val scopes = principal.getAttribute<List<String>>(OAuth2IntrospectionClaimNames.SCOPE)
  432. return scopes
  433. .map { SimpleGrantedAuthority(it) }
  434. }
  435. }
  436. ----
  437. ====
  438. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  439. ====
  440. .Java
  441. [source,java,role="primary"]
  442. ----
  443. @Bean
  444. public ReactiveOpaqueTokenIntrospector introspector() {
  445. return new CustomAuthoritiesOpaqueTokenIntrospector();
  446. }
  447. ----
  448. .Kotlin
  449. [source,kotlin,role="secondary"]
  450. ----
  451. @Bean
  452. fun introspector(): ReactiveOpaqueTokenIntrospector {
  453. return CustomAuthoritiesOpaqueTokenIntrospector()
  454. }
  455. ----
  456. ====
  457. [[webflux-oauth2resourceserver-opaque-jwt-introspector]]
  458. == Using Introspection with JWTs
  459. A common question is whether or not introspection is compatible with JWTs.
  460. Spring Security's Opaque Token support has been designed to not care about the format of the token -- it will gladly pass any token to the introspection endpoint provided.
  461. So, let's say that you've got a requirement that requires you to check with the authorization server on each request, in case the JWT has been revoked.
  462. Even though you are using the JWT format for the token, your validation method is introspection, meaning you'd want to do:
  463. [source,yaml]
  464. ----
  465. spring:
  466. security:
  467. oauth2:
  468. resourceserver:
  469. opaque-token:
  470. introspection-uri: https://idp.example.org/introspection
  471. client-id: client
  472. client-secret: secret
  473. ----
  474. In this case, the resulting `Authentication` would be `BearerTokenAuthentication`.
  475. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint.
  476. But, let's say that, oddly enough, the introspection endpoint only returns whether or not the token is active.
  477. Now what?
  478. In this case, you can create a custom `ReactiveOpaqueTokenIntrospector` that still hits the endpoint, but then updates the returned principal to have the JWTs claims as the attributes:
  479. ====
  480. .Java
  481. [source,java,role="primary"]
  482. ----
  483. public class JwtOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  484. private ReactiveOpaqueTokenIntrospector delegate =
  485. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  486. private ReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder(new ParseOnlyJWTProcessor());
  487. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  488. return this.delegate.introspect(token)
  489. .flatMap(principal -> this.jwtDecoder.decode(token))
  490. .map(jwt -> new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES));
  491. }
  492. private static class ParseOnlyJWTProcessor implements Converter<JWT, Mono<JWTClaimsSet>> {
  493. public Mono<JWTClaimsSet> convert(JWT jwt) {
  494. try {
  495. return Mono.just(jwt.getJWTClaimsSet());
  496. } catch (Exception ex) {
  497. return Mono.error(ex);
  498. }
  499. }
  500. }
  501. }
  502. ----
  503. .Kotlin
  504. [source,kotlin,role="secondary"]
  505. ----
  506. class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  507. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  508. private val jwtDecoder: ReactiveJwtDecoder = NimbusReactiveJwtDecoder(ParseOnlyJWTProcessor())
  509. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  510. return delegate.introspect(token)
  511. .flatMap { jwtDecoder.decode(token) }
  512. .map { jwt: Jwt -> DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES) }
  513. }
  514. private class ParseOnlyJWTProcessor : Converter<JWT, Mono<JWTClaimsSet>> {
  515. override fun convert(jwt: JWT): Mono<JWTClaimsSet> {
  516. return try {
  517. Mono.just(jwt.jwtClaimsSet)
  518. } catch (e: Exception) {
  519. Mono.error(e)
  520. }
  521. }
  522. }
  523. }
  524. ----
  525. ====
  526. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  527. ====
  528. .Java
  529. [source,java,role="primary"]
  530. ----
  531. @Bean
  532. public ReactiveOpaqueTokenIntrospector introspector() {
  533. return new JwtOpaqueTokenIntropsector();
  534. }
  535. ----
  536. .Kotlin
  537. [source,kotlin,role="secondary"]
  538. ----
  539. @Bean
  540. fun introspector(): ReactiveOpaqueTokenIntrospector {
  541. return JwtOpaqueTokenIntrospector()
  542. }
  543. ----
  544. ====
  545. [[webflux-oauth2resourceserver-opaque-userinfo]]
  546. == Calling a `/userinfo` Endpoint
  547. Generally speaking, a Resource Server doesn't care about the underlying user, but instead about the authorities that have been granted.
  548. That said, at times it can be valuable to tie the authorization statement back to a user.
  549. If an application is also using `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, then this is quite simple with a custom `OpaqueTokenIntrospector`.
  550. This implementation below does three things:
  551. * Delegates to the introspection endpoint, to affirm the token's validity
  552. * Looks up the appropriate client registration associated with the `/userinfo` endpoint
  553. * Invokes and returns the response from the `/userinfo` endpoint
  554. ====
  555. .Java
  556. [source,java,role="primary"]
  557. ----
  558. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  559. private final ReactiveOpaqueTokenIntrospector delegate =
  560. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  561. private final ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService =
  562. new DefaultReactiveOAuth2UserService();
  563. private final ReactiveClientRegistrationRepository repository;
  564. // ... constructor
  565. @Override
  566. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  567. return Mono.zip(this.delegate.introspect(token), this.repository.findByRegistrationId("registration-id"))
  568. .map(t -> {
  569. OAuth2AuthenticatedPrincipal authorized = t.getT1();
  570. ClientRegistration clientRegistration = t.getT2();
  571. Instant issuedAt = authorized.getAttribute(ISSUED_AT);
  572. Instant expiresAt = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT);
  573. OAuth2AccessToken accessToken = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
  574. return new OAuth2UserRequest(clientRegistration, accessToken);
  575. })
  576. .flatMap(this.oauth2UserService::loadUser);
  577. }
  578. }
  579. ----
  580. .Kotlin
  581. [source,kotlin,role="secondary"]
  582. ----
  583. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  584. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  585. private val oauth2UserService: ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> = DefaultReactiveOAuth2UserService()
  586. private val repository: ReactiveClientRegistrationRepository? = null
  587. // ... constructor
  588. override fun introspect(token: String?): Mono<OAuth2AuthenticatedPrincipal> {
  589. return Mono.zip<OAuth2AuthenticatedPrincipal, ClientRegistration>(delegate.introspect(token), repository!!.findByRegistrationId("registration-id"))
  590. .map<OAuth2UserRequest> { t: Tuple2<OAuth2AuthenticatedPrincipal, ClientRegistration> ->
  591. val authorized = t.t1
  592. val clientRegistration = t.t2
  593. val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
  594. val expiresAt: Instant? = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT)
  595. val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
  596. OAuth2UserRequest(clientRegistration, accessToken)
  597. }
  598. .flatMap { userRequest: OAuth2UserRequest -> oauth2UserService.loadUser(userRequest) }
  599. }
  600. }
  601. ----
  602. ====
  603. If you aren't using `spring-security-oauth2-client`, it's still quite simple.
  604. You will simply need to invoke the `/userinfo` with your own instance of `WebClient`:
  605. ====
  606. .Java
  607. [source,java,role="primary"]
  608. ----
  609. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  610. private final ReactiveOpaqueTokenIntrospector delegate =
  611. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  612. private final WebClient rest = WebClient.create();
  613. @Override
  614. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  615. return this.delegate.introspect(token)
  616. .map(this::makeUserInfoRequest);
  617. }
  618. }
  619. ----
  620. .Kotlin
  621. [source,kotlin,role="secondary"]
  622. ----
  623. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  624. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  625. private val rest: WebClient = WebClient.create()
  626. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  627. return delegate.introspect(token)
  628. .map(this::makeUserInfoRequest)
  629. }
  630. }
  631. ----
  632. ====
  633. Either way, having created your `ReactiveOpaqueTokenIntrospector`, you should publish it as a `@Bean` to override the defaults:
  634. ====
  635. .Java
  636. [source,java,role="primary"]
  637. ----
  638. @Bean
  639. ReactiveOpaqueTokenIntrospector introspector() {
  640. return new UserInfoOpaqueTokenIntrospector();
  641. }
  642. ----
  643. .Kotlin
  644. [source,kotlin,role="secondary"]
  645. ----
  646. @Bean
  647. fun introspector(): ReactiveOpaqueTokenIntrospector {
  648. return UserInfoOpaqueTokenIntrospector()
  649. }
  650. ----
  651. ====