opaque-token.adoc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. = OAuth 2.0 Resource Server Opaque Token
  2. :figures: servlet/oauth2
  3. [[oauth2resourceserver-opaque-minimaldependencies]]
  4. == Minimal Dependencies for Introspection
  5. 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`.
  6. However unless a custom <<oauth2resourceserver-opaque-introspector,`OpaqueTokenIntrospector`>> is provided, the Resource Server will fallback to NimbusOpaqueTokenIntrospector.
  7. 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.
  8. Please refer to `spring-security-oauth2-resource-server` in order to determine the correct version for `oauth2-oidc-sdk`.
  9. [[oauth2resourceserver-opaque-minimalconfiguration]]
  10. == Minimal Configuration for Introspection
  11. 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.
  12. This can be handy when revocation is a requirement.
  13. 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.
  14. First, include the needed dependencies and second, indicate the introspection endpoint details.
  15. [[oauth2resourceserver-opaque-introspectionuri]]
  16. === Specifying the Authorization Server
  17. To specify where the introspection endpoint is, simply do:
  18. [source,yaml]
  19. ----
  20. spring:
  21. security:
  22. oauth2:
  23. resourceserver:
  24. opaque-token:
  25. introspection-uri: https://idp.example.com/introspect
  26. client-id: client
  27. client-secret: secret
  28. ----
  29. 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.
  30. Resource Server will use these properties to further self-configure and subsequently validate incoming JWTs.
  31. [NOTE]
  32. When using introspection, the authorization server's word is the law.
  33. If the authorization server responses that the token is valid, then it is.
  34. And that's it!
  35. === Startup Expectations
  36. When this property and these dependencies are used, Resource Server will automatically configure itself to validate Opaque Bearer Tokens.
  37. 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.
  38. === Runtime Expectations
  39. Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header:
  40. [source,http]
  41. ----
  42. GET / HTTP/1.1
  43. Authorization: Bearer some-token-value # Resource Server will process this
  44. ----
  45. So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification.
  46. Given an Opaque Token, Resource Server will
  47. 1. Query the provided introspection endpoint using the provided credentials and the token
  48. 2. Inspect the response for an `{ 'active' : true }` attribute
  49. 3. Map each scope to an authority with the prefix `SCOPE_`
  50. 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.
  51. From here, you may want to jump to:
  52. * <<oauth2resourceserver-opaque-architecture>>
  53. * <<oauth2resourceserver-opaque-attributes,Looking Up Attributes Post-Authentication>>
  54. * <<oauth2resourceserver-opaque-authorization-extraction,Extracting Authorities Manually>>
  55. * <<oauth2resourceserver-opaque-jwt-introspector,Using Introspection with JWTs>>
  56. [[oauth2resourceserver-opaque-architecture]]
  57. == How Opaque Token Authentication Works
  58. Next, let's see the architectural components that Spring Security uses to support https://tools.ietf.org/html/rfc7662[opaque token] Authentication in servlet-based applications, like the one we just saw.
  59. {security-api-url}org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.html[`OpaqueTokenAuthenticationProvider`] is an xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationprovider[`AuthenticationProvider`] implementation that leverages a <<oauth2resourceserver-opaque-introspector,`OpaqueTokenIntrospector`>> to authenticate an opaque token.
  60. Let's take a look at how `OpaqueTokenAuthenticationProvider` works within Spring Security.
  61. The figure explains details of how the xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationmanager[`AuthenticationManager`] in figures from <<oauth2resourceserver-authentication-bearertokenauthenticationfilter,Reading the Bearer Token>> works.
  62. .`OpaqueTokenAuthenticationProvider` Usage
  63. image::{figures}/opaquetokenauthenticationprovider.png[]
  64. image:{icondir}/number_1.png[] The authentication `Filter` from <<oauth2resourceserver-authentication-bearertokenauthenticationfilter,Reading the Bearer Token>> passes a `BearerTokenAuthenticationToken` to the `AuthenticationManager` which is implemented by xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`ProviderManager`].
  65. image:{icondir}/number_2.png[] The `ProviderManager` is configured to use an xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationprovider[AuthenticationProvider] of type `OpaqueTokenAuthenticationProvider`.
  66. [[oauth2resourceserver-opaque-architecture-introspector]]
  67. image:{icondir}/number_3.png[] `OpaqueTokenAuthenticationProvider` introspects the opaque token and adds granted authorities using an <<oauth2resourceserver-opaque-introspector,`OpaqueTokenIntrospector`>>.
  68. When authentication is successful, the xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] that is returned is of type `BearerTokenAuthentication` and has a principal that is the `OAuth2AuthenticatedPrincipal` returned by the configured <<oauth2resourceserver-opaque-introspector,`OpaqueTokenIntrospector`>>.
  69. Ultimately, the returned `BearerTokenAuthentication` will be set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] by the authentication `Filter`.
  70. [[oauth2resourceserver-opaque-attributes]]
  71. == Looking Up Attributes Post-Authentication
  72. Once a token is authenticated, an instance of `BearerTokenAuthentication` is set in the `SecurityContext`.
  73. This means that it's available in `@Controller` methods when using `@EnableWebMvc` in your configuration:
  74. ====
  75. .Java
  76. [source,java,role="primary"]
  77. ----
  78. @GetMapping("/foo")
  79. public String foo(BearerTokenAuthentication authentication) {
  80. return authentication.getTokenAttributes().get("sub") + " is the subject";
  81. }
  82. ----
  83. .Kotlin
  84. [source,kotlin,role="secondary"]
  85. ----
  86. @GetMapping("/foo")
  87. fun foo(authentication: BearerTokenAuthentication): String {
  88. return authentication.tokenAttributes["sub"].toString() + " is the subject"
  89. }
  90. ----
  91. ====
  92. Since `BearerTokenAuthentication` holds an `OAuth2AuthenticatedPrincipal`, that also means that it's available to controller methods, too:
  93. ====
  94. .Java
  95. [source,java,role="primary"]
  96. ----
  97. @GetMapping("/foo")
  98. public String foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
  99. return principal.getAttribute("sub") + " is the subject";
  100. }
  101. ----
  102. .Kotlin
  103. [source,kotlin,role="secondary"]
  104. ----
  105. @GetMapping("/foo")
  106. fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): String {
  107. return principal.getAttribute<Any>("sub").toString() + " is the subject"
  108. }
  109. ----
  110. ====
  111. === Looking Up Attributes Via SpEL
  112. Of course, this also means that attributes can be accessed via SpEL.
  113. For example, if using `@EnableGlobalMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do:
  114. ====
  115. .Java
  116. [source,java,role="primary"]
  117. ----
  118. @PreAuthorize("principal?.attributes['sub'] == 'foo'")
  119. public String forFoosEyesOnly() {
  120. return "foo";
  121. }
  122. ----
  123. .Kotlin
  124. [source,kotlin,role="secondary"]
  125. ----
  126. @PreAuthorize("principal?.attributes['sub'] == 'foo'")
  127. fun forFoosEyesOnly(): String {
  128. return "foo"
  129. }
  130. ----
  131. ====
  132. [[oauth2resourceserver-opaque-sansboot]]
  133. == Overriding or Replacing Boot Auto Configuration
  134. There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf.
  135. The first is a `SecurityFilterChain` that configures the app as a resource server.
  136. When use Opaque Token, this `SecurityFilterChain` looks like:
  137. .Default Opaque Token Configuration
  138. ====
  139. .Java
  140. [source,java,role="primary"]
  141. ----
  142. @Bean
  143. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  144. http
  145. .authorizeHttpRequests(authorize -> authorize
  146. .anyRequest().authenticated()
  147. )
  148. .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
  149. return http.build();
  150. }
  151. ----
  152. .Kotlin
  153. [source,kotlin,role="secondary"]
  154. ----
  155. @Bean
  156. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  157. http {
  158. authorizeRequests {
  159. authorize(anyRequest, authenticated)
  160. }
  161. oauth2ResourceServer {
  162. opaqueToken { }
  163. }
  164. }
  165. return http.build()
  166. }
  167. ----
  168. ====
  169. If the application doesn't expose a `SecurityFilterChain` bean, then Spring Boot will expose the above default one.
  170. Replacing this is as simple as exposing the bean within the application:
  171. .Custom Opaque Token Configuration
  172. ====
  173. .Java
  174. [source,java,role="primary"]
  175. ----
  176. @EnableWebSecurity
  177. public class MyCustomSecurityConfiguration {
  178. @Bean
  179. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  180. http
  181. .authorizeHttpRequests(authorize -> authorize
  182. .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read")
  183. .anyRequest().authenticated()
  184. )
  185. .oauth2ResourceServer(oauth2 -> oauth2
  186. .opaqueToken(opaqueToken -> opaqueToken
  187. .introspector(myIntrospector())
  188. )
  189. );
  190. return http.build();
  191. }
  192. }
  193. ----
  194. .Kotlin
  195. [source,kotlin,role="secondary"]
  196. ----
  197. @EnableWebSecurity
  198. class MyCustomSecurityConfiguration {
  199. @Bean
  200. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  201. http {
  202. authorizeRequests {
  203. authorize("/messages/**", hasAuthority("SCOPE_message:read"))
  204. authorize(anyRequest, authenticated)
  205. }
  206. oauth2ResourceServer {
  207. opaqueToken {
  208. introspector = myIntrospector()
  209. }
  210. }
  211. }
  212. return http.build()
  213. }
  214. }
  215. ----
  216. ====
  217. The above requires the scope of `message:read` for any URL that starts with `/messages/`.
  218. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration.
  219. [[oauth2resourceserver-opaque-introspector]]
  220. For example, the second `@Bean` Spring Boot creates is an `OpaqueTokenIntrospector`, <<oauth2resourceserver-opaque-architecture-introspector,which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`>>:
  221. ====
  222. .Java
  223. [source,java,role="primary"]
  224. ----
  225. @Bean
  226. public OpaqueTokenIntrospector introspector() {
  227. return new NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  228. }
  229. ----
  230. .Kotlin
  231. [source,kotlin,role="secondary"]
  232. ----
  233. @Bean
  234. fun introspector(): OpaqueTokenIntrospector {
  235. return NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  236. }
  237. ----
  238. ====
  239. If the application doesn't expose a <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> bean, then Spring Boot will expose the above default one.
  240. And its configuration can be overridden using `introspectionUri()` and `introspectionClientCredentials()` or replaced using `introspector()`.
  241. Or, if you're not using Spring Boot at all, then both of these components - the filter chain and a <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> can be specified in XML.
  242. The filter chain is specified like so:
  243. .Default Opaque Token Configuration
  244. ====
  245. .Xml
  246. [source,xml,role="primary"]
  247. ----
  248. <http>
  249. <intercept-uri pattern="/**" access="authenticated"/>
  250. <oauth2-resource-server>
  251. <opaque-token introspector-ref="opaqueTokenIntrospector"/>
  252. </oauth2-resource-server>
  253. </http>
  254. ----
  255. ====
  256. And the <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> like so:
  257. .Opaque Token Introspector
  258. ====
  259. .Xml
  260. [source,xml,role="primary"]
  261. ----
  262. <bean id="opaqueTokenIntrospector"
  263. class="org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector">
  264. <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.introspection_uri}"/>
  265. <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.client_id}"/>
  266. <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.client_secret}"/>
  267. </bean>
  268. ----
  269. ====
  270. [[oauth2resourceserver-opaque-introspectionuri-dsl]]
  271. === Using `introspectionUri()`
  272. An authorization server's Introspection Uri can be configured <<oauth2resourceserver-opaque-introspectionuri,as a configuration property>> or it can be supplied in the DSL:
  273. .Introspection URI Configuration
  274. ====
  275. .Java
  276. [source,java,role="primary"]
  277. ----
  278. @EnableWebSecurity
  279. public class DirectlyConfiguredIntrospectionUri {
  280. @Bean
  281. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  282. http
  283. .authorizeHttpRequests(authorize -> authorize
  284. .anyRequest().authenticated()
  285. )
  286. .oauth2ResourceServer(oauth2 -> oauth2
  287. .opaqueToken(opaqueToken -> opaqueToken
  288. .introspectionUri("https://idp.example.com/introspect")
  289. .introspectionClientCredentials("client", "secret")
  290. )
  291. );
  292. return http.build();
  293. }
  294. }
  295. ----
  296. .Kotlin
  297. [source,kotlin,role="secondary"]
  298. ----
  299. @EnableWebSecurity
  300. class DirectlyConfiguredIntrospectionUri {
  301. @Bean
  302. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  303. http {
  304. authorizeRequests {
  305. authorize(anyRequest, authenticated)
  306. }
  307. oauth2ResourceServer {
  308. opaqueToken {
  309. introspectionUri = "https://idp.example.com/introspect"
  310. introspectionClientCredentials("client", "secret")
  311. }
  312. }
  313. }
  314. return http.build()
  315. }
  316. }
  317. ----
  318. .Xml
  319. [source,xml,role="secondary"]
  320. ----
  321. <bean id="opaqueTokenIntrospector"
  322. class="org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector">
  323. <constructor-arg value="https://idp.example.com/introspect"/>
  324. <constructor-arg value="client"/>
  325. <constructor-arg value="secret"/>
  326. </bean>
  327. ----
  328. ====
  329. Using `introspectionUri()` takes precedence over any configuration property.
  330. [[oauth2resourceserver-opaque-introspector-dsl]]
  331. === Using `introspector()`
  332. More powerful than `introspectionUri()` is `introspector()`, which will completely replace any Boot auto configuration of <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>>:
  333. .Introspector Configuration
  334. ====
  335. .Java
  336. [source,java,role="primary"]
  337. ----
  338. @EnableWebSecurity
  339. public class DirectlyConfiguredIntrospector {
  340. @Bean
  341. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  342. http
  343. .authorizeHttpRequests(authorize -> authorize
  344. .anyRequest().authenticated()
  345. )
  346. .oauth2ResourceServer(oauth2 -> oauth2
  347. .opaqueToken(opaqueToken -> opaqueToken
  348. .introspector(myCustomIntrospector())
  349. )
  350. );
  351. return http.build();
  352. }
  353. }
  354. ----
  355. .Kotlin
  356. [source,kotlin,role="secondary"]
  357. ----
  358. @EnableWebSecurity
  359. class DirectlyConfiguredIntrospector {
  360. @Bean
  361. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  362. http {
  363. authorizeRequests {
  364. authorize(anyRequest, authenticated)
  365. }
  366. oauth2ResourceServer {
  367. opaqueToken {
  368. introspector = myCustomIntrospector()
  369. }
  370. }
  371. }
  372. return http.build()
  373. }
  374. }
  375. ----
  376. .Xml
  377. [source,xml,role="secondary"]
  378. ----
  379. <http>
  380. <intercept-uri pattern="/**" access="authenticated"/>
  381. <oauth2-resource-server>
  382. <opaque-token introspector-ref="myCustomIntrospector"/>
  383. </oauth2-resource-server>
  384. </http>
  385. ----
  386. ====
  387. This is handy when deeper configuration, like <<oauth2resourceserver-opaque-authorization-extraction,authority mapping>>, <<oauth2resourceserver-opaque-jwt-introspector,JWT revocation>>, or <<oauth2resourceserver-opaque-timeouts,request timeouts>>, is necessary.
  388. [[oauth2resourceserver-opaque-introspector-bean]]
  389. === Exposing a `OpaqueTokenIntrospector` `@Bean`
  390. Or, exposing a <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> `@Bean` has the same effect as `introspector()`:
  391. [source,java]
  392. ----
  393. @Bean
  394. public OpaqueTokenIntrospector introspector() {
  395. return new NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  396. }
  397. ----
  398. [[oauth2resourceserver-opaque-authorization]]
  399. == Configuring Authorization
  400. An OAuth 2.0 Introspection endpoint will typically return a `scope` attribute, indicating the scopes (or authorities) it's been granted, for example:
  401. `{ ..., "scope" : "messages contacts"}`
  402. 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_".
  403. This means that to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix:
  404. .Authorization Opaque Token Configuration
  405. ====
  406. .Java
  407. [source,java,role="primary"]
  408. ----
  409. @EnableWebSecurity
  410. public class MappedAuthorities {
  411. @Bean
  412. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  413. http
  414. .authorizeHttpRequests(authorizeRequests -> authorizeRequests
  415. .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  416. .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
  417. .anyRequest().authenticated()
  418. )
  419. .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
  420. return http.build();
  421. }
  422. }
  423. ----
  424. .Kotlin
  425. [source,kotlin,role="secondary"]
  426. ----
  427. @EnableWebSecurity
  428. class MappedAuthorities {
  429. @Bean
  430. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  431. http {
  432. authorizeRequests {
  433. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  434. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  435. authorize(anyRequest, authenticated)
  436. }
  437. oauth2ResourceServer {
  438. opaqueToken { }
  439. }
  440. }
  441. return http.build()
  442. }
  443. }
  444. ----
  445. .Xml
  446. [source,xml,role="secondary"]
  447. ----
  448. <http>
  449. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  450. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  451. <oauth2-resource-server>
  452. <opaque-token introspector-ref="opaqueTokenIntrospector"/>
  453. </oauth2-resource-server>
  454. </http>
  455. ----
  456. ====
  457. Or similarly with method security:
  458. ====
  459. .Java
  460. [source,java,role="primary"]
  461. ----
  462. @PreAuthorize("hasAuthority('SCOPE_messages')")
  463. public List<Message> getMessages(...) {}
  464. ----
  465. .Kotlin
  466. [source,kotlin,role="secondary"]
  467. ----
  468. @PreAuthorize("hasAuthority('SCOPE_messages')")
  469. fun getMessages(): List<Message?> {}
  470. ----
  471. ====
  472. [[oauth2resourceserver-opaque-authorization-extraction]]
  473. === Extracting Authorities Manually
  474. By default, Opaque Token support will extract the scope claim from an introspection response and parse it into individual `GrantedAuthority` instances.
  475. For example, if the introspection response were:
  476. [source,json]
  477. ----
  478. {
  479. "active" : true,
  480. "scope" : "message:read message:write"
  481. }
  482. ----
  483. Then Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`.
  484. This can, of course, be customized using a custom <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> that takes a look at the attribute set and converts in its own way:
  485. ====
  486. .Java
  487. [source,java,role="primary"]
  488. ----
  489. public class CustomAuthoritiesOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  490. private OpaqueTokenIntrospector delegate =
  491. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  492. public OAuth2AuthenticatedPrincipal introspect(String token) {
  493. OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token);
  494. return new DefaultOAuth2AuthenticatedPrincipal(
  495. principal.getName(), principal.getAttributes(), extractAuthorities(principal));
  496. }
  497. private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
  498. List<String> scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE);
  499. return scopes.stream()
  500. .map(SimpleGrantedAuthority::new)
  501. .collect(Collectors.toList());
  502. }
  503. }
  504. ----
  505. .Kotlin
  506. [source,kotlin,role="secondary"]
  507. ----
  508. class CustomAuthoritiesOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  509. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  510. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  511. val principal: OAuth2AuthenticatedPrincipal = delegate.introspect(token)
  512. return DefaultOAuth2AuthenticatedPrincipal(
  513. principal.name, principal.attributes, extractAuthorities(principal))
  514. }
  515. private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
  516. val scopes: List<String> = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE)
  517. return scopes
  518. .map { SimpleGrantedAuthority(it) }
  519. }
  520. }
  521. ----
  522. ====
  523. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  524. ====
  525. .Java
  526. [source,java,role="primary"]
  527. ----
  528. @Bean
  529. public OpaqueTokenIntrospector introspector() {
  530. return new CustomAuthoritiesOpaqueTokenIntrospector();
  531. }
  532. ----
  533. .Kotlin
  534. [source,kotlin,role="secondary"]
  535. ----
  536. @Bean
  537. fun introspector(): OpaqueTokenIntrospector {
  538. return CustomAuthoritiesOpaqueTokenIntrospector()
  539. }
  540. ----
  541. ====
  542. [[oauth2resourceserver-opaque-timeouts]]
  543. == Configuring Timeouts
  544. By default, Resource Server uses connection and socket timeouts of 30 seconds each for coordinating with the authorization server.
  545. This may be too short in some scenarios.
  546. Further, it doesn't take into account more sophisticated patterns like back-off and discovery.
  547. To adjust the way in which Resource Server connects to the authorization server, `NimbusOpaqueTokenIntrospector` accepts an instance of `RestOperations`:
  548. ====
  549. .Java
  550. [source,java,role="primary"]
  551. ----
  552. @Bean
  553. public OpaqueTokenIntrospector introspector(RestTemplateBuilder builder, OAuth2ResourceServerProperties properties) {
  554. RestOperations rest = builder
  555. .basicAuthentication(properties.getOpaquetoken().getClientId(), properties.getOpaquetoken().getClientSecret())
  556. .setConnectTimeout(Duration.ofSeconds(60))
  557. .setReadTimeout(Duration.ofSeconds(60))
  558. .build();
  559. return new NimbusOpaqueTokenIntrospector(introspectionUri, rest);
  560. }
  561. ----
  562. .Kotlin
  563. [source,kotlin,role="secondary"]
  564. ----
  565. @Bean
  566. fun introspector(builder: RestTemplateBuilder, properties: OAuth2ResourceServerProperties): OpaqueTokenIntrospector? {
  567. val rest: RestOperations = builder
  568. .basicAuthentication(properties.opaquetoken.clientId, properties.opaquetoken.clientSecret)
  569. .setConnectTimeout(Duration.ofSeconds(60))
  570. .setReadTimeout(Duration.ofSeconds(60))
  571. .build()
  572. return NimbusOpaqueTokenIntrospector(introspectionUri, rest)
  573. }
  574. ----
  575. ====
  576. [[oauth2resourceserver-opaque-jwt-introspector]]
  577. == Using Introspection with JWTs
  578. A common question is whether or not introspection is compatible with JWTs.
  579. 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.
  580. 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.
  581. Even though you are using the JWT format for the token, your validation method is introspection, meaning you'd want to do:
  582. [source,yaml]
  583. ----
  584. spring:
  585. security:
  586. oauth2:
  587. resourceserver:
  588. opaque-token:
  589. introspection-uri: https://idp.example.org/introspection
  590. client-id: client
  591. client-secret: secret
  592. ----
  593. In this case, the resulting `Authentication` would be `BearerTokenAuthentication`.
  594. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint.
  595. But, let's say that, oddly enough, the introspection endpoint only returns whether or not the token is active.
  596. Now what?
  597. In this case, you can create a custom <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> that still hits the endpoint, but then updates the returned principal to have the JWTs claims as the attributes:
  598. ====
  599. .Java
  600. [source,java,role="primary"]
  601. ----
  602. public class JwtOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  603. private OpaqueTokenIntrospector delegate =
  604. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  605. private JwtDecoder jwtDecoder = new NimbusJwtDecoder(new ParseOnlyJWTProcessor());
  606. public OAuth2AuthenticatedPrincipal introspect(String token) {
  607. OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token);
  608. try {
  609. Jwt jwt = this.jwtDecoder.decode(token);
  610. return new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES);
  611. } catch (JwtException ex) {
  612. throw new OAuth2IntrospectionException(ex);
  613. }
  614. }
  615. private static class ParseOnlyJWTProcessor extends DefaultJWTProcessor<SecurityContext> {
  616. JWTClaimsSet process(SignedJWT jwt, SecurityContext context)
  617. throws JOSEException {
  618. return jwt.getJWTClaimsSet();
  619. }
  620. }
  621. }
  622. ----
  623. .Kotlin
  624. [source,kotlin,role="secondary"]
  625. ----
  626. class JwtOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  627. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  628. private val jwtDecoder: JwtDecoder = NimbusJwtDecoder(ParseOnlyJWTProcessor())
  629. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  630. val principal = delegate.introspect(token)
  631. return try {
  632. val jwt: Jwt = jwtDecoder.decode(token)
  633. DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES)
  634. } catch (ex: JwtException) {
  635. throw OAuth2IntrospectionException(ex.message)
  636. }
  637. }
  638. private class ParseOnlyJWTProcessor : DefaultJWTProcessor<SecurityContext>() {
  639. override fun process(jwt: SignedJWT, context: SecurityContext): JWTClaimsSet {
  640. return jwt.jwtClaimsSet
  641. }
  642. }
  643. }
  644. ----
  645. ====
  646. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  647. ====
  648. .Java
  649. [source,java,role="primary"]
  650. ----
  651. @Bean
  652. public OpaqueTokenIntrospector introspector() {
  653. return new JwtOpaqueTokenIntrospector();
  654. }
  655. ----
  656. .Kotlin
  657. [source,kotlin,role="secondary"]
  658. ----
  659. @Bean
  660. fun introspector(): OpaqueTokenIntrospector {
  661. return JwtOpaqueTokenIntrospector()
  662. }
  663. ----
  664. ====
  665. [[oauth2resourceserver-opaque-userinfo]]
  666. == Calling a `/userinfo` Endpoint
  667. Generally speaking, a Resource Server doesn't care about the underlying user, but instead about the authorities that have been granted.
  668. That said, at times it can be valuable to tie the authorization statement back to a user.
  669. If an application is also using `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, then this is quite simple with a custom <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>>.
  670. This implementation below does three things:
  671. * Delegates to the introspection endpoint, to affirm the token's validity
  672. * Looks up the appropriate client registration associated with the `/userinfo` endpoint
  673. * Invokes and returns the response from the `/userinfo` endpoint
  674. ====
  675. .Java
  676. [source,java,role="primary"]
  677. ----
  678. public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  679. private final OpaqueTokenIntrospector delegate =
  680. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  681. private final OAuth2UserService oauth2UserService = new DefaultOAuth2UserService();
  682. private final ClientRegistrationRepository repository;
  683. // ... constructor
  684. @Override
  685. public OAuth2AuthenticatedPrincipal introspect(String token) {
  686. OAuth2AuthenticatedPrincipal authorized = this.delegate.introspect(token);
  687. Instant issuedAt = authorized.getAttribute(ISSUED_AT);
  688. Instant expiresAt = authorized.getAttribute(EXPIRES_AT);
  689. ClientRegistration clientRegistration = this.repository.findByRegistrationId("registration-id");
  690. OAuth2AccessToken token = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
  691. OAuth2UserRequest oauth2UserRequest = new OAuth2UserRequest(clientRegistration, token);
  692. return this.oauth2UserService.loadUser(oauth2UserRequest);
  693. }
  694. }
  695. ----
  696. .Kotlin
  697. [source,kotlin,role="secondary"]
  698. ----
  699. class UserInfoOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  700. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  701. private val oauth2UserService = DefaultOAuth2UserService()
  702. private val repository: ClientRegistrationRepository? = null
  703. // ... constructor
  704. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  705. val authorized = delegate.introspect(token)
  706. val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
  707. val expiresAt: Instant? = authorized.getAttribute(EXPIRES_AT)
  708. val clientRegistration: ClientRegistration = repository!!.findByRegistrationId("registration-id")
  709. val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
  710. val oauth2UserRequest = OAuth2UserRequest(clientRegistration, accessToken)
  711. return oauth2UserService.loadUser(oauth2UserRequest)
  712. }
  713. }
  714. ----
  715. ====
  716. If you aren't using `spring-security-oauth2-client`, it's still quite simple.
  717. You will simply need to invoke the `/userinfo` with your own instance of `WebClient`:
  718. ====
  719. .Java
  720. [source,java,role="primary"]
  721. ----
  722. public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  723. private final OpaqueTokenIntrospector delegate =
  724. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  725. private final WebClient rest = WebClient.create();
  726. @Override
  727. public OAuth2AuthenticatedPrincipal introspect(String token) {
  728. OAuth2AuthenticatedPrincipal authorized = this.delegate.introspect(token);
  729. return makeUserInfoRequest(authorized);
  730. }
  731. }
  732. ----
  733. .Kotlin
  734. [source,kotlin,role="secondary"]
  735. ----
  736. class UserInfoOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  737. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  738. private val rest: WebClient = WebClient.create()
  739. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  740. val authorized = delegate.introspect(token)
  741. return makeUserInfoRequest(authorized)
  742. }
  743. }
  744. ----
  745. ====
  746. Either way, having created your <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>>, you should publish it as a `@Bean` to override the defaults:
  747. ====
  748. .Java
  749. [source,java,role="primary"]
  750. ----
  751. @Bean
  752. OpaqueTokenIntrospector introspector() {
  753. return new UserInfoOpaqueTokenIntrospector(...);
  754. }
  755. ----
  756. .Kotlin
  757. [source,kotlin,role="secondary"]
  758. ----
  759. @Bean
  760. fun introspector(): OpaqueTokenIntrospector {
  761. return UserInfoOpaqueTokenIntrospector(...)
  762. }
  763. ----
  764. ====