opaque-token.adoc 33 KB

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