opaque-token.adoc 32 KB

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