authentication.adoc 18 KB

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