opaque-token.adoc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. 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 an <<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. If the application doesn't expose an `OpaqueTokenAuthenticationConverter` bean, then spring-security will build `BearerTokenAuthentication`.
  242. Or, if you're not using Spring Boot at all, then all of these components - the filter chain, an <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> and an `OpaqueTokenAuthenticationConverter` can be specified in XML.
  243. The filter chain is specified like so:
  244. .Default Opaque Token Configuration
  245. ====
  246. .Xml
  247. [source,xml,role="primary"]
  248. ----
  249. <http>
  250. <intercept-uri pattern="/**" access="authenticated"/>
  251. <oauth2-resource-server>
  252. <opaque-token introspector-ref="opaqueTokenIntrospector"/>
  253. </oauth2-resource-server>
  254. </http>
  255. ----
  256. ====
  257. And the <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> like so:
  258. .Opaque Token Introspector
  259. ====
  260. .Xml
  261. [source,xml,role="primary"]
  262. ----
  263. <bean id="opaqueTokenIntrospector"
  264. class="org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector">
  265. <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.introspection_uri}"/>
  266. <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.client_id}"/>
  267. <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.client_secret}"/>
  268. </bean>
  269. ----
  270. ====
  271. [[oauth2resourceserver-opaque-introspectionuri-dsl]]
  272. === Using `introspectionUri()`
  273. An authorization server's Introspection Uri can be configured <<oauth2resourceserver-opaque-introspectionuri,as a configuration property>> or it can be supplied in the DSL:
  274. .Introspection URI Configuration
  275. ====
  276. .Java
  277. [source,java,role="primary"]
  278. ----
  279. @EnableWebSecurity
  280. public class DirectlyConfiguredIntrospectionUri {
  281. @Bean
  282. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  283. http
  284. .authorizeHttpRequests(authorize -> authorize
  285. .anyRequest().authenticated()
  286. )
  287. .oauth2ResourceServer(oauth2 -> oauth2
  288. .opaqueToken(opaqueToken -> opaqueToken
  289. .introspectionUri("https://idp.example.com/introspect")
  290. .introspectionClientCredentials("client", "secret")
  291. )
  292. );
  293. return http.build();
  294. }
  295. }
  296. ----
  297. .Kotlin
  298. [source,kotlin,role="secondary"]
  299. ----
  300. @EnableWebSecurity
  301. class DirectlyConfiguredIntrospectionUri {
  302. @Bean
  303. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  304. http {
  305. authorizeRequests {
  306. authorize(anyRequest, authenticated)
  307. }
  308. oauth2ResourceServer {
  309. opaqueToken {
  310. introspectionUri = "https://idp.example.com/introspect"
  311. introspectionClientCredentials("client", "secret")
  312. }
  313. }
  314. }
  315. return http.build()
  316. }
  317. }
  318. ----
  319. .Xml
  320. [source,xml,role="secondary"]
  321. ----
  322. <bean id="opaqueTokenIntrospector"
  323. class="org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector">
  324. <constructor-arg value="https://idp.example.com/introspect"/>
  325. <constructor-arg value="client"/>
  326. <constructor-arg value="secret"/>
  327. </bean>
  328. ----
  329. ====
  330. Using `introspectionUri()` takes precedence over any configuration property.
  331. [[oauth2resourceserver-opaque-introspector-dsl]]
  332. === Using `introspector()`
  333. More powerful than `introspectionUri()` is `introspector()`, which will completely replace any Boot auto configuration of <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>>:
  334. .Introspector Configuration
  335. ====
  336. .Java
  337. [source,java,role="primary"]
  338. ----
  339. @EnableWebSecurity
  340. public class DirectlyConfiguredIntrospector {
  341. @Bean
  342. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  343. http
  344. .authorizeHttpRequests(authorize -> authorize
  345. .anyRequest().authenticated()
  346. )
  347. .oauth2ResourceServer(oauth2 -> oauth2
  348. .opaqueToken(opaqueToken -> opaqueToken
  349. .introspector(myCustomIntrospector())
  350. )
  351. );
  352. return http.build();
  353. }
  354. }
  355. ----
  356. .Kotlin
  357. [source,kotlin,role="secondary"]
  358. ----
  359. @EnableWebSecurity
  360. class DirectlyConfiguredIntrospector {
  361. @Bean
  362. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  363. http {
  364. authorizeRequests {
  365. authorize(anyRequest, authenticated)
  366. }
  367. oauth2ResourceServer {
  368. opaqueToken {
  369. introspector = myCustomIntrospector()
  370. }
  371. }
  372. }
  373. return http.build()
  374. }
  375. }
  376. ----
  377. .Xml
  378. [source,xml,role="secondary"]
  379. ----
  380. <http>
  381. <intercept-uri pattern="/**" access="authenticated"/>
  382. <oauth2-resource-server>
  383. <opaque-token introspector-ref="myCustomIntrospector"/>
  384. </oauth2-resource-server>
  385. </http>
  386. ----
  387. ====
  388. 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.
  389. [[oauth2resourceserver-opaque-introspector-bean]]
  390. === Exposing a `OpaqueTokenIntrospector` `@Bean`
  391. Or, exposing a <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> `@Bean` has the same effect as `introspector()`:
  392. [source,java]
  393. ----
  394. @Bean
  395. public OpaqueTokenIntrospector introspector() {
  396. return new NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  397. }
  398. ----
  399. [[oauth2resourceserver-opaque-authorization]]
  400. == Configuring Authorization
  401. An OAuth 2.0 Introspection endpoint will typically return a `scope` attribute, indicating the scopes (or authorities) it's been granted, for example:
  402. `{ ..., "scope" : "messages contacts"}`
  403. 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_".
  404. This means that to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix:
  405. .Authorization Opaque Token Configuration
  406. ====
  407. .Java
  408. [source,java,role="primary"]
  409. ----
  410. @EnableWebSecurity
  411. public class MappedAuthorities {
  412. @Bean
  413. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  414. http
  415. .authorizeHttpRequests(authorizeRequests -> authorizeRequests
  416. .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  417. .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
  418. .anyRequest().authenticated()
  419. )
  420. .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
  421. return http.build();
  422. }
  423. }
  424. ----
  425. .Kotlin
  426. [source,kotlin,role="secondary"]
  427. ----
  428. @EnableWebSecurity
  429. class MappedAuthorities {
  430. @Bean
  431. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  432. http {
  433. authorizeRequests {
  434. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  435. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  436. authorize(anyRequest, authenticated)
  437. }
  438. oauth2ResourceServer {
  439. opaqueToken { }
  440. }
  441. }
  442. return http.build()
  443. }
  444. }
  445. ----
  446. .Xml
  447. [source,xml,role="secondary"]
  448. ----
  449. <http>
  450. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  451. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  452. <oauth2-resource-server>
  453. <opaque-token introspector-ref="opaqueTokenIntrospector"/>
  454. </oauth2-resource-server>
  455. </http>
  456. ----
  457. ====
  458. Or similarly with method security:
  459. ====
  460. .Java
  461. [source,java,role="primary"]
  462. ----
  463. @PreAuthorize("hasAuthority('SCOPE_messages')")
  464. public List<Message> getMessages(...) {}
  465. ----
  466. .Kotlin
  467. [source,kotlin,role="secondary"]
  468. ----
  469. @PreAuthorize("hasAuthority('SCOPE_messages')")
  470. fun getMessages(): List<Message?> {}
  471. ----
  472. ====
  473. [[oauth2resourceserver-opaque-authorization-extraction]]
  474. === Extracting Authorities Manually
  475. By default, Opaque Token support will extract the scope claim from an introspection response and parse it into individual `GrantedAuthority` instances.
  476. For example, if the introspection response were:
  477. [source,json]
  478. ----
  479. {
  480. "active" : true,
  481. "scope" : "message:read message:write"
  482. }
  483. ----
  484. Then Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`.
  485. 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:
  486. ====
  487. .Java
  488. [source,java,role="primary"]
  489. ----
  490. public class CustomAuthoritiesOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  491. private OpaqueTokenIntrospector delegate =
  492. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  493. public OAuth2AuthenticatedPrincipal introspect(String token) {
  494. OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token);
  495. return new DefaultOAuth2AuthenticatedPrincipal(
  496. principal.getName(), principal.getAttributes(), extractAuthorities(principal));
  497. }
  498. private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
  499. List<String> scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE);
  500. return scopes.stream()
  501. .map(SimpleGrantedAuthority::new)
  502. .collect(Collectors.toList());
  503. }
  504. }
  505. ----
  506. .Kotlin
  507. [source,kotlin,role="secondary"]
  508. ----
  509. class CustomAuthoritiesOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  510. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  511. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  512. val principal: OAuth2AuthenticatedPrincipal = delegate.introspect(token)
  513. return DefaultOAuth2AuthenticatedPrincipal(
  514. principal.name, principal.attributes, extractAuthorities(principal))
  515. }
  516. private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
  517. val scopes: List<String> = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE)
  518. return scopes
  519. .map { SimpleGrantedAuthority(it) }
  520. }
  521. }
  522. ----
  523. ====
  524. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  525. ====
  526. .Java
  527. [source,java,role="primary"]
  528. ----
  529. @Bean
  530. public OpaqueTokenIntrospector introspector() {
  531. return new CustomAuthoritiesOpaqueTokenIntrospector();
  532. }
  533. ----
  534. .Kotlin
  535. [source,kotlin,role="secondary"]
  536. ----
  537. @Bean
  538. fun introspector(): OpaqueTokenIntrospector {
  539. return CustomAuthoritiesOpaqueTokenIntrospector()
  540. }
  541. ----
  542. ====
  543. [[oauth2resourceserver-opaque-timeouts]]
  544. == Configuring Timeouts
  545. By default, Resource Server uses connection and socket timeouts of 30 seconds each for coordinating with the authorization server.
  546. This may be too short in some scenarios.
  547. Further, it doesn't take into account more sophisticated patterns like back-off and discovery.
  548. To adjust the way in which Resource Server connects to the authorization server, `NimbusOpaqueTokenIntrospector` accepts an instance of `RestOperations`:
  549. ====
  550. .Java
  551. [source,java,role="primary"]
  552. ----
  553. @Bean
  554. public OpaqueTokenIntrospector introspector(RestTemplateBuilder builder, OAuth2ResourceServerProperties properties) {
  555. RestOperations rest = builder
  556. .basicAuthentication(properties.getOpaquetoken().getClientId(), properties.getOpaquetoken().getClientSecret())
  557. .setConnectTimeout(Duration.ofSeconds(60))
  558. .setReadTimeout(Duration.ofSeconds(60))
  559. .build();
  560. return new NimbusOpaqueTokenIntrospector(introspectionUri, rest);
  561. }
  562. ----
  563. .Kotlin
  564. [source,kotlin,role="secondary"]
  565. ----
  566. @Bean
  567. fun introspector(builder: RestTemplateBuilder, properties: OAuth2ResourceServerProperties): OpaqueTokenIntrospector? {
  568. val rest: RestOperations = builder
  569. .basicAuthentication(properties.opaquetoken.clientId, properties.opaquetoken.clientSecret)
  570. .setConnectTimeout(Duration.ofSeconds(60))
  571. .setReadTimeout(Duration.ofSeconds(60))
  572. .build()
  573. return NimbusOpaqueTokenIntrospector(introspectionUri, rest)
  574. }
  575. ----
  576. ====
  577. [[oauth2resourceserver-opaque-jwt-introspector]]
  578. == Using Introspection with JWTs
  579. A common question is whether or not introspection is compatible with JWTs.
  580. 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.
  581. 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.
  582. Even though you are using the JWT format for the token, your validation method is introspection, meaning you'd want to do:
  583. [source,yaml]
  584. ----
  585. spring:
  586. security:
  587. oauth2:
  588. resourceserver:
  589. opaque-token:
  590. introspection-uri: https://idp.example.org/introspection
  591. client-id: client
  592. client-secret: secret
  593. ----
  594. In this case, the resulting `Authentication` would be `BearerTokenAuthentication`.
  595. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint.
  596. But, let's say that, oddly enough, the introspection endpoint only returns whether or not the token is active.
  597. Now what?
  598. 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:
  599. ====
  600. .Java
  601. [source,java,role="primary"]
  602. ----
  603. public class JwtOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  604. private OpaqueTokenIntrospector delegate =
  605. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  606. private JwtDecoder jwtDecoder = new NimbusJwtDecoder(new ParseOnlyJWTProcessor());
  607. public OAuth2AuthenticatedPrincipal introspect(String token) {
  608. OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token);
  609. try {
  610. Jwt jwt = this.jwtDecoder.decode(token);
  611. return new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES);
  612. } catch (JwtException ex) {
  613. throw new OAuth2IntrospectionException(ex);
  614. }
  615. }
  616. private static class ParseOnlyJWTProcessor extends DefaultJWTProcessor<SecurityContext> {
  617. JWTClaimsSet process(SignedJWT jwt, SecurityContext context)
  618. throws JOSEException {
  619. return jwt.getJWTClaimsSet();
  620. }
  621. }
  622. }
  623. ----
  624. .Kotlin
  625. [source,kotlin,role="secondary"]
  626. ----
  627. class JwtOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  628. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  629. private val jwtDecoder: JwtDecoder = NimbusJwtDecoder(ParseOnlyJWTProcessor())
  630. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  631. val principal = delegate.introspect(token)
  632. return try {
  633. val jwt: Jwt = jwtDecoder.decode(token)
  634. DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES)
  635. } catch (ex: JwtException) {
  636. throw OAuth2IntrospectionException(ex.message)
  637. }
  638. }
  639. private class ParseOnlyJWTProcessor : DefaultJWTProcessor<SecurityContext>() {
  640. override fun process(jwt: SignedJWT, context: SecurityContext): JWTClaimsSet {
  641. return jwt.jwtClaimsSet
  642. }
  643. }
  644. }
  645. ----
  646. ====
  647. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  648. ====
  649. .Java
  650. [source,java,role="primary"]
  651. ----
  652. @Bean
  653. public OpaqueTokenIntrospector introspector() {
  654. return new JwtOpaqueTokenIntrospector();
  655. }
  656. ----
  657. .Kotlin
  658. [source,kotlin,role="secondary"]
  659. ----
  660. @Bean
  661. fun introspector(): OpaqueTokenIntrospector {
  662. return JwtOpaqueTokenIntrospector()
  663. }
  664. ----
  665. ====
  666. [[oauth2resourceserver-opaque-userinfo]]
  667. == Calling a `/userinfo` Endpoint
  668. Generally speaking, a Resource Server doesn't care about the underlying user, but instead about the authorities that have been granted.
  669. That said, at times it can be valuable to tie the authorization statement back to a user.
  670. 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`>>.
  671. This implementation below does three things:
  672. * Delegates to the introspection endpoint, to affirm the token's validity
  673. * Looks up the appropriate client registration associated with the `/userinfo` endpoint
  674. * Invokes and returns the response from the `/userinfo` endpoint
  675. ====
  676. .Java
  677. [source,java,role="primary"]
  678. ----
  679. public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  680. private final OpaqueTokenIntrospector delegate =
  681. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  682. private final OAuth2UserService oauth2UserService = new DefaultOAuth2UserService();
  683. private final ClientRegistrationRepository repository;
  684. // ... constructor
  685. @Override
  686. public OAuth2AuthenticatedPrincipal introspect(String token) {
  687. OAuth2AuthenticatedPrincipal authorized = this.delegate.introspect(token);
  688. Instant issuedAt = authorized.getAttribute(ISSUED_AT);
  689. Instant expiresAt = authorized.getAttribute(EXPIRES_AT);
  690. ClientRegistration clientRegistration = this.repository.findByRegistrationId("registration-id");
  691. OAuth2AccessToken token = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
  692. OAuth2UserRequest oauth2UserRequest = new OAuth2UserRequest(clientRegistration, token);
  693. return this.oauth2UserService.loadUser(oauth2UserRequest);
  694. }
  695. }
  696. ----
  697. .Kotlin
  698. [source,kotlin,role="secondary"]
  699. ----
  700. class UserInfoOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  701. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  702. private val oauth2UserService = DefaultOAuth2UserService()
  703. private val repository: ClientRegistrationRepository? = null
  704. // ... constructor
  705. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  706. val authorized = delegate.introspect(token)
  707. val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
  708. val expiresAt: Instant? = authorized.getAttribute(EXPIRES_AT)
  709. val clientRegistration: ClientRegistration = repository!!.findByRegistrationId("registration-id")
  710. val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
  711. val oauth2UserRequest = OAuth2UserRequest(clientRegistration, accessToken)
  712. return oauth2UserService.loadUser(oauth2UserRequest)
  713. }
  714. }
  715. ----
  716. ====
  717. If you aren't using `spring-security-oauth2-client`, it's still quite simple.
  718. You will simply need to invoke the `/userinfo` with your own instance of `WebClient`:
  719. ====
  720. .Java
  721. [source,java,role="primary"]
  722. ----
  723. public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  724. private final OpaqueTokenIntrospector delegate =
  725. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  726. private final WebClient rest = WebClient.create();
  727. @Override
  728. public OAuth2AuthenticatedPrincipal introspect(String token) {
  729. OAuth2AuthenticatedPrincipal authorized = this.delegate.introspect(token);
  730. return makeUserInfoRequest(authorized);
  731. }
  732. }
  733. ----
  734. .Kotlin
  735. [source,kotlin,role="secondary"]
  736. ----
  737. class UserInfoOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  738. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  739. private val rest: WebClient = WebClient.create()
  740. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  741. val authorized = delegate.introspect(token)
  742. return makeUserInfoRequest(authorized)
  743. }
  744. }
  745. ----
  746. ====
  747. Either way, having created your <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>>, you should publish it as a `@Bean` to override the defaults:
  748. ====
  749. .Java
  750. [source,java,role="primary"]
  751. ----
  752. @Bean
  753. OpaqueTokenIntrospector introspector() {
  754. return new UserInfoOpaqueTokenIntrospector(...);
  755. }
  756. ----
  757. .Kotlin
  758. [source,kotlin,role="secondary"]
  759. ----
  760. @Bean
  761. fun introspector(): OpaqueTokenIntrospector {
  762. return UserInfoOpaqueTokenIntrospector(...)
  763. }
  764. ----
  765. ====