authentication.adoc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. [[servlet-saml2login-authenticate-responses]]
  2. = Authenticating ``<saml2:Response>``s
  3. To verify SAML 2.0 Responses, Spring Security uses xref:servlet/saml2/login/overview.adoc#servlet-saml2login-authentication-saml2authenticationtokenconverter[`Saml2AuthenticationTokenConverter`] to populate the `Authentication` request and xref:servlet/saml2/login/overview.adoc#servlet-saml2login-architecture[`OpenSaml4AuthenticationProvider`] to authenticate it.
  4. You can configure this in a number of ways including:
  5. 1. Changing the way the `RelyingPartyRegistration` is Looked Up
  6. 2. Setting a clock skew to timestamp validation
  7. 3. Mapping the response to a list of `GrantedAuthority` instances
  8. 4. Customizing the strategy for validating assertions
  9. 5. Customizing the strategy for decrypting response and assertion elements
  10. To configure these, you'll use the `saml2Login#authenticationManager` method in the DSL.
  11. [[saml2-response-processing-endpoint]]
  12. == Changing the SAML Response Processing Endpoint
  13. The default endpoint is `+/login/saml2/sso/{registrationId}+`.
  14. You can change this in the DSL and in the associated metadata like so:
  15. [tabs]
  16. ======
  17. Java::
  18. +
  19. [source,java,role="primary"]
  20. ----
  21. @Bean
  22. SecurityFilterChain securityFilters(HttpSecurity http) throws Exception {
  23. http
  24. // ...
  25. .saml2Login((saml2) -> saml2.loginProcessingUrl("/saml2/login/sso"))
  26. // ...
  27. return http.build();
  28. }
  29. ----
  30. Kotlin::
  31. +
  32. [source,kotlin,role="secondary"]
  33. ----
  34. @Bean
  35. fun securityFilters(val http: HttpSecurity): SecurityFilterChain {
  36. http {
  37. // ...
  38. .saml2Login {
  39. loginProcessingUrl = "/saml2/login/sso"
  40. }
  41. // ...
  42. }
  43. return http.build()
  44. }
  45. ----
  46. ======
  47. and:
  48. [tabs]
  49. ======
  50. Java::
  51. +
  52. [source,java,role="primary"]
  53. ----
  54. relyingPartyRegistrationBuilder.assertionConsumerServiceLocation("/saml/SSO")
  55. ----
  56. Kotlin::
  57. +
  58. [source,kotlin,role="secondary"]
  59. ----
  60. relyingPartyRegistrationBuilder.assertionConsumerServiceLocation("/saml/SSO")
  61. ----
  62. ======
  63. [[relyingpartyregistrationresolver-apply]]
  64. == Changing `RelyingPartyRegistration` lookup
  65. By default, this converter will match against any associated `<saml2:AuthnRequest>` or any `registrationId` it finds in the URL.
  66. Or, if it cannot find one in either of those cases, then it attempts to look it up by the `<saml2:Response#Issuer>` element.
  67. There are a number of circumstances where you might need something more sophisticated, like if you are supporting `ARTIFACT` binding.
  68. In those cases, you can customize lookup through a custom `AuthenticationConverter`, which you can customize like so:
  69. [tabs]
  70. ======
  71. Java::
  72. +
  73. [source,java,role="primary"]
  74. ----
  75. @Bean
  76. SecurityFilterChain securityFilters(HttpSecurity http, AuthenticationConverter authenticationConverter) throws Exception {
  77. http
  78. // ...
  79. .saml2Login((saml2) -> saml2.authenticationConverter(authenticationConverter))
  80. // ...
  81. return http.build();
  82. }
  83. ----
  84. Kotlin::
  85. +
  86. [source,kotlin,role="secondary"]
  87. ----
  88. @Bean
  89. fun securityFilters(val http: HttpSecurity, val converter: AuthenticationConverter): SecurityFilterChain {
  90. http {
  91. // ...
  92. .saml2Login {
  93. authenticationConverter = converter
  94. }
  95. // ...
  96. }
  97. return http.build()
  98. }
  99. ----
  100. ======
  101. [[servlet-saml2login-opensamlauthenticationprovider-clockskew]]
  102. == Setting a Clock Skew
  103. It's not uncommon for the asserting and relying parties to have system clocks that aren't perfectly synchronized.
  104. For that reason, you can configure ``OpenSaml4AuthenticationProvider``'s default assertion validator with some tolerance:
  105. [tabs]
  106. ======
  107. Java::
  108. +
  109. [source,java,role="primary"]
  110. ----
  111. @Configuration
  112. @EnableWebSecurity
  113. public class SecurityConfig {
  114. @Bean
  115. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  116. OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
  117. authenticationProvider.setAssertionValidator(OpenSaml4AuthenticationProvider
  118. .createDefaultAssertionValidatorWithParameters(assertionToken -> {
  119. Map<String, Object> params = new HashMap<>();
  120. params.put(CLOCK_SKEW, Duration.ofMinutes(10).toMillis());
  121. // ... other validation parameters
  122. return new ValidationContext(params);
  123. })
  124. );
  125. http
  126. .authorizeHttpRequests(authz -> authz
  127. .anyRequest().authenticated()
  128. )
  129. .saml2Login(saml2 -> saml2
  130. .authenticationManager(new ProviderManager(authenticationProvider))
  131. );
  132. return http.build();
  133. }
  134. }
  135. ----
  136. Kotlin::
  137. +
  138. [source,kotlin,role="secondary"]
  139. ----
  140. @Configuration
  141. @EnableWebSecurity
  142. open class SecurityConfig {
  143. @Bean
  144. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  145. val authenticationProvider = OpenSaml4AuthenticationProvider()
  146. authenticationProvider.setAssertionValidator(
  147. OpenSaml4AuthenticationProvider
  148. .createDefaultAssertionValidatorWithParameters(Converter<OpenSaml4AuthenticationProvider.AssertionToken, ValidationContext> {
  149. val params: MutableMap<String, Any> = HashMap()
  150. params[CLOCK_SKEW] =
  151. Duration.ofMinutes(10).toMillis()
  152. ValidationContext(params)
  153. })
  154. )
  155. http {
  156. authorizeRequests {
  157. authorize(anyRequest, authenticated)
  158. }
  159. saml2Login {
  160. authenticationManager = ProviderManager(authenticationProvider)
  161. }
  162. }
  163. return http.build()
  164. }
  165. }
  166. ----
  167. ======
  168. If you are using xref:servlet/saml2/opensaml.adoc[OpenSAML 5], then we have a simpler way, using `OpenSaml5AuthenticationProvider.AssertionValidator`:
  169. [tabs]
  170. ======
  171. Java::
  172. +
  173. [source,java,role="primary"]
  174. ----
  175. @Configuration
  176. @EnableWebSecurity
  177. public class SecurityConfig {
  178. @Bean
  179. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  180. OpenSaml5AuthenticationProvider authenticationProvider = new OpenSaml5AuthenticationProvider();
  181. AssertionValidator assertionValidator = AssertionValidator.builder()
  182. .clockSkew(Duration.ofMinutes(10)).build();
  183. authenticationProvider.setAssertionValidator(assertionValidator);
  184. http
  185. .authorizeHttpRequests(authz -> authz
  186. .anyRequest().authenticated()
  187. )
  188. .saml2Login(saml2 -> saml2
  189. .authenticationManager(new ProviderManager(authenticationProvider))
  190. );
  191. return http.build();
  192. }
  193. }
  194. ----
  195. Kotlin::
  196. +
  197. [source,kotlin,role="secondary"]
  198. ----
  199. @Configuration @EnableWebSecurity
  200. class SecurityConfig {
  201. @Bean
  202. @Throws(Exception::class)
  203. fun filterChain(http: HttpSecurity): SecurityFilterChain {
  204. val authenticationProvider = OpenSaml5AuthenticationProvider()
  205. val assertionValidator = AssertionValidator.builder().clockSkew(Duration.ofMinutes(10)).build()
  206. authenticationProvider.setAssertionValidator(assertionValidator)
  207. http {
  208. authorizeHttpRequests {
  209. authorize(anyRequest, authenticated)
  210. }
  211. saml2Login {
  212. authenticationManager = ProviderManager(authenticationProvider)
  213. }
  214. }
  215. return http.build()
  216. }
  217. }
  218. ----
  219. ======
  220. == Converting an `Assertion` into an `Authentication`
  221. `OpenSamlXAuthenticationProvider#setResponseAuthenticationConverter` provides a way for you to change how it converts your assertion into an `Authentication` instance.
  222. You can set a custom converter in the following way:
  223. [tabs]
  224. ======
  225. Java::
  226. +
  227. [source,java,role="primary"]
  228. ----
  229. @Configuration
  230. @EnableWebSecurity
  231. public class SecurityConfig {
  232. @Autowired
  233. Converter<ResponseToken, Saml2Authentication> authenticationConverter;
  234. @Bean
  235. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  236. OpenSaml5AuthenticationProvider authenticationProvider = new OpenSaml5AuthenticationProvider();
  237. authenticationProvider.setResponseAuthenticationConverter(this.authenticationConverter);
  238. http
  239. .authorizeHttpRequests((authz) -> authz
  240. .anyRequest().authenticated())
  241. .saml2Login((saml2) -> saml2
  242. .authenticationManager(new ProviderManager(authenticationProvider))
  243. );
  244. return http.build();
  245. }
  246. }
  247. ----
  248. Kotlin::
  249. +
  250. [source,kotlin,role="secondary"]
  251. ----
  252. @Configuration
  253. @EnableWebSecurity
  254. open class SecurityConfig {
  255. @Autowired
  256. var authenticationConverter: Converter<ResponseToken, Saml2Authentication>? = null
  257. @Bean
  258. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  259. val authenticationProvider = OpenSaml5AuthenticationProvider()
  260. authenticationProvider.setResponseAuthenticationConverter(this.authenticationConverter)
  261. http {
  262. authorizeRequests {
  263. authorize(anyRequest, authenticated)
  264. }
  265. saml2Login {
  266. authenticationManager = ProviderManager(authenticationProvider)
  267. }
  268. }
  269. return http.build()
  270. }
  271. }
  272. ----
  273. ======
  274. The ensuing examples all build off of this common construct to show you different ways this converter comes in handy.
  275. [[servlet-saml2login-opensamlauthenticationprovider-userdetailsservice]]
  276. == Coordinating with a `UserDetailsService`
  277. Or, perhaps you would like to include user details from a legacy `UserDetailsService`.
  278. In that case, the response authentication converter can come in handy, as can be seen below:
  279. [tabs]
  280. ======
  281. Java::
  282. +
  283. [source,java,role="primary"]
  284. ----
  285. @Component
  286. class MyUserDetailsResponseAuthenticationConverter implements Converter<ResponseToken, Saml2Authentication> {
  287. private final ResponseAuthenticationConverter delegate = new ResponseAuthenticationConverter();
  288. private final UserDetailsService userDetailsService;
  289. MyUserDetailsResponseAuthenticationConverter(UserDetailsService userDetailsService) {
  290. this.userDetailsService = userDetailsService;
  291. }
  292. @Override
  293. public Saml2Authentication convert(ResponseToken responseToken) {
  294. Saml2Authentication authentication = this.delegate.convert(responseToken); <1>
  295. UserDetails principal = this.userDetailsService.loadByUsername(username); <2>
  296. String saml2Response = authentication.getSaml2Response();
  297. Collection<GrantedAuthority> authorities = principal.getAuthorities();
  298. return new Saml2Authentication((AuthenticatedPrincipal) userDetails, saml2Response, authorities); <3>
  299. }
  300. }
  301. ----
  302. Kotlin::
  303. +
  304. [source,kotlin,role="secondary"]
  305. ----
  306. @Component
  307. open class MyUserDetailsResponseAuthenticationConverter(val delegate: ResponseAuthenticationConverter,
  308. UserDetailsService userDetailsService): Converter<ResponseToken, Saml2Authentication> {
  309. @Override
  310. open fun convert(responseToken: ResponseToken): Saml2Authentication {
  311. val authentication = this.delegate.convert(responseToken) <1>
  312. val principal = this.userDetailsService.loadByUsername(username) <2>
  313. val saml2Response = authentication.getSaml2Response()
  314. val authorities = principal.getAuthorities()
  315. return Saml2Authentication(userDetails as AuthenticatedPrincipal, saml2Response, authorities) <3>
  316. }
  317. }
  318. ----
  319. ======
  320. <1> First, call the default converter, which extracts attributes and authorities from the response
  321. <2> Second, call the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`] using the relevant information
  322. <3> Third, return an authentication that includes the user details
  323. [TIP]
  324. ====
  325. If your `UserDetailsService` returns a value that also implements `AuthenticatedPrincipal`, then you don't need a custom authentication implementation.
  326. ====
  327. Or, if you are using OpenSaml 4, then you can achieve something similar as follows:
  328. [tabs]
  329. ======
  330. Java::
  331. +
  332. [source,java,role="primary"]
  333. ----
  334. @Configuration
  335. @EnableWebSecurity
  336. public class SecurityConfig {
  337. @Autowired
  338. UserDetailsService userDetailsService;
  339. @Bean
  340. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  341. OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
  342. authenticationProvider.setResponseAuthenticationConverter(responseToken -> {
  343. Saml2Authentication authentication = OpenSaml4AuthenticationProvider
  344. .createDefaultResponseAuthenticationConverter() <1>
  345. .convert(responseToken);
  346. Assertion assertion = responseToken.getResponse().getAssertions().get(0);
  347. String username = assertion.getSubject().getNameID().getValue();
  348. UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); <2>
  349. return MySaml2Authentication(userDetails, authentication); <3>
  350. });
  351. http
  352. .authorizeHttpRequests(authz -> authz
  353. .anyRequest().authenticated()
  354. )
  355. .saml2Login(saml2 -> saml2
  356. .authenticationManager(new ProviderManager(authenticationProvider))
  357. );
  358. return http.build();
  359. }
  360. }
  361. ----
  362. Kotlin::
  363. +
  364. [source,kotlin,role="secondary"]
  365. ----
  366. @Configuration
  367. @EnableWebSecurity
  368. open class SecurityConfig {
  369. @Autowired
  370. var userDetailsService: UserDetailsService? = null
  371. @Bean
  372. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  373. val authenticationProvider = OpenSaml4AuthenticationProvider()
  374. authenticationProvider.setResponseAuthenticationConverter { responseToken: OpenSaml4AuthenticationProvider.ResponseToken ->
  375. val authentication = OpenSaml4AuthenticationProvider
  376. .createDefaultResponseAuthenticationConverter() <1>
  377. .convert(responseToken)
  378. val assertion: Assertion = responseToken.response.assertions[0]
  379. val username: String = assertion.subject.nameID.value
  380. val userDetails = userDetailsService!!.loadUserByUsername(username) <2>
  381. MySaml2Authentication(userDetails, authentication) <3>
  382. }
  383. http {
  384. authorizeRequests {
  385. authorize(anyRequest, authenticated)
  386. }
  387. saml2Login {
  388. authenticationManager = ProviderManager(authenticationProvider)
  389. }
  390. }
  391. return http.build()
  392. }
  393. }
  394. ----
  395. ======
  396. <1> First, call the default converter, which extracts attributes and authorities from the response
  397. <2> Second, call the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`] using the relevant information
  398. <3> Third, return a custom authentication that includes the user details
  399. [NOTE]
  400. It's not required to call ``OpenSaml4AuthenticationProvider``'s default authentication converter.
  401. It returns a `Saml2AuthenticatedPrincipal` containing the attributes it extracted from ``AttributeStatement``s as well as the single `ROLE_USER` authority.
  402. === Configuring the Principal Name
  403. Sometimes, the principal name is not in the `<saml2:NameID>` element.
  404. In that case, you can configure the `ResponseAuthenticationConverter` with a custom strategy like so:
  405. [tabs]
  406. ======
  407. Java::
  408. +
  409. [source,java,role="primary"]
  410. ----
  411. @Bean
  412. ResponseAuthenticationConverter authenticationConverter() {
  413. ResponseAuthenticationConverter authenticationConverter = new ResponseAuthenticationConverter();
  414. authenticationConverter.setPrincipalNameConverter((assertion) -> {
  415. // ... work with OpenSAML's Assertion object to extract the principal
  416. });
  417. return authenticationConverter;
  418. }
  419. ----
  420. Kotlin::
  421. +
  422. [source,kotlin,role="secondary"]
  423. ----
  424. @Bean
  425. fun authenticationConverter(): ResponseAuthenticationConverter {
  426. val authenticationConverter: ResponseAuthenticationConverter = ResponseAuthenticationConverter()
  427. authenticationConverter.setPrincipalNameConverter { assertion ->
  428. // ... work with OpenSAML's Assertion object to extract the principal
  429. }
  430. return authenticationConverter
  431. }
  432. ----
  433. ======
  434. === Configuring a Principal's Granted Authorities
  435. Spring Security automatically grants `ROLE_USER` when using `OpenSamlXAuhenticationProvider`.
  436. With `OpenSaml5AuthenticationProvider`, you can configure a different set of granted authorities like so:
  437. [tabs]
  438. ======
  439. Java::
  440. +
  441. [source,java,role="primary"]
  442. ----
  443. @Bean
  444. ResponseAuthenticationConverter authenticationConverter() {
  445. ResponseAuthenticationConverter authenticationConverter = new ResponseAuthenticationConverter();
  446. authenticationConverter.setPrincipalNameConverter((assertion) -> {
  447. // ... grant the needed authorities based on attributes in the assertion
  448. });
  449. return authenticationConverter;
  450. }
  451. ----
  452. Kotlin::
  453. +
  454. [source,kotlin,role="secondary"]
  455. ----
  456. @Bean
  457. fun authenticationConverter(): ResponseAuthenticationConverter {
  458. val authenticationConverter = ResponseAuthenticationConverter()
  459. authenticationConverter.setPrincipalNameConverter{ assertion ->
  460. // ... grant the needed authorities based on attributes in the assertion
  461. }
  462. return authenticationConverter
  463. }
  464. ----
  465. ======
  466. [[servlet-saml2login-opensamlauthenticationprovider-additionalvalidation]]
  467. == Performing Additional Response Validation
  468. `OpenSaml4AuthenticationProvider` validates the `Issuer` and `Destination` values right after decrypting the `Response`.
  469. You can customize the validation by extending the default validator concatenating with your own response validator, or you can replace it entirely with yours.
  470. For example, you can throw a custom exception with any additional information available in the `Response` object, like so:
  471. [source,java]
  472. ----
  473. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  474. provider.setResponseValidator((responseToken) -> {
  475. Saml2ResponseValidatorResult result = OpenSaml4AuthenticationProvider
  476. .createDefaultResponseValidator()
  477. .convert(responseToken)
  478. .concat(myCustomValidator.convert(responseToken));
  479. if (!result.getErrors().isEmpty()) {
  480. String inResponseTo = responseToken.getInResponseTo();
  481. throw new CustomSaml2AuthenticationException(result, inResponseTo);
  482. }
  483. return result;
  484. });
  485. ----
  486. When using `OpenSaml5AuthenticationProvider`, you can do the same with less boilerplate:
  487. [source,java]
  488. ----
  489. OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
  490. ResponseValidator responseValidator = ResponseValidator.withDefaults(myCustomValidator);
  491. provider.setResponseValidator(responseValidator);
  492. ----
  493. You can also customize which validation steps Spring Security should do.
  494. For example, if you want to skip `Response#InResponseTo` validation, you can call ``ResponseValidator``'s constructor, excluding `InResponseToValidator` from the list:
  495. [source,java]
  496. ----
  497. OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
  498. ResponseValidator responseValidator = new ResponseValidator(new DestinationValidator(), new IssuerValidator());
  499. provider.setResponseValidator(responseValidator);
  500. ----
  501. [TIP]
  502. ====
  503. OpenSAML performs `Asssertion#InResponseTo` validation in its `BearerSubjectConfirmationValidator` class, which is configurable using <<_performing_additional_assertion_validation, setAssertionValidator>>.
  504. ====
  505. == Performing Additional Assertion Validation
  506. `OpenSaml4AuthenticationProvider` performs minimal validation on SAML 2.0 Assertions.
  507. After verifying the signature, it will:
  508. 1. Validate `<AudienceRestriction>` and `<DelegationRestriction>` conditions
  509. 2. Validate ``<SubjectConfirmation>``s, expect for any IP address information
  510. To perform additional validation, you can configure your own assertion validator that delegates to ``OpenSaml4AuthenticationProvider``'s default and then performs its own.
  511. [[servlet-saml2login-opensamlauthenticationprovider-onetimeuse]]
  512. For example, you can use OpenSAML's `OneTimeUseConditionValidator` to also validate a `<OneTimeUse>` condition, like so:
  513. [tabs]
  514. ======
  515. Java::
  516. +
  517. [source,java,role="primary"]
  518. ----
  519. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  520. OneTimeUseConditionValidator validator = ...;
  521. provider.setAssertionValidator(assertionToken -> {
  522. Saml2ResponseValidatorResult result = OpenSaml4AuthenticationProvider
  523. .createDefaultAssertionValidator()
  524. .convert(assertionToken);
  525. Assertion assertion = assertionToken.getAssertion();
  526. OneTimeUse oneTimeUse = assertion.getConditions().getOneTimeUse();
  527. ValidationContext context = new ValidationContext();
  528. try {
  529. if (validator.validate(oneTimeUse, assertion, context) = ValidationResult.VALID) {
  530. return result;
  531. }
  532. } catch (Exception e) {
  533. return result.concat(new Saml2Error(INVALID_ASSERTION, e.getMessage()));
  534. }
  535. return result.concat(new Saml2Error(INVALID_ASSERTION, context.getValidationFailureMessage()));
  536. });
  537. ----
  538. Kotlin::
  539. +
  540. [source,kotlin,role="secondary"]
  541. ----
  542. var provider = OpenSaml4AuthenticationProvider()
  543. var validator: OneTimeUseConditionValidator = ...
  544. provider.setAssertionValidator { assertionToken ->
  545. val result = OpenSaml4AuthenticationProvider
  546. .createDefaultAssertionValidator()
  547. .convert(assertionToken)
  548. val assertion: Assertion = assertionToken.assertion
  549. val oneTimeUse: OneTimeUse = assertion.conditions.oneTimeUse
  550. val context = ValidationContext()
  551. try {
  552. if (validator.validate(oneTimeUse, assertion, context) = ValidationResult.VALID) {
  553. return@setAssertionValidator result
  554. }
  555. } catch (e: Exception) {
  556. return@setAssertionValidator result.concat(Saml2Error(INVALID_ASSERTION, e.message))
  557. }
  558. result.concat(Saml2Error(INVALID_ASSERTION, context.validationFailureMessage))
  559. }
  560. ----
  561. ======
  562. [NOTE]
  563. While recommended, it's not necessary to call ``OpenSaml4AuthenticationProvider``'s default assertion validator.
  564. A circumstance where you would skip it would be if you don't need it to check the `<AudienceRestriction>` or the `<SubjectConfirmation>` since you are doing those yourself.
  565. If you are using xref:servlet/saml2/opensaml.adoc[OpenSAML 5], then we have a simpler way using `OpenSaml5AuthenticationProvider.AssertionValidator`:
  566. [tabs]
  567. ======
  568. Java::
  569. +
  570. [source,java,role="primary"]
  571. ----
  572. OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
  573. OneTimeUseConditionValidator validator = ...;
  574. AssertionValidator assertionValidator = AssertionValidator.builder()
  575. .conditionValidators((c) -> c.add(validator)).build();
  576. provider.setAssertionValidator(assertionValidator);
  577. ----
  578. Kotlin::
  579. +
  580. [source,kotlin,role="secondary"]
  581. ----
  582. val provider = OpenSaml5AuthenticationProvider()
  583. val validator: OneTimeUseConditionValidator = ...;
  584. val assertionValidator = AssertionValidator.builder()
  585. .conditionValidators { add(validator) }.build()
  586. provider.setAssertionValidator(assertionValidator)
  587. ----
  588. ======
  589. You can use this same builder to remove validators that you don't want to use like so:
  590. [tabs]
  591. ======
  592. Java::
  593. +
  594. [source,java,role="primary"]
  595. ----
  596. OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
  597. AssertionValidator assertionValidator = AssertionValidator.builder()
  598. .conditionValidators((c) -> c.removeIf(AudienceRestrictionValidator.class::isInstance)).build();
  599. provider.setAssertionValidator(assertionValidator);
  600. ----
  601. Kotlin::
  602. +
  603. [source,kotlin,role="secondary"]
  604. ----
  605. val provider = new OpenSaml5AuthenticationProvider()
  606. val assertionValidator = AssertionValidator.builder()
  607. .conditionValidators {
  608. c: List<ConditionValidator> -> c.removeIf { it is AudienceRestrictionValidator }
  609. }.build()
  610. provider.setAssertionValidator(assertionValidator)
  611. ----
  612. ======
  613. [[servlet-saml2login-opensamlauthenticationprovider-decryption]]
  614. == Customizing Decryption
  615. Spring Security decrypts `<saml2:EncryptedAssertion>`, `<saml2:EncryptedAttribute>`, and `<saml2:EncryptedID>` elements automatically by using the decryption xref:servlet/saml2/login/overview.adoc#servlet-saml2login-rpr-credentials[`Saml2X509Credential` instances] registered in the xref:servlet/saml2/login/overview.adoc#servlet-saml2login-relyingpartyregistration[`RelyingPartyRegistration`].
  616. `OpenSaml4AuthenticationProvider` exposes xref:servlet/saml2/login/overview.adoc#servlet-saml2login-architecture[two decryption strategies].
  617. The response decrypter is for decrypting encrypted elements of the `<saml2:Response>`, like `<saml2:EncryptedAssertion>`.
  618. The assertion decrypter is for decrypting encrypted elements of the `<saml2:Assertion>`, like `<saml2:EncryptedAttribute>` and `<saml2:EncryptedID>`.
  619. You can replace ``OpenSaml4AuthenticationProvider``'s default decryption strategy with your own.
  620. For example, if you have a separate service that decrypts the assertions in a `<saml2:Response>`, you can use it instead like so:
  621. [tabs]
  622. ======
  623. Java::
  624. +
  625. [source,java,role="primary"]
  626. ----
  627. MyDecryptionService decryptionService = ...;
  628. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  629. provider.setResponseElementsDecrypter((responseToken) -> decryptionService.decrypt(responseToken.getResponse()));
  630. ----
  631. Kotlin::
  632. +
  633. [source,kotlin,role="secondary"]
  634. ----
  635. val decryptionService: MyDecryptionService = ...
  636. val provider = OpenSaml4AuthenticationProvider()
  637. provider.setResponseElementsDecrypter { responseToken -> decryptionService.decrypt(responseToken.response) }
  638. ----
  639. ======
  640. If you are also decrypting individual elements in a `<saml2:Assertion>`, you can customize the assertion decrypter, too:
  641. [tabs]
  642. ======
  643. Java::
  644. +
  645. [source,java,role="primary"]
  646. ----
  647. provider.setAssertionElementsDecrypter((assertionToken) -> decryptionService.decrypt(assertionToken.getAssertion()));
  648. ----
  649. Kotlin::
  650. +
  651. [source,kotlin,role="secondary"]
  652. ----
  653. provider.setAssertionElementsDecrypter { assertionToken -> decryptionService.decrypt(assertionToken.assertion) }
  654. ----
  655. ======
  656. NOTE: There are two separate decrypters since assertions can be signed separately from responses.
  657. Trying to decrypt a signed assertion's elements before signature verification may invalidate the signature.
  658. If your asserting party signs the response only, then it's safe to decrypt all elements using only the response decrypter.
  659. [[servlet-saml2login-authenticationmanager-custom]]
  660. == Using a Custom Authentication Manager
  661. [[servlet-saml2login-opensamlauthenticationprovider-authenticationmanager]]
  662. Of course, the `authenticationManager` DSL method can be also used to perform a completely custom SAML 2.0 authentication.
  663. This authentication manager should expect a `Saml2AuthenticationToken` object containing the SAML 2.0 Response XML data.
  664. [tabs]
  665. ======
  666. Java::
  667. +
  668. [source,java,role="primary"]
  669. ----
  670. @Configuration
  671. @EnableWebSecurity
  672. public class SecurityConfig {
  673. @Bean
  674. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  675. AuthenticationManager authenticationManager = new MySaml2AuthenticationManager(...);
  676. http
  677. .authorizeHttpRequests(authorize -> authorize
  678. .anyRequest().authenticated()
  679. )
  680. .saml2Login(saml2 -> saml2
  681. .authenticationManager(authenticationManager)
  682. )
  683. ;
  684. return http.build();
  685. }
  686. }
  687. ----
  688. Kotlin::
  689. +
  690. [source,kotlin,role="secondary"]
  691. ----
  692. @Configuration
  693. @EnableWebSecurity
  694. open class SecurityConfig {
  695. @Bean
  696. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  697. val customAuthenticationManager: AuthenticationManager = MySaml2AuthenticationManager(...)
  698. http {
  699. authorizeRequests {
  700. authorize(anyRequest, authenticated)
  701. }
  702. saml2Login {
  703. authenticationManager = customAuthenticationManager
  704. }
  705. }
  706. return http.build()
  707. }
  708. }
  709. ----
  710. ======
  711. [[servlet-saml2login-authenticatedprincipal]]
  712. == Using `Saml2AuthenticatedPrincipal`
  713. With the relying party correctly configured for a given asserting party, it's ready to accept assertions.
  714. Once the relying party validates an assertion, the result is a `Saml2Authentication` with a `Saml2AuthenticatedPrincipal`.
  715. This means that you can access the principal in your controller like so:
  716. [tabs]
  717. ======
  718. Java::
  719. +
  720. [source,java,role="primary"]
  721. ----
  722. @Controller
  723. public class MainController {
  724. @GetMapping("/")
  725. public String index(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal, Model model) {
  726. String email = principal.getFirstAttribute("email");
  727. model.setAttribute("email", email);
  728. return "index";
  729. }
  730. }
  731. ----
  732. Kotlin::
  733. +
  734. [source,kotlin,role="secondary"]
  735. ----
  736. @Controller
  737. class MainController {
  738. @GetMapping("/")
  739. fun index(@AuthenticationPrincipal principal: Saml2AuthenticatedPrincipal, model: Model): String {
  740. val email = principal.getFirstAttribute<String>("email")
  741. model.setAttribute("email", email)
  742. return "index"
  743. }
  744. }
  745. ----
  746. ======
  747. [TIP]
  748. Because the SAML 2.0 specification allows for each attribute to have multiple values, you can either call `getAttribute` to get the list of attributes or `getFirstAttribute` to get the first in the list.
  749. `getFirstAttribute` is quite handy when you know that there is only one value.