authentication.adoc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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. [[servlet-saml2login-opensamlauthenticationprovider-userdetailsservice]]
  221. == Coordinating with a `UserDetailsService`
  222. Or, perhaps you would like to include user details from a legacy `UserDetailsService`.
  223. In that case, the response authentication converter can come in handy, as can be seen below:
  224. [tabs]
  225. ======
  226. Java::
  227. +
  228. [source,java,role="primary"]
  229. ----
  230. @Configuration
  231. @EnableWebSecurity
  232. public class SecurityConfig {
  233. @Autowired
  234. UserDetailsService userDetailsService;
  235. @Bean
  236. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  237. OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
  238. authenticationProvider.setResponseAuthenticationConverter(responseToken -> {
  239. Saml2Authentication authentication = OpenSaml4AuthenticationProvider
  240. .createDefaultResponseAuthenticationConverter() <1>
  241. .convert(responseToken);
  242. Assertion assertion = responseToken.getResponse().getAssertions().get(0);
  243. String username = assertion.getSubject().getNameID().getValue();
  244. UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); <2>
  245. return MySaml2Authentication(userDetails, authentication); <3>
  246. });
  247. http
  248. .authorizeHttpRequests(authz -> authz
  249. .anyRequest().authenticated()
  250. )
  251. .saml2Login(saml2 -> saml2
  252. .authenticationManager(new ProviderManager(authenticationProvider))
  253. );
  254. return http.build();
  255. }
  256. }
  257. ----
  258. Kotlin::
  259. +
  260. [source,kotlin,role="secondary"]
  261. ----
  262. @Configuration
  263. @EnableWebSecurity
  264. open class SecurityConfig {
  265. @Autowired
  266. var userDetailsService: UserDetailsService? = null
  267. @Bean
  268. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  269. val authenticationProvider = OpenSaml4AuthenticationProvider()
  270. authenticationProvider.setResponseAuthenticationConverter { responseToken: OpenSaml4AuthenticationProvider.ResponseToken ->
  271. val authentication = OpenSaml4AuthenticationProvider
  272. .createDefaultResponseAuthenticationConverter() <1>
  273. .convert(responseToken)
  274. val assertion: Assertion = responseToken.response.assertions[0]
  275. val username: String = assertion.subject.nameID.value
  276. val userDetails = userDetailsService!!.loadUserByUsername(username) <2>
  277. MySaml2Authentication(userDetails, authentication) <3>
  278. }
  279. http {
  280. authorizeRequests {
  281. authorize(anyRequest, authenticated)
  282. }
  283. saml2Login {
  284. authenticationManager = ProviderManager(authenticationProvider)
  285. }
  286. }
  287. return http.build()
  288. }
  289. }
  290. ----
  291. ======
  292. <1> First, call the default converter, which extracts attributes and authorities from the response
  293. <2> Second, call the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`] using the relevant information
  294. <3> Third, return a custom authentication that includes the user details
  295. [NOTE]
  296. It's not required to call ``OpenSaml4AuthenticationProvider``'s default authentication converter.
  297. It returns a `Saml2AuthenticatedPrincipal` containing the attributes it extracted from ``AttributeStatement``s as well as the single `ROLE_USER` authority.
  298. [[servlet-saml2login-opensamlauthenticationprovider-additionalvalidation]]
  299. == Performing Additional Response Validation
  300. `OpenSaml4AuthenticationProvider` validates the `Issuer` and `Destination` values right after decrypting the `Response`.
  301. You can customize the validation by extending the default validator concatenating with your own response validator, or you can replace it entirely with yours.
  302. For example, you can throw a custom exception with any additional information available in the `Response` object, like so:
  303. [source,java]
  304. ----
  305. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  306. provider.setResponseValidator((responseToken) -> {
  307. Saml2ResponseValidatorResult result = OpenSamlAuthenticationProvider
  308. .createDefaultResponseValidator()
  309. .convert(responseToken)
  310. .concat(myCustomValidator.convert(responseToken));
  311. if (!result.getErrors().isEmpty()) {
  312. String inResponseTo = responseToken.getInResponseTo();
  313. throw new CustomSaml2AuthenticationException(result, inResponseTo);
  314. }
  315. return result;
  316. });
  317. ----
  318. When using `OpenSaml5AuthenticationProvider`, you can do the same with less boilerplate:
  319. [source,java]
  320. ----
  321. OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
  322. ResponseValidator responseValidator = ResponseValidator.withDefaults(myCustomValidator);
  323. provider.setResponseValidator(responseValidator);
  324. ----
  325. You can also customize which validation steps Spring Security should do.
  326. For example, if you want to skip `Response#InResponseTo` validation, you can call ``ResponseValidator``'s constructor, excluding `InResponseToValidator` from the list:
  327. [source,java]
  328. ----
  329. OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
  330. ResponseValidator responseValidator = new ResponseValidator(new DestinationValidator(), new IssuerValidator());
  331. provider.setResponseValidator(responseValidator);
  332. ----
  333. [TIP]
  334. ====
  335. OpenSAML performs `Asssertion#InResponseTo` validation in its `BearerSubjectConfirmationValidator` class, which is configurable using <<_performing_additional_assertion_validation, setAssertionValidator>>.
  336. ====
  337. == Performing Additional Assertion Validation
  338. `OpenSaml4AuthenticationProvider` performs minimal validation on SAML 2.0 Assertions.
  339. After verifying the signature, it will:
  340. 1. Validate `<AudienceRestriction>` and `<DelegationRestriction>` conditions
  341. 2. Validate ``<SubjectConfirmation>``s, expect for any IP address information
  342. To perform additional validation, you can configure your own assertion validator that delegates to ``OpenSaml4AuthenticationProvider``'s default and then performs its own.
  343. [[servlet-saml2login-opensamlauthenticationprovider-onetimeuse]]
  344. For example, you can use OpenSAML's `OneTimeUseConditionValidator` to also validate a `<OneTimeUse>` condition, like so:
  345. [tabs]
  346. ======
  347. Java::
  348. +
  349. [source,java,role="primary"]
  350. ----
  351. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  352. OneTimeUseConditionValidator validator = ...;
  353. provider.setAssertionValidator(assertionToken -> {
  354. Saml2ResponseValidatorResult result = OpenSaml4AuthenticationProvider
  355. .createDefaultAssertionValidator()
  356. .convert(assertionToken);
  357. Assertion assertion = assertionToken.getAssertion();
  358. OneTimeUse oneTimeUse = assertion.getConditions().getOneTimeUse();
  359. ValidationContext context = new ValidationContext();
  360. try {
  361. if (validator.validate(oneTimeUse, assertion, context) = ValidationResult.VALID) {
  362. return result;
  363. }
  364. } catch (Exception e) {
  365. return result.concat(new Saml2Error(INVALID_ASSERTION, e.getMessage()));
  366. }
  367. return result.concat(new Saml2Error(INVALID_ASSERTION, context.getValidationFailureMessage()));
  368. });
  369. ----
  370. Kotlin::
  371. +
  372. [source,kotlin,role="secondary"]
  373. ----
  374. var provider = OpenSaml4AuthenticationProvider()
  375. var validator: OneTimeUseConditionValidator = ...
  376. provider.setAssertionValidator { assertionToken ->
  377. val result = OpenSaml4AuthenticationProvider
  378. .createDefaultAssertionValidator()
  379. .convert(assertionToken)
  380. val assertion: Assertion = assertionToken.assertion
  381. val oneTimeUse: OneTimeUse = assertion.conditions.oneTimeUse
  382. val context = ValidationContext()
  383. try {
  384. if (validator.validate(oneTimeUse, assertion, context) = ValidationResult.VALID) {
  385. return@setAssertionValidator result
  386. }
  387. } catch (e: Exception) {
  388. return@setAssertionValidator result.concat(Saml2Error(INVALID_ASSERTION, e.message))
  389. }
  390. result.concat(Saml2Error(INVALID_ASSERTION, context.validationFailureMessage))
  391. }
  392. ----
  393. ======
  394. [NOTE]
  395. While recommended, it's not necessary to call ``OpenSaml4AuthenticationProvider``'s default assertion validator.
  396. 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.
  397. If you are using xref:servlet/saml2/opensaml.adoc[OpenSAML 5], then we have a simpler way using `OpenSaml5AuthenticationProvider.AssertionValidator`:
  398. [tabs]
  399. ======
  400. Java::
  401. +
  402. [source,java,role="primary"]
  403. ----
  404. OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
  405. OneTimeUseConditionValidator validator = ...;
  406. AssertionValidator assertionValidator = AssertionValidator.builder()
  407. .conditionValidators((c) -> c.add(validator)).build();
  408. provider.setAssertionValidator(assertionValidator);
  409. ----
  410. Kotlin::
  411. +
  412. [source,kotlin,role="secondary"]
  413. ----
  414. val provider = OpenSaml5AuthenticationProvider()
  415. val validator: OneTimeUseConditionValidator = ...;
  416. val assertionValidator = AssertionValidator.builder()
  417. .conditionValidators { add(validator) }.build()
  418. provider.setAssertionValidator(assertionValidator)
  419. ----
  420. ======
  421. You can use this same builder to remove validators that you don't want to use like so:
  422. [tabs]
  423. ======
  424. Java::
  425. +
  426. [source,java,role="primary"]
  427. ----
  428. OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
  429. AssertionValidator assertionValidator = AssertionValidator.builder()
  430. .conditionValidators((c) -> c.removeIf(AudienceRestrictionValidator.class::isInstance)).build();
  431. provider.setAssertionValidator(assertionValidator);
  432. ----
  433. Kotlin::
  434. +
  435. [source,kotlin,role="secondary"]
  436. ----
  437. val provider = new OpenSaml5AuthenticationProvider()
  438. val assertionValidator = AssertionValidator.builder()
  439. .conditionValidators {
  440. c: List<ConditionValidator> -> c.removeIf { it is AudienceRestrictionValidator }
  441. }.build()
  442. provider.setAssertionValidator(assertionValidator)
  443. ----
  444. ======
  445. [[servlet-saml2login-opensamlauthenticationprovider-decryption]]
  446. == Customizing Decryption
  447. 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`].
  448. `OpenSaml4AuthenticationProvider` exposes xref:servlet/saml2/login/overview.adoc#servlet-saml2login-architecture[two decryption strategies].
  449. The response decrypter is for decrypting encrypted elements of the `<saml2:Response>`, like `<saml2:EncryptedAssertion>`.
  450. The assertion decrypter is for decrypting encrypted elements of the `<saml2:Assertion>`, like `<saml2:EncryptedAttribute>` and `<saml2:EncryptedID>`.
  451. You can replace ``OpenSaml4AuthenticationProvider``'s default decryption strategy with your own.
  452. For example, if you have a separate service that decrypts the assertions in a `<saml2:Response>`, you can use it instead like so:
  453. [tabs]
  454. ======
  455. Java::
  456. +
  457. [source,java,role="primary"]
  458. ----
  459. MyDecryptionService decryptionService = ...;
  460. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  461. provider.setResponseElementsDecrypter((responseToken) -> decryptionService.decrypt(responseToken.getResponse()));
  462. ----
  463. Kotlin::
  464. +
  465. [source,kotlin,role="secondary"]
  466. ----
  467. val decryptionService: MyDecryptionService = ...
  468. val provider = OpenSaml4AuthenticationProvider()
  469. provider.setResponseElementsDecrypter { responseToken -> decryptionService.decrypt(responseToken.response) }
  470. ----
  471. ======
  472. If you are also decrypting individual elements in a `<saml2:Assertion>`, you can customize the assertion decrypter, too:
  473. [tabs]
  474. ======
  475. Java::
  476. +
  477. [source,java,role="primary"]
  478. ----
  479. provider.setAssertionElementsDecrypter((assertionToken) -> decryptionService.decrypt(assertionToken.getAssertion()));
  480. ----
  481. Kotlin::
  482. +
  483. [source,kotlin,role="secondary"]
  484. ----
  485. provider.setAssertionElementsDecrypter { assertionToken -> decryptionService.decrypt(assertionToken.assertion) }
  486. ----
  487. ======
  488. NOTE: There are two separate decrypters since assertions can be signed separately from responses.
  489. Trying to decrypt a signed assertion's elements before signature verification may invalidate the signature.
  490. If your asserting party signs the response only, then it's safe to decrypt all elements using only the response decrypter.
  491. [[servlet-saml2login-authenticationmanager-custom]]
  492. == Using a Custom Authentication Manager
  493. [[servlet-saml2login-opensamlauthenticationprovider-authenticationmanager]]
  494. Of course, the `authenticationManager` DSL method can be also used to perform a completely custom SAML 2.0 authentication.
  495. This authentication manager should expect a `Saml2AuthenticationToken` object containing the SAML 2.0 Response XML data.
  496. [tabs]
  497. ======
  498. Java::
  499. +
  500. [source,java,role="primary"]
  501. ----
  502. @Configuration
  503. @EnableWebSecurity
  504. public class SecurityConfig {
  505. @Bean
  506. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  507. AuthenticationManager authenticationManager = new MySaml2AuthenticationManager(...);
  508. http
  509. .authorizeHttpRequests(authorize -> authorize
  510. .anyRequest().authenticated()
  511. )
  512. .saml2Login(saml2 -> saml2
  513. .authenticationManager(authenticationManager)
  514. )
  515. ;
  516. return http.build();
  517. }
  518. }
  519. ----
  520. Kotlin::
  521. +
  522. [source,kotlin,role="secondary"]
  523. ----
  524. @Configuration
  525. @EnableWebSecurity
  526. open class SecurityConfig {
  527. @Bean
  528. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  529. val customAuthenticationManager: AuthenticationManager = MySaml2AuthenticationManager(...)
  530. http {
  531. authorizeRequests {
  532. authorize(anyRequest, authenticated)
  533. }
  534. saml2Login {
  535. authenticationManager = customAuthenticationManager
  536. }
  537. }
  538. return http.build()
  539. }
  540. }
  541. ----
  542. ======
  543. [[servlet-saml2login-authenticatedprincipal]]
  544. == Using `Saml2AuthenticatedPrincipal`
  545. With the relying party correctly configured for a given asserting party, it's ready to accept assertions.
  546. Once the relying party validates an assertion, the result is a `Saml2Authentication` with a `Saml2AuthenticatedPrincipal`.
  547. This means that you can access the principal in your controller like so:
  548. [tabs]
  549. ======
  550. Java::
  551. +
  552. [source,java,role="primary"]
  553. ----
  554. @Controller
  555. public class MainController {
  556. @GetMapping("/")
  557. public String index(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal, Model model) {
  558. String email = principal.getFirstAttribute("email");
  559. model.setAttribute("email", email);
  560. return "index";
  561. }
  562. }
  563. ----
  564. Kotlin::
  565. +
  566. [source,kotlin,role="secondary"]
  567. ----
  568. @Controller
  569. class MainController {
  570. @GetMapping("/")
  571. fun index(@AuthenticationPrincipal principal: Saml2AuthenticatedPrincipal, model: Model): String {
  572. val email = principal.getFirstAttribute<String>("email")
  573. model.setAttribute("email", email)
  574. return "index"
  575. }
  576. }
  577. ----
  578. ======
  579. [TIP]
  580. 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.
  581. `getFirstAttribute` is quite handy when you know that there is only one value.