opaque-token.adoc 34 KB

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