authentication.adoc 15 KB

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