authentication.adoc 18 KB

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