authentication.adoc 18 KB

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