authentication.adoc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. [[relyingpartyregistrationresolver-apply]]
  12. == Changing `RelyingPartyRegistration` Lookup
  13. `RelyingPartyRegistration` lookup is customized xref:servlet/saml2/login/overview.adoc#servlet-saml2login-rpr-relyingpartyregistrationresolver[in a `RelyingPartyRegistrationResolver`].
  14. To apply a `RelyingPartyRegistrationResolver` when processing `<saml2:Response>` payloads, you should first publish a `Saml2AuthenticationTokenConverter` bean like so:
  15. [tabs]
  16. ======
  17. Java::
  18. +
  19. [source,java,role="primary"]
  20. ----
  21. @Bean
  22. Saml2AuthenticationTokenConverter authenticationConverter(InMemoryRelyingPartyRegistrationRepository registrations) {
  23. return new Saml2AuthenticationTokenConverter(new MyRelyingPartyRegistrationResolver(registrations));
  24. }
  25. ----
  26. Kotlin::
  27. +
  28. [source,kotlin,role="secondary"]
  29. ----
  30. @Bean
  31. fun authenticationConverter(val registrations: InMemoryRelyingPartyRegistrationRepository): Saml2AuthenticationTokenConverter {
  32. return Saml2AuthenticationTokenConverter(MyRelyingPartyRegistrationResolver(registrations));
  33. }
  34. ----
  35. ======
  36. Recall that the Assertion Consumer Service URL is `+/saml2/login/sso/{registrationId}+` by default.
  37. If you are no longer wanting the `registrationId` in the URL, change it in the filter chain and in your relying party metadata:
  38. [tabs]
  39. ======
  40. Java::
  41. +
  42. [source,java,role="primary"]
  43. ----
  44. @Bean
  45. SecurityFilterChain securityFilters(HttpSecurity http) throws Exception {
  46. http
  47. // ...
  48. .saml2Login((saml2) -> saml2.filterProcessingUrl("/saml2/login/sso"))
  49. // ...
  50. return http.build();
  51. }
  52. ----
  53. Kotlin::
  54. +
  55. [source,kotlin,role="secondary"]
  56. ----
  57. @Bean
  58. fun securityFilters(val http: HttpSecurity): SecurityFilterChain {
  59. http {
  60. // ...
  61. .saml2Login {
  62. filterProcessingUrl = "/saml2/login/sso"
  63. }
  64. // ...
  65. }
  66. return http.build()
  67. }
  68. ----
  69. ======
  70. and:
  71. [tabs]
  72. ======
  73. Java::
  74. +
  75. [source,java,role="primary"]
  76. ----
  77. relyingPartyRegistrationBuilder.assertionConsumerServiceLocation("/saml2/login/sso")
  78. ----
  79. Kotlin::
  80. +
  81. [source,kotlin,role="secondary"]
  82. ----
  83. relyingPartyRegistrationBuilder.assertionConsumerServiceLocation("/saml2/login/sso")
  84. ----
  85. ======
  86. [[servlet-saml2login-opensamlauthenticationprovider-clockskew]]
  87. == Setting a Clock Skew
  88. It's not uncommon for the asserting and relying parties to have system clocks that aren't perfectly synchronized.
  89. For that reason, you can configure ``OpenSaml4AuthenticationProvider``'s default assertion validator with some tolerance:
  90. [tabs]
  91. ======
  92. Java::
  93. +
  94. [source,java,role="primary"]
  95. ----
  96. @Configuration
  97. @EnableWebSecurity
  98. public class SecurityConfig {
  99. @Bean
  100. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  101. OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
  102. authenticationProvider.setAssertionValidator(OpenSaml4AuthenticationProvider
  103. .createDefaultAssertionValidator(assertionToken -> {
  104. Map<String, Object> params = new HashMap<>();
  105. params.put(CLOCK_SKEW, Duration.ofMinutes(10).toMillis());
  106. // ... other validation parameters
  107. return new ValidationContext(params);
  108. })
  109. );
  110. http
  111. .authorizeHttpRequests(authz -> authz
  112. .anyRequest().authenticated()
  113. )
  114. .saml2Login(saml2 -> saml2
  115. .authenticationManager(new ProviderManager(authenticationProvider))
  116. );
  117. return http.build();
  118. }
  119. }
  120. ----
  121. Kotlin::
  122. +
  123. [source,kotlin,role="secondary"]
  124. ----
  125. @Configuration
  126. @EnableWebSecurity
  127. open class SecurityConfig {
  128. @Bean
  129. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  130. val authenticationProvider = OpenSaml4AuthenticationProvider()
  131. authenticationProvider.setAssertionValidator(
  132. OpenSaml4AuthenticationProvider
  133. .createDefaultAssertionValidator(Converter<OpenSaml4AuthenticationProvider.AssertionToken, ValidationContext> {
  134. val params: MutableMap<String, Any> = HashMap()
  135. params[CLOCK_SKEW] =
  136. Duration.ofMinutes(10).toMillis()
  137. ValidationContext(params)
  138. })
  139. )
  140. http {
  141. authorizeRequests {
  142. authorize(anyRequest, authenticated)
  143. }
  144. saml2Login {
  145. authenticationManager = ProviderManager(authenticationProvider)
  146. }
  147. }
  148. return http.build()
  149. }
  150. }
  151. ----
  152. ======
  153. [[servlet-saml2login-opensamlauthenticationprovider-userdetailsservice]]
  154. == Coordinating with a `UserDetailsService`
  155. Or, perhaps you would like to include user details from a legacy `UserDetailsService`.
  156. In that case, the response authentication converter can come in handy, as can be seen below:
  157. [tabs]
  158. ======
  159. Java::
  160. +
  161. [source,java,role="primary"]
  162. ----
  163. @Configuration
  164. @EnableWebSecurity
  165. public class SecurityConfig {
  166. @Autowired
  167. UserDetailsService userDetailsService;
  168. @Bean
  169. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  170. OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
  171. authenticationProvider.setResponseAuthenticationConverter(responseToken -> {
  172. Saml2Authentication authentication = OpenSaml4AuthenticationProvider
  173. .createDefaultResponseAuthenticationConverter() <1>
  174. .convert(responseToken);
  175. Assertion assertion = responseToken.getResponse().getAssertions().get(0);
  176. String username = assertion.getSubject().getNameID().getValue();
  177. UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); <2>
  178. return MySaml2Authentication(userDetails, authentication); <3>
  179. });
  180. http
  181. .authorizeHttpRequests(authz -> authz
  182. .anyRequest().authenticated()
  183. )
  184. .saml2Login(saml2 -> saml2
  185. .authenticationManager(new ProviderManager(authenticationProvider))
  186. );
  187. return http.build();
  188. }
  189. }
  190. ----
  191. Kotlin::
  192. +
  193. [source,kotlin,role="secondary"]
  194. ----
  195. @Configuration
  196. @EnableWebSecurity
  197. open class SecurityConfig {
  198. @Autowired
  199. var userDetailsService: UserDetailsService? = null
  200. @Bean
  201. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  202. val authenticationProvider = OpenSaml4AuthenticationProvider()
  203. authenticationProvider.setResponseAuthenticationConverter { responseToken: OpenSaml4AuthenticationProvider.ResponseToken ->
  204. val authentication = OpenSaml4AuthenticationProvider
  205. .createDefaultResponseAuthenticationConverter() <1>
  206. .convert(responseToken)
  207. val assertion: Assertion = responseToken.response.assertions[0]
  208. val username: String = assertion.subject.nameID.value
  209. val userDetails = userDetailsService!!.loadUserByUsername(username) <2>
  210. MySaml2Authentication(userDetails, authentication) <3>
  211. }
  212. http {
  213. authorizeRequests {
  214. authorize(anyRequest, authenticated)
  215. }
  216. saml2Login {
  217. authenticationManager = ProviderManager(authenticationProvider)
  218. }
  219. }
  220. return http.build()
  221. }
  222. }
  223. ----
  224. ======
  225. <1> First, call the default converter, which extracts attributes and authorities from the response
  226. <2> Second, call the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`] using the relevant information
  227. <3> Third, return a custom authentication that includes the user details
  228. [NOTE]
  229. It's not required to call ``OpenSaml4AuthenticationProvider``'s default authentication converter.
  230. It returns a `Saml2AuthenticatedPrincipal` containing the attributes it extracted from ``AttributeStatement``s as well as the single `ROLE_USER` authority.
  231. [[servlet-saml2login-opensamlauthenticationprovider-additionalvalidation]]
  232. == Performing Additional Response Validation
  233. `OpenSaml4AuthenticationProvider` validates the `Issuer` and `Destination` values right after decrypting the `Response`.
  234. You can customize the validation by extending the default validator concatenating with your own response validator, or you can replace it entirely with yours.
  235. For example, you can throw a custom exception with any additional information available in the `Response` object, like so:
  236. [source,java]
  237. ----
  238. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  239. provider.setResponseValidator((responseToken) -> {
  240. Saml2ResponseValidatorResult result = OpenSamlAuthenticationProvider
  241. .createDefaultResponseValidator()
  242. .convert(responseToken)
  243. .concat(myCustomValidator.convert(responseToken));
  244. if (!result.getErrors().isEmpty()) {
  245. String inResponseTo = responseToken.getInResponseTo();
  246. throw new CustomSaml2AuthenticationException(result, inResponseTo);
  247. }
  248. return result;
  249. });
  250. ----
  251. == Performing Additional Assertion Validation
  252. `OpenSaml4AuthenticationProvider` performs minimal validation on SAML 2.0 Assertions.
  253. After verifying the signature, it will:
  254. 1. Validate `<AudienceRestriction>` and `<DelegationRestriction>` conditions
  255. 2. Validate ``<SubjectConfirmation>``s, expect for any IP address information
  256. To perform additional validation, you can configure your own assertion validator that delegates to ``OpenSaml4AuthenticationProvider``'s default and then performs its own.
  257. [[servlet-saml2login-opensamlauthenticationprovider-onetimeuse]]
  258. For example, you can use OpenSAML's `OneTimeUseConditionValidator` to also validate a `<OneTimeUse>` condition, like so:
  259. [tabs]
  260. ======
  261. Java::
  262. +
  263. [source,java,role="primary"]
  264. ----
  265. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  266. OneTimeUseConditionValidator validator = ...;
  267. provider.setAssertionValidator(assertionToken -> {
  268. Saml2ResponseValidatorResult result = OpenSaml4AuthenticationProvider
  269. .createDefaultAssertionValidator()
  270. .convert(assertionToken);
  271. Assertion assertion = assertionToken.getAssertion();
  272. OneTimeUse oneTimeUse = assertion.getConditions().getOneTimeUse();
  273. ValidationContext context = new ValidationContext();
  274. try {
  275. if (validator.validate(oneTimeUse, assertion, context) = ValidationResult.VALID) {
  276. return result;
  277. }
  278. } catch (Exception e) {
  279. return result.concat(new Saml2Error(INVALID_ASSERTION, e.getMessage()));
  280. }
  281. return result.concat(new Saml2Error(INVALID_ASSERTION, context.getValidationFailureMessage()));
  282. });
  283. ----
  284. Kotlin::
  285. +
  286. [source,kotlin,role="secondary"]
  287. ----
  288. var provider = OpenSaml4AuthenticationProvider()
  289. var validator: OneTimeUseConditionValidator = ...
  290. provider.setAssertionValidator { assertionToken ->
  291. val result = OpenSaml4AuthenticationProvider
  292. .createDefaultAssertionValidator()
  293. .convert(assertionToken)
  294. val assertion: Assertion = assertionToken.assertion
  295. val oneTimeUse: OneTimeUse = assertion.conditions.oneTimeUse
  296. val context = ValidationContext()
  297. try {
  298. if (validator.validate(oneTimeUse, assertion, context) = ValidationResult.VALID) {
  299. return@setAssertionValidator result
  300. }
  301. } catch (e: Exception) {
  302. return@setAssertionValidator result.concat(Saml2Error(INVALID_ASSERTION, e.message))
  303. }
  304. result.concat(Saml2Error(INVALID_ASSERTION, context.validationFailureMessage))
  305. }
  306. ----
  307. ======
  308. [NOTE]
  309. While recommended, it's not necessary to call ``OpenSaml4AuthenticationProvider``'s default assertion validator.
  310. 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.
  311. [[servlet-saml2login-opensamlauthenticationprovider-decryption]]
  312. == Customizing Decryption
  313. 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`].
  314. `OpenSaml4AuthenticationProvider` exposes xref:servlet/saml2/login/overview.adoc#servlet-saml2login-architecture[two decryption strategies].
  315. The response decrypter is for decrypting encrypted elements of the `<saml2:Response>`, like `<saml2:EncryptedAssertion>`.
  316. The assertion decrypter is for decrypting encrypted elements of the `<saml2:Assertion>`, like `<saml2:EncryptedAttribute>` and `<saml2:EncryptedID>`.
  317. You can replace ``OpenSaml4AuthenticationProvider``'s default decryption strategy with your own.
  318. For example, if you have a separate service that decrypts the assertions in a `<saml2:Response>`, you can use it instead like so:
  319. [tabs]
  320. ======
  321. Java::
  322. +
  323. [source,java,role="primary"]
  324. ----
  325. MyDecryptionService decryptionService = ...;
  326. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  327. provider.setResponseElementsDecrypter((responseToken) -> decryptionService.decrypt(responseToken.getResponse()));
  328. ----
  329. Kotlin::
  330. +
  331. [source,kotlin,role="secondary"]
  332. ----
  333. val decryptionService: MyDecryptionService = ...
  334. val provider = OpenSaml4AuthenticationProvider()
  335. provider.setResponseElementsDecrypter { responseToken -> decryptionService.decrypt(responseToken.response) }
  336. ----
  337. ======
  338. If you are also decrypting individual elements in a `<saml2:Assertion>`, you can customize the assertion decrypter, too:
  339. [tabs]
  340. ======
  341. Java::
  342. +
  343. [source,java,role="primary"]
  344. ----
  345. provider.setAssertionElementsDecrypter((assertionToken) -> decryptionService.decrypt(assertionToken.getAssertion()));
  346. ----
  347. Kotlin::
  348. +
  349. [source,kotlin,role="secondary"]
  350. ----
  351. provider.setAssertionElementsDecrypter { assertionToken -> decryptionService.decrypt(assertionToken.assertion) }
  352. ----
  353. ======
  354. NOTE: There are two separate decrypters since assertions can be signed separately from responses.
  355. Trying to decrypt a signed assertion's elements before signature verification may invalidate the signature.
  356. If your asserting party signs the response only, then it's safe to decrypt all elements using only the response decrypter.
  357. [[servlet-saml2login-authenticationmanager-custom]]
  358. == Using a Custom Authentication Manager
  359. [[servlet-saml2login-opensamlauthenticationprovider-authenticationmanager]]
  360. Of course, the `authenticationManager` DSL method can be also used to perform a completely custom SAML 2.0 authentication.
  361. This authentication manager should expect a `Saml2AuthenticationToken` object containing the SAML 2.0 Response XML data.
  362. [tabs]
  363. ======
  364. Java::
  365. +
  366. [source,java,role="primary"]
  367. ----
  368. @Configuration
  369. @EnableWebSecurity
  370. public class SecurityConfig {
  371. @Bean
  372. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  373. AuthenticationManager authenticationManager = new MySaml2AuthenticationManager(...);
  374. http
  375. .authorizeHttpRequests(authorize -> authorize
  376. .anyRequest().authenticated()
  377. )
  378. .saml2Login(saml2 -> saml2
  379. .authenticationManager(authenticationManager)
  380. )
  381. ;
  382. return http.build();
  383. }
  384. }
  385. ----
  386. Kotlin::
  387. +
  388. [source,kotlin,role="secondary"]
  389. ----
  390. @Configuration
  391. @EnableWebSecurity
  392. open class SecurityConfig {
  393. @Bean
  394. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  395. val customAuthenticationManager: AuthenticationManager = MySaml2AuthenticationManager(...)
  396. http {
  397. authorizeRequests {
  398. authorize(anyRequest, authenticated)
  399. }
  400. saml2Login {
  401. authenticationManager = customAuthenticationManager
  402. }
  403. }
  404. return http.build()
  405. }
  406. }
  407. ----
  408. ======
  409. [[servlet-saml2login-authenticatedprincipal]]
  410. == Using `Saml2AuthenticatedPrincipal`
  411. With the relying party correctly configured for a given asserting party, it's ready to accept assertions.
  412. Once the relying party validates an assertion, the result is a `Saml2Authentication` with a `Saml2AuthenticatedPrincipal`.
  413. This means that you can access the principal in your controller like so:
  414. [tabs]
  415. ======
  416. Java::
  417. +
  418. [source,java,role="primary"]
  419. ----
  420. @Controller
  421. public class MainController {
  422. @GetMapping("/")
  423. public String index(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal, Model model) {
  424. String email = principal.getFirstAttribute("email");
  425. model.setAttribute("email", email);
  426. return "index";
  427. }
  428. }
  429. ----
  430. Kotlin::
  431. +
  432. [source,kotlin,role="secondary"]
  433. ----
  434. @Controller
  435. class MainController {
  436. @GetMapping("/")
  437. fun index(@AuthenticationPrincipal principal: Saml2AuthenticatedPrincipal, model: Model): String {
  438. val email = principal.getFirstAttribute<String>("email")
  439. model.setAttribute("email", email)
  440. return "index"
  441. }
  442. }
  443. ----
  444. ======
  445. [TIP]
  446. 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.
  447. `getFirstAttribute` is quite handy when you know that there is only one value.