authentication.adoc 18 KB

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