opaque-token.adoc 32 KB

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