login.adoc 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  1. [[servlet-saml2login]]
  2. = SAML 2.0 Login
  3. :figures: images/servlet/saml2
  4. :icondir: images/icons
  5. The SAML 2.0 Login feature provides an application with the capability to act as a SAML 2.0 Relying Party, having users https://wiki.shibboleth.net/confluence/display/CONCEPT/FlowsAndConfig[log in] to the application by using their existing account at a SAML 2.0 Asserting Party (Okta, ADFS, etc).
  6. NOTE: SAML 2.0 Login is implemented by using the *Web Browser SSO Profile*, as specified in
  7. https://www.oasis-open.org/committees/download.php/35389/sstc-saml-profiles-errata-2.0-wd-06-diff.pdf#page=15[SAML 2 Profiles].
  8. [[servlet-saml2login-spring-security-history]]
  9. Since 2009, support for relying parties has existed as an https://github.com/spring-projects/spring-security-saml/tree/1e013b07a7772defd6a26fcfae187c9bf661ee8f#spring-saml[extension project].
  10. In 2019, the process began to port that into https://github.com/spring-projects/spring-security[Spring Security] proper.
  11. This process is similar to the one started in 2017 for xref:servlet/oauth2/index.adoc[Spring Security's OAuth 2.0 support].
  12. [NOTE]
  13. ====
  14. A working sample for {gh-samples-url}/servlet/spring-boot/java/saml2-login[SAML 2.0 Login] is available in the {gh-samples-url}[Spring Security Samples repository].
  15. ====
  16. Let's take a look at how SAML 2.0 Relying Party Authentication works within Spring Security.
  17. First, we see that, like xref:servlet/oauth2/oauth2-login.adoc[OAuth 2.0 Login], Spring Security takes the user to a third-party for performing authentication.
  18. It does this through a series of redirects.
  19. .Redirecting to Asserting Party Authentication
  20. image::{figures}/saml2webssoauthenticationrequestfilter.png[]
  21. The figure above builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] and xref:servlet/authentication/architecture.adoc#servlet-authentication-abstractprocessingfilter[`AbstractAuthenticationProcessingFilter`] diagrams:
  22. image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized.
  23. image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is __Denied__ by throwing an `AccessDeniedException`.
  24. image:{icondir}/number_3.png[] Since the user lacks authorization, the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__.
  25. The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.html[`LoginUrlAuthenticationEntryPoint`] which redirects to <<servlet-saml2login-sp-initiated-factory,the `<saml2:AuthnRequest>` generating endpoint>>, `Saml2WebSsoAuthenticationRequestFilter`.
  26. Or, if you've <<servlet-saml2login-relyingpartyregistrationrepository,configured more than one asserting party>>, it will first redirect to a picker page.
  27. image:{icondir}/number_4.png[] Next, the `Saml2WebSsoAuthenticationRequestFilter` creates, signs, serializes, and encodes a `<saml2:AuthnRequest>` using its configured <<servlet-saml2login-sp-initiated-factory,`Saml2AuthenticationRequestFactory`>>.
  28. image:{icondir}/number_5.png[] Then, the browser takes this `<saml2:AuthnRequest>` and presents it to the asserting party.
  29. The asserting party attempts to authentication the user.
  30. If successful, it will return a `<saml2:Response>` back to the browser.
  31. image:{icondir}/number_6.png[] The browser then POSTs the `<saml2:Response>` to the assertion consumer service endpoint.
  32. [[servlet-saml2login-authentication-saml2webssoauthenticationfilter]]
  33. .Authenticating a `<saml2:Response>`
  34. image::{figures}/saml2webssoauthenticationfilter.png[]
  35. The figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram.
  36. image:{icondir}/number_1.png[] When the browser submits a `<saml2:Response>` to the application, it <<servlet-saml2login-authenticate-responses, delegates to `Saml2WebSsoAuthenticationFilter`>>.
  37. This filter calls its configured `AuthenticationConverter` to create a `Saml2AuthenticationToken` by extracting the response from the `HttpServletRequest`.
  38. This converter additionally resolves the <<servlet-saml2login-relyingpartyregistration, `RelyingPartyRegistration`>> and supplies it to `Saml2AuthenticationToken`.
  39. image:{icondir}/number_2.png[] Next, the filter passes the token to its configured xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`].
  40. By default, it will use the <<servlet-saml2login-architecture,`OpenSAML authentication provider`>>.
  41. image:{icondir}/number_3.png[] If authentication fails, then __Failure__
  42. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] is cleared out.
  43. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is invoked to restart the authentication process.
  44. image:{icondir}/number_4.png[] If authentication is successful, then __Success__.
  45. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`].
  46. * The `Saml2WebSsoAuthenticationFilter` invokes `FilterChain#doFilter(request,response)` to continue with the rest of the application logic.
  47. [[servlet-saml2login-minimaldependencies]]
  48. == Minimal Dependencies
  49. SAML 2.0 service provider support resides in `spring-security-saml2-service-provider`.
  50. It builds off of the OpenSAML library.
  51. [[servlet-saml2login-minimalconfiguration]]
  52. == Minimal Configuration
  53. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a service provider consists of two basic steps.
  54. First, include the needed dependencies and second, indicate the necessary asserting party metadata.
  55. [NOTE]
  56. Also, this presupposes that you've already xref:servlet/saml2/metadata.adoc#servlet-saml2login-metadata[registered the relying party with your asserting party].
  57. === Specifying Identity Provider Metadata
  58. In a Spring Boot application, to specify an identity provider's metadata, simply do:
  59. [source,yml]
  60. ----
  61. spring:
  62. security:
  63. saml2:
  64. relyingparty:
  65. registration:
  66. adfs:
  67. identityprovider:
  68. entity-id: https://idp.example.com/issuer
  69. verification.credentials:
  70. - certificate-location: "classpath:idp.crt"
  71. singlesignon.url: https://idp.example.com/issuer/sso
  72. singlesignon.sign-request: false
  73. ----
  74. where
  75. * `https://idp.example.com/issuer` is the value contained in the `Issuer` attribute of the SAML responses that the identity provider will issue
  76. * `classpath:idp.crt` is the location on the classpath for the identity provider's certificate for verifying SAML responses, and
  77. * `https://idp.example.com/issuer/sso` is the endpoint where the identity provider is expecting ``AuthnRequest``s.
  78. * `adfs` is <<servlet-saml2login-relyingpartyregistrationid, an arbitrary identifier you choose>>
  79. And that's it!
  80. [NOTE]
  81. Identity Provider and Asserting Party are synonymous, as are Service Provider and Relying Party.
  82. These are frequently abbreviated as AP and RP, respectively.
  83. === Runtime Expectations
  84. As configured above, the application processes any `+POST /login/saml2/sso/{registrationId}+` request containing a `SAMLResponse` parameter:
  85. [source,html]
  86. ----
  87. POST /login/saml2/sso/adfs HTTP/1.1
  88. SAMLResponse=PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZ...
  89. ----
  90. There are two ways to see induce your asserting party to generate a `SAMLResponse`:
  91. * First, you can navigate to your asserting party.
  92. It likely has some kind of link or button for each registered relying party that you can click to send the `SAMLResponse`.
  93. * Second, you can navigate to a protected page in your app, for example, `http://localhost:8080`.
  94. Your app then redirects to the configured asserting party which then sends the `SAMLResponse`.
  95. From here, consider jumping to:
  96. * <<servlet-saml2login-architecture,How SAML 2.0 Login Integrates with OpenSAML>>
  97. * <<servlet-saml2login-authenticatedprincipal,How to Use the `Saml2AuthenticatedPrincipal`>>
  98. * <<servlet-saml2login-sansboot,How to Override or Replace Spring Boot's Auto Configuration>>
  99. [[servlet-saml2login-architecture]]
  100. == How SAML 2.0 Login Integrates with OpenSAML
  101. Spring Security's SAML 2.0 support has a couple of design goals:
  102. * First, rely on a library for SAML 2.0 operations and domain objects.
  103. To achieve this, Spring Security uses OpenSAML.
  104. * Second, ensure this library is not required when using Spring Security's SAML support.
  105. To achieve this, any interfaces or classes where Spring Security uses OpenSAML in the contract remain encapsulated.
  106. This makes it possible for you to switch out OpenSAML for some other library or even an unsupported version of OpenSAML.
  107. As a natural outcome of the above two goals, Spring Security's SAML API is quite small relative to other modules.
  108. Instead, classes like `OpenSaml4AuthenticationRequestFactory` and `OpenSaml4AuthenticationProvider` expose ``Converter``s that customize various steps in the authentication process.
  109. For example, once your application receives a `SAMLResponse` and delegates to `Saml2WebSsoAuthenticationFilter`, the filter will delegate to `OpenSaml4AuthenticationProvider`.
  110. [NOTE]
  111. For backward compatibility, Spring Security will use the latest OpenSAML 3 by default.
  112. Note, though that OpenSAML 3 has reached it's end-of-life and updating to OpenSAML 4.x is recommended.
  113. For that reason, Spring Security supports both OpenSAML 3.x and 4.x.
  114. If you manage your OpenSAML dependency to 4.x, then Spring Security will select its OpenSAML 4.x implementations.
  115. .Authenticating an OpenSAML `Response`
  116. image:{figures}/opensamlauthenticationprovider.png[]
  117. This figure builds off of the <<servlet-saml2login-authentication-saml2webssoauthenticationfilter,`Saml2WebSsoAuthenticationFilter` diagram>>.
  118. image:{icondir}/number_1.png[] The `Saml2WebSsoAuthenticationFilter` formulates the `Saml2AuthenticationToken` and invokes the xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`].
  119. image:{icondir}/number_2.png[] The xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`] invokes the OpenSAML authentication provider.
  120. image:{icondir}/number_3.png[] The authentication provider deserializes the response into an OpenSAML `Response` and checks its signature.
  121. If the signature is invalid, authentication fails.
  122. image:{icondir}/number_4.png[] Then, the provider <<servlet-saml2login-opensamlauthenticationprovider-decryption,decrypts any `EncryptedAssertion` elements>>.
  123. If any decryptions fail, authentication fails.
  124. image:{icondir}/number_5.png[] Next, the provider validates the response's `Issuer` and `Destination` values.
  125. If they don't match what's in the `RelyingPartyRegistration`, authentication fails.
  126. image:{icondir}/number_6.png[] After that, the provider verifies the signature of each `Assertion`.
  127. If any signature is invalid, authentication fails.
  128. Also, if neither the response nor the assertions have signatures, authentication fails.
  129. Either the response or all the assertions must have signatures.
  130. image:{icondir}/number_7.png[] Then, the provider <<servlet-saml2login-opensamlauthenticationprovider-decryption,decrypts any `EncryptedID` or `EncryptedAttribute` elements>>.
  131. If any decryptions fail, authentication fails.
  132. image:{icondir}/number_8.png[] Next, the provider validates each assertion's `ExpiresAt` and `NotBefore` timestamps, the `<Subject>` and any `<AudienceRestriction>` conditions.
  133. If any validations fail, authentication fails.
  134. image:{icondir}/number_9.png[] Following that, the provider takes the first assertion's `AttributeStatement` and maps it to a `Map<String, List<Object>>`.
  135. It also grants the `ROLE_USER` granted authority.
  136. image:{icondir}/number_10.png[] And finally, it takes the `NameID` from the first assertion, the `Map` of attributes, and the `GrantedAuthority` and constructs a `Saml2AuthenticatedPrincipal`.
  137. Then, it places that principal and the authorities into a `Saml2Authentication`.
  138. The resulting `Authentication#getPrincipal` is a Spring Security `Saml2AuthenticatedPrincipal` object, and `Authentication#getName` maps to the first assertion's `NameID` element.
  139. `Saml2AuthenticatedPrincipal#getRelyingPartyRegistrationId` holds the <<servlet-saml2login-relyingpartyregistrationid,identifier to the associated `RelyingPartyRegistration`>>.
  140. [[servlet-saml2login-opensaml-customization]]
  141. === Customizing OpenSAML Configuration
  142. Any class that uses both Spring Security and OpenSAML should statically initialize `OpenSamlInitializationService` at the beginning of the class, like so:
  143. ====
  144. .Java
  145. [source,java,role="primary"]
  146. ----
  147. static {
  148. OpenSamlInitializationService.initialize();
  149. }
  150. ----
  151. .Kotlin
  152. [source,kotlin,role="secondary"]
  153. ----
  154. companion object {
  155. init {
  156. OpenSamlInitializationService.initialize()
  157. }
  158. }
  159. ----
  160. ====
  161. This replaces OpenSAML's `InitializationService#initialize`.
  162. Occasionally, it can be valuable to customize how OpenSAML builds, marshalls, and unmarshalls SAML objects.
  163. In these circumstances, you may instead want to call `OpenSamlInitializationService#requireInitialize(Consumer)` that gives you access to OpenSAML's `XMLObjectProviderFactory`.
  164. For example, when sending an unsigned AuthNRequest, you may want to force reauthentication.
  165. In that case, you can register your own `AuthnRequestMarshaller`, like so:
  166. ====
  167. .Java
  168. [source,java,role="primary"]
  169. ----
  170. static {
  171. OpenSamlInitializationService.requireInitialize(factory -> {
  172. AuthnRequestMarshaller marshaller = new AuthnRequestMarshaller() {
  173. @Override
  174. public Element marshall(XMLObject object, Element element) throws MarshallingException {
  175. configureAuthnRequest((AuthnRequest) object);
  176. return super.marshall(object, element);
  177. }
  178. public Element marshall(XMLObject object, Document document) throws MarshallingException {
  179. configureAuthnRequest((AuthnRequest) object);
  180. return super.marshall(object, document);
  181. }
  182. private void configureAuthnRequest(AuthnRequest authnRequest) {
  183. authnRequest.setForceAuthn(true);
  184. }
  185. }
  186. factory.getMarshallerFactory().registerMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME, marshaller);
  187. });
  188. }
  189. ----
  190. .Kotlin
  191. [source,kotlin,role="secondary"]
  192. ----
  193. companion object {
  194. init {
  195. OpenSamlInitializationService.requireInitialize {
  196. val marshaller = object : AuthnRequestMarshaller() {
  197. override fun marshall(xmlObject: XMLObject, element: Element): Element {
  198. configureAuthnRequest(xmlObject as AuthnRequest)
  199. return super.marshall(xmlObject, element)
  200. }
  201. override fun marshall(xmlObject: XMLObject, document: Document): Element {
  202. configureAuthnRequest(xmlObject as AuthnRequest)
  203. return super.marshall(xmlObject, document)
  204. }
  205. private fun configureAuthnRequest(authnRequest: AuthnRequest) {
  206. authnRequest.isForceAuthn = true
  207. }
  208. }
  209. it.marshallerFactory.registerMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME, marshaller)
  210. }
  211. }
  212. }
  213. ----
  214. ====
  215. The `requireInitialize` method may only be called once per application instance.
  216. [[servlet-saml2login-sansboot]]
  217. == Overriding or Replacing Boot Auto Configuration
  218. There are two ``@Bean``s that Spring Boot generates for a relying party.
  219. The first is a `WebSecurityConfigurerAdapter` that configures the app as a relying party.
  220. When including `spring-security-saml2-service-provider`, the `WebSecurityConfigurerAdapter` looks like:
  221. .Default JWT Configuration
  222. ====
  223. .Java
  224. [source,java,role="primary"]
  225. ----
  226. protected void configure(HttpSecurity http) {
  227. http
  228. .authorizeRequests(authorize -> authorize
  229. .anyRequest().authenticated()
  230. )
  231. .saml2Login(withDefaults());
  232. }
  233. ----
  234. .Kotlin
  235. [source,kotlin,role="secondary"]
  236. ----
  237. fun configure(http: HttpSecurity) {
  238. http {
  239. authorizeRequests {
  240. authorize(anyRequest, authenticated)
  241. }
  242. saml2Login { }
  243. }
  244. }
  245. ----
  246. ====
  247. If the application doesn't expose a `WebSecurityConfigurerAdapter` bean, then Spring Boot will expose the above default one.
  248. You can replace this by exposing the bean within the application:
  249. .Custom SAML 2.0 Login Configuration
  250. ====
  251. .Java
  252. [source,java,role="primary"]
  253. ----
  254. @EnableWebSecurity
  255. public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
  256. protected void configure(HttpSecurity http) {
  257. http
  258. .authorizeRequests(authorize -> authorize
  259. .mvcMatchers("/messages/**").hasAuthority("ROLE_USER")
  260. .anyRequest().authenticated()
  261. )
  262. .saml2Login(withDefaults());
  263. }
  264. }
  265. ----
  266. .Kotlin
  267. [source,kotlin,role="secondary"]
  268. ----
  269. @EnableWebSecurity
  270. class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
  271. override fun configure(http: HttpSecurity) {
  272. http {
  273. authorizeRequests {
  274. authorize("/messages/**", hasAuthority("ROLE_USER"))
  275. authorize(anyRequest, authenticated)
  276. }
  277. saml2Login {
  278. }
  279. }
  280. }
  281. }
  282. ----
  283. ====
  284. The above requires the role of `USER` for any URL that starts with `/messages/`.
  285. [[servlet-saml2login-relyingpartyregistrationrepository]]
  286. The second `@Bean` Spring Boot creates is a {security-api-url}org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationRepository.html[`RelyingPartyRegistrationRepository`], which represents the asserting party and relying party metadata.
  287. This includes things like the location of the SSO endpoint the relying party should use when requesting authentication from the asserting party.
  288. You can override the default by publishing your own `RelyingPartyRegistrationRepository` bean.
  289. For example, you can look up the asserting party's configuration by hitting its metadata endpoint like so:
  290. .Relying Party Registration Repository
  291. ====
  292. .Java
  293. [source,java,role="primary"]
  294. ----
  295. @Value("${metadata.location}")
  296. String assertingPartyMetadataLocation;
  297. @Bean
  298. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  299. RelyingPartyRegistration registration = RelyingPartyRegistrations
  300. .fromMetadataLocation(assertingPartyMetadataLocation)
  301. .registrationId("example")
  302. .build();
  303. return new InMemoryRelyingPartyRegistrationRepository(registration);
  304. }
  305. ----
  306. .Kotlin
  307. [source,kotlin,role="secondary"]
  308. ----
  309. @Value("\${metadata.location}")
  310. var assertingPartyMetadataLocation: String? = null
  311. @Bean
  312. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  313. val registration = RelyingPartyRegistrations
  314. .fromMetadataLocation(assertingPartyMetadataLocation)
  315. .registrationId("example")
  316. .build()
  317. return InMemoryRelyingPartyRegistrationRepository(registration)
  318. }
  319. ----
  320. ====
  321. [[servlet-saml2login-relyingpartyregistrationid]]
  322. [NOTE]
  323. The `registrationId` is an arbitrary value that you choose for differentiating between registrations.
  324. Or you can provide each detail manually, as you can see below:
  325. .Relying Party Registration Repository Manual Configuration
  326. ====
  327. .Java
  328. [source,java,role="primary"]
  329. ----
  330. @Value("${verification.key}")
  331. File verificationKey;
  332. @Bean
  333. public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception {
  334. X509Certificate certificate = X509Support.decodeCertificate(this.verificationKey);
  335. Saml2X509Credential credential = Saml2X509Credential.verification(certificate);
  336. RelyingPartyRegistration registration = RelyingPartyRegistration
  337. .withRegistrationId("example")
  338. .assertingPartyDetails(party -> party
  339. .entityId("https://idp.example.com/issuer")
  340. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  341. .wantAuthnRequestsSigned(false)
  342. .verificationX509Credentials(c -> c.add(credential))
  343. )
  344. .build();
  345. return new InMemoryRelyingPartyRegistrationRepository(registration);
  346. }
  347. ----
  348. .Kotlin
  349. [source,kotlin,role="secondary"]
  350. ----
  351. @Value("\${verification.key}")
  352. var verificationKey: File? = null
  353. @Bean
  354. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository {
  355. val certificate: X509Certificate? = X509Support.decodeCertificate(verificationKey!!)
  356. val credential: Saml2X509Credential = Saml2X509Credential.verification(certificate)
  357. val registration = RelyingPartyRegistration
  358. .withRegistrationId("example")
  359. .assertingPartyDetails { party: AssertingPartyDetails.Builder ->
  360. party
  361. .entityId("https://idp.example.com/issuer")
  362. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  363. .wantAuthnRequestsSigned(false)
  364. .verificationX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  365. c.add(
  366. credential
  367. )
  368. }
  369. }
  370. .build()
  371. return InMemoryRelyingPartyRegistrationRepository(registration)
  372. }
  373. ----
  374. ====
  375. [NOTE]
  376. Note that `X509Support` is an OpenSAML class, used here in the snippet for brevity
  377. [[servlet-saml2login-relyingpartyregistrationrepository-dsl]]
  378. Alternatively, you can directly wire up the repository using the DSL, which will also override the auto-configured `WebSecurityConfigurerAdapter`:
  379. .Custom Relying Party Registration DSL
  380. ====
  381. .Java
  382. [source,java,role="primary"]
  383. ----
  384. @EnableWebSecurity
  385. public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
  386. protected void configure(HttpSecurity http) {
  387. http
  388. .authorizeRequests(authorize -> authorize
  389. .mvcMatchers("/messages/**").hasAuthority("ROLE_USER")
  390. .anyRequest().authenticated()
  391. )
  392. .saml2Login(saml2 -> saml2
  393. .relyingPartyRegistrationRepository(relyingPartyRegistrations())
  394. );
  395. }
  396. }
  397. ----
  398. .Kotlin
  399. [source,kotlin,role="secondary"]
  400. ----
  401. @EnableWebSecurity
  402. class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
  403. override fun configure(http: HttpSecurity) {
  404. http {
  405. authorizeRequests {
  406. authorize("/messages/**", hasAuthority("ROLE_USER"))
  407. authorize(anyRequest, authenticated)
  408. }
  409. saml2Login {
  410. relyingPartyRegistrationRepository = relyingPartyRegistrations()
  411. }
  412. }
  413. }
  414. }
  415. ----
  416. ====
  417. [NOTE]
  418. A relying party can be multi-tenant by registering more than one relying party in the `RelyingPartyRegistrationRepository`.
  419. [[servlet-saml2login-relyingpartyregistration]]
  420. == RelyingPartyRegistration
  421. A {security-api-url}org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.html[`RelyingPartyRegistration`]
  422. instance represents a link between an relying party and assering party's metadata.
  423. In a `RelyingPartyRegistration`, you can provide relying party metadata like its `Issuer` value, where it expects SAML Responses to be sent to, and any credentials that it owns for the purposes of signing or decrypting payloads.
  424. Also, you can provide asserting party metadata like its `Issuer` value, where it expects AuthnRequests to be sent to, and any public credentials that it owns for the purposes of the relying party verifying or encrypting payloads.
  425. The following `RelyingPartyRegistration` is the minimum required for most setups:
  426. ====
  427. .Java
  428. [source,java,role="primary"]
  429. ----
  430. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
  431. .fromMetadataLocation("https://ap.example.org/metadata")
  432. .registrationId("my-id")
  433. .build();
  434. ----
  435. .Kotlin
  436. [source,kotlin,role="secondary"]
  437. ----
  438. val relyingPartyRegistration = RelyingPartyRegistrations
  439. .fromMetadataLocation("https://ap.example.org/metadata")
  440. .registrationId("my-id")
  441. .build()
  442. ----
  443. ====
  444. Note that you can also create a `RelyingPartyRegistration` from an arbitrary `InputStream` source.
  445. One such example is when the metadata is stored in a database:
  446. [source,java]
  447. ----
  448. String xml = fromDatabase();
  449. try (InputStream source = new ByteArrayInputStream(xml.getBytes())) {
  450. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
  451. .fromMetadata(source)
  452. .registrationId("my-id")
  453. .build();
  454. }
  455. ----
  456. Though a more sophisticated setup is also possible, like so:
  457. ====
  458. .Java
  459. [source,java,role="primary"]
  460. ----
  461. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("my-id")
  462. .entityId("{baseUrl}/{registrationId}")
  463. .decryptionX509Credentials(c -> c.add(relyingPartyDecryptingCredential()))
  464. .assertionConsumerServiceLocation("/my-login-endpoint/{registrationId}")
  465. .assertingPartyDetails(party -> party
  466. .entityId("https://ap.example.org")
  467. .verificationX509Credentials(c -> c.add(assertingPartyVerifyingCredential()))
  468. .singleSignOnServiceLocation("https://ap.example.org/SSO.saml2")
  469. )
  470. .build();
  471. ----
  472. .Kotlin
  473. [source,kotlin,role="secondary"]
  474. ----
  475. val relyingPartyRegistration =
  476. RelyingPartyRegistration.withRegistrationId("my-id")
  477. .entityId("{baseUrl}/{registrationId}")
  478. .decryptionX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  479. c.add(relyingPartyDecryptingCredential())
  480. }
  481. .assertionConsumerServiceLocation("/my-login-endpoint/{registrationId}")
  482. .assertingPartyDetails { party -> party
  483. .entityId("https://ap.example.org")
  484. .verificationX509Credentials { c -> c.add(assertingPartyVerifyingCredential()) }
  485. .singleSignOnServiceLocation("https://ap.example.org/SSO.saml2")
  486. }
  487. .build()
  488. ----
  489. ====
  490. [TIP]
  491. The top-level metadata methods are details about the relying party.
  492. The methods inside `assertingPartyDetails` are details about the asserting party.
  493. [NOTE]
  494. The location where a relying party is expecting SAML Responses is the Assertion Consumer Service Location.
  495. The default for the relying party's `entityId` is `+{baseUrl}/saml2/service-provider-metadata/{registrationId}+`.
  496. This is this value needed when configuring the asserting party to know about your relying party.
  497. The default for the `assertionConsumerServiceLocation` is `+/login/saml2/sso/{registrationId}+`.
  498. It's mapped by default to <<servlet-saml2login-authentication-saml2webssoauthenticationfilter,`Saml2WebSsoAuthenticationFilter`>> in the filter chain.
  499. [[servlet-saml2login-rpr-uripatterns]]
  500. === URI Patterns
  501. You probably noticed in the above examples the `+{baseUrl}+` and `+{registrationId}+` placeholders.
  502. These are useful for generating URIs. As such, the relying party's `entityId` and `assertionConsumerServiceLocation` support the following placeholders:
  503. * `baseUrl` - the scheme, host, and port of a deployed application
  504. * `registrationId` - the registration id for this relying party
  505. * `baseScheme` - the scheme of a deployed application
  506. * `baseHost` - the host of a deployed application
  507. * `basePort` - the port of a deployed application
  508. For example, the `assertionConsumerServiceLocation` defined above was:
  509. `+/my-login-endpoint/{registrationId}+`
  510. which in a deployed application would translate to
  511. `+/my-login-endpoint/adfs+`
  512. The `entityId` above was defined as:
  513. `+{baseUrl}/{registrationId}+`
  514. which in a deployed application would translate to
  515. `+https://rp.example.com/adfs+`
  516. [[servlet-saml2login-rpr-credentials]]
  517. === Credentials
  518. You also likely noticed the credential that was used.
  519. Oftentimes, a relying party will use the same key to sign payloads as well as decrypt them.
  520. Or it will use the same key to verify payloads as well as encrypt them.
  521. Because of this, Spring Security ships with `Saml2X509Credential`, a SAML-specific credential that simplifies configuring the same key for different use cases.
  522. At a minimum, it's necessary to have a certificate from the asserting party so that the asserting party's signed responses can be verified.
  523. To construct a `Saml2X509Credential` that you'll use to verify assertions from the asserting party, you can load the file and use
  524. the `CertificateFactory` like so:
  525. ====
  526. .Java
  527. [source,java,role="primary"]
  528. ----
  529. Resource resource = new ClassPathResource("ap.crt");
  530. try (InputStream is = resource.getInputStream()) {
  531. X509Certificate certificate = (X509Certificate)
  532. CertificateFactory.getInstance("X.509").generateCertificate(is);
  533. return Saml2X509Credential.verification(certificate);
  534. }
  535. ----
  536. .Kotlin
  537. [source,kotlin,role="secondary"]
  538. ----
  539. val resource = ClassPathResource("ap.crt")
  540. resource.inputStream.use {
  541. return Saml2X509Credential.verification(
  542. CertificateFactory.getInstance("X.509").generateCertificate(it) as X509Certificate?
  543. )
  544. }
  545. ----
  546. ====
  547. Let's say that the asserting party is going to also encrypt the assertion.
  548. In that case, the relying party will need a private key to be able to decrypt the encrypted value.
  549. In that case, you'll need an `RSAPrivateKey` as well as its corresponding `X509Certificate`.
  550. You can load the first using Spring Security's `RsaKeyConverters` utility class and the second as you did before:
  551. ====
  552. .Java
  553. [source,java,role="primary"]
  554. ----
  555. X509Certificate certificate = relyingPartyDecryptionCertificate();
  556. Resource resource = new ClassPathResource("rp.crt");
  557. try (InputStream is = resource.getInputStream()) {
  558. RSAPrivateKey rsa = RsaKeyConverters.pkcs8().convert(is);
  559. return Saml2X509Credential.decryption(rsa, certificate);
  560. }
  561. ----
  562. .Kotlin
  563. [source,kotlin,role="secondary"]
  564. ----
  565. val certificate: X509Certificate = relyingPartyDecryptionCertificate()
  566. val resource = ClassPathResource("rp.crt")
  567. resource.inputStream.use {
  568. val rsa: RSAPrivateKey = RsaKeyConverters.pkcs8().convert(it)
  569. return Saml2X509Credential.decryption(rsa, certificate)
  570. }
  571. ----
  572. ====
  573. [TIP]
  574. When you specify the locations of these files as the appropriate Spring Boot properties, then Spring Boot will perform these conversions for you.
  575. [[servlet-saml2login-rpr-relyingpartyregistrationresolver]]
  576. === Resolving the Relying Party from the Request
  577. As seen so far, Spring Security resolves the `RelyingPartyRegistration` by looking for the registration id in the URI path.
  578. There are a number of reasons you may want to customize. Among them:
  579. * You may know that you will never be a multi-tenant application and so want to have a simpler URL scheme
  580. * You may identify tenants in a way other than by the URI path
  581. To customize the way that a `RelyingPartyRegistration` is resolved, you can configure a custom `RelyingPartyRegistrationResolver`.
  582. The default looks up the registration id from the URI's last path element and looks it up in your `RelyingPartyRegistrationRepository`.
  583. You can provide a simpler resolver that, for example, always returns the same relying party:
  584. ====
  585. .Java
  586. [source,java,role="primary"]
  587. ----
  588. public class SingleRelyingPartyRegistrationResolver implements RelyingPartyRegistrationResolver {
  589. private final RelyingPartyRegistrationResolver delegate;
  590. public SingleRelyingPartyRegistrationResolver(RelyingPartyRegistrationRepository registrations) {
  591. this.delegate = new DefaultRelyingPartyRegistrationResolver(registrations);
  592. }
  593. @Override
  594. public RelyingPartyRegistration resolve(HttpServletRequest request, String registrationId) {
  595. return this.delegate.resolve(request, "single");
  596. }
  597. }
  598. ----
  599. .Kotlin
  600. [source,kotlin,role="secondary"]
  601. ----
  602. class SingleRelyingPartyRegistrationResolver(delegate: RelyingPartyRegistrationResolver) : RelyingPartyRegistrationResolver {
  603. override fun resolve(request: HttpServletRequest?, registrationId: String?): RelyingPartyRegistration? {
  604. return this.delegate.resolve(request, "single")
  605. }
  606. }
  607. ----
  608. ====
  609. Then, you can provide this resolver to the appropriate filters that <<servlet-saml2login-sp-initiated-factory, produce ``<saml2:AuthnRequest>``s>>, <<servlet-saml2login-authenticate-responses, authenticate ``<saml2:Response>``s>>, and xref:servlet/saml2/metadata.adoc#servlet-saml2login-metadata[produce `<saml2:SPSSODescriptor>` metadata].
  610. [NOTE]
  611. Remember that if you have any placeholders in your `RelyingPartyRegistration`, your resolver implementation should resolve them.
  612. [[servlet-saml2login-rpr-duplicated]]
  613. === Duplicated Relying Party Configurations
  614. When an application uses multiple asserting parties, some configuration is duplicated between `RelyingPartyRegistration` instances:
  615. * The relying party's `entityId`
  616. * Its `assertionConsumerServiceLocation`, and
  617. * Its credentials, for example its signing or decryption credentials
  618. What's nice about this setup is credentials may be more easily rotated for some identity providers vs others.
  619. The duplication can be alleviated in a few different ways.
  620. First, in YAML this can be alleviated with references, like so:
  621. [source,yaml]
  622. ----
  623. spring:
  624. security:
  625. saml2:
  626. relyingparty:
  627. okta:
  628. signing.credentials: &relying-party-credentials
  629. - private-key-location: classpath:rp.key
  630. certificate-location: classpath:rp.crt
  631. identityprovider:
  632. entity-id: ...
  633. azure:
  634. signing.credentials: *relying-party-credentials
  635. identityprovider:
  636. entity-id: ...
  637. ----
  638. Second, in a database, it's not necessary to replicate `RelyingPartyRegistration` 's model.
  639. Third, in Java, you can create a custom configuration method, like so:
  640. ====
  641. .Java
  642. [source,java,role="primary"]
  643. ----
  644. private RelyingPartyRegistration.Builder
  645. addRelyingPartyDetails(RelyingPartyRegistration.Builder builder) {
  646. Saml2X509Credential signingCredential = ...
  647. builder.signingX509Credentials(c -> c.addAll(signingCredential));
  648. // ... other relying party configurations
  649. }
  650. @Bean
  651. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  652. RelyingPartyRegistration okta = addRelyingPartyDetails(
  653. RelyingPartyRegistrations
  654. .fromMetadataLocation(oktaMetadataUrl)
  655. .registrationId("okta")).build();
  656. RelyingPartyRegistration azure = addRelyingPartyDetails(
  657. RelyingPartyRegistrations
  658. .fromMetadataLocation(oktaMetadataUrl)
  659. .registrationId("azure")).build();
  660. return new InMemoryRelyingPartyRegistrationRepository(okta, azure);
  661. }
  662. ----
  663. .Kotlin
  664. [source,kotlin,role="secondary"]
  665. ----
  666. private fun addRelyingPartyDetails(builder: RelyingPartyRegistration.Builder): RelyingPartyRegistration.Builder {
  667. val signingCredential: Saml2X509Credential = ...
  668. builder.signingX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  669. c.add(
  670. signingCredential
  671. )
  672. }
  673. // ... other relying party configurations
  674. }
  675. @Bean
  676. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  677. val okta = addRelyingPartyDetails(
  678. RelyingPartyRegistrations
  679. .fromMetadataLocation(oktaMetadataUrl)
  680. .registrationId("okta")
  681. ).build()
  682. val azure = addRelyingPartyDetails(
  683. RelyingPartyRegistrations
  684. .fromMetadataLocation(oktaMetadataUrl)
  685. .registrationId("azure")
  686. ).build()
  687. return InMemoryRelyingPartyRegistrationRepository(okta, azure)
  688. }
  689. ----
  690. ====
  691. [[servlet-saml2login-sp-initiated-factory]]
  692. == Producing ``<saml2:AuthnRequest>``s
  693. As stated earlier, Spring Security's SAML 2.0 support produces a `<saml2:AuthnRequest>` to commence authentication with the asserting party.
  694. Spring Security achieves this in part by registering the `Saml2WebSsoAuthenticationRequestFilter` in the filter chain.
  695. This filter by default responds to endpoint `+/saml2/authenticate/{registrationId}+`.
  696. For example, if you were deployed to `https://rp.example.com` and you gave your registration an ID of `okta`, you could navigate to:
  697. `https://rp.example.org/saml2/authenticate/ping`
  698. and the result would be a redirect that included a `SAMLRequest` parameter containing the signed, deflated, and encoded `<saml2:AuthnRequest>`.
  699. [[servlet-saml2login-store-authn-request]]
  700. === Changing How the `<saml2:AuthnRequest>` Gets Stored
  701. `Saml2WebSsoAuthenticationRequestFilter` uses an `Saml2AuthenticationRequestRepository` to persist an `AbstractSaml2AuthenticationRequest` instance before <<servlet-saml2login-sp-initiated-factory,sending the `<saml2:AuthnRequest>`>> to the asserting party.
  702. Additionally, `Saml2WebSsoAuthenticationFilter` and `Saml2AuthenticationTokenConverter` use an `Saml2AuthenticationRequestRepository` to load any `AbstractSaml2AuthenticationRequest` as part of <<servlet-saml2login-authenticate-responses,authenticating the `<saml2:Response>`>>.
  703. By default, Spring Security uses an `HttpSessionSaml2AuthenticationRequestRepository`, which stores the `AbstractSaml2AuthenticationRequest` in the `HttpSession`.
  704. If you have a custom implementation of `Saml2AuthenticationRequestRepository`, you may configure it by exposing it as a `@Bean` as shown in the following example:
  705. ====
  706. .Java
  707. [source,java,role="primary"]
  708. ----
  709. @Bean
  710. Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository() {
  711. return new CustomSaml2AuthenticationRequestRepository();
  712. }
  713. ----
  714. .Kotlin
  715. [source,kotlin,role="secondary"]
  716. ----
  717. @Bean
  718. open fun authenticationRequestRepository(): Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> {
  719. return CustomSaml2AuthenticationRequestRepository()
  720. }
  721. ----
  722. ====
  723. [[servlet-saml2login-sp-initiated-factory-signing]]
  724. === Changing How the `<saml2:AuthnRequest>` Gets Sent
  725. By default, Spring Security signs each `<saml2:AuthnRequest>` and send it as a GET to the asserting party.
  726. Many asserting parties don't require a signed `<saml2:AuthnRequest>`.
  727. This can be configured automatically via `RelyingPartyRegistrations`, or you can supply it manually, like so:
  728. .Not Requiring Signed AuthnRequests
  729. ====
  730. .Boot
  731. [source,yaml,role="primary"]
  732. ----
  733. spring:
  734. security:
  735. saml2:
  736. relyingparty:
  737. okta:
  738. identityprovider:
  739. entity-id: ...
  740. singlesignon.sign-request: false
  741. ----
  742. .Java
  743. [source,java,role="secondary"]
  744. ----
  745. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("okta")
  746. // ...
  747. .assertingPartyDetails(party -> party
  748. // ...
  749. .wantAuthnRequestsSigned(false)
  750. )
  751. .build();
  752. ----
  753. .Kotlin
  754. [source,java,role="secondary"]
  755. ----
  756. var relyingPartyRegistration: RelyingPartyRegistration =
  757. RelyingPartyRegistration.withRegistrationId("okta")
  758. // ...
  759. .assertingPartyDetails { party: AssertingPartyDetails.Builder -> party
  760. // ...
  761. .wantAuthnRequestsSigned(false)
  762. }
  763. .build();
  764. ----
  765. ====
  766. Otherwise, you will need to specify a private key to `RelyingPartyRegistration#signingX509Credentials` so that Spring Security can sign the `<saml2:AuthnRequest>` before sending.
  767. [[servlet-saml2login-sp-initiated-factory-algorithm]]
  768. By default, Spring Security will sign the `<saml2:AuthnRequest>` using `rsa-sha256`, though some asserting parties will require a different algorithm, as indicated in their metadata.
  769. You can configure the algorithm based on the asserting party's <<servlet-saml2login-relyingpartyregistrationrepository,metadata using `RelyingPartyRegistrations`>>.
  770. Or, you can provide it manually:
  771. ====
  772. .Java
  773. [source,java,role="primary"]
  774. ----
  775. String metadataLocation = "classpath:asserting-party-metadata.xml";
  776. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations.fromMetadataLocation(metadataLocation)
  777. // ...
  778. .assertingPartyDetails((party) -> party
  779. // ...
  780. .signingAlgorithms((sign) -> sign.add(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA512))
  781. )
  782. .build();
  783. ----
  784. .Kotlin
  785. [source,kotlin,role="secondary"]
  786. ----
  787. var metadataLocation = "classpath:asserting-party-metadata.xml"
  788. var relyingPartyRegistration: RelyingPartyRegistration =
  789. RelyingPartyRegistrations.fromMetadataLocation(metadataLocation)
  790. // ...
  791. .assertingPartyDetails { party: AssertingPartyDetails.Builder -> party
  792. // ...
  793. .signingAlgorithms { sign: MutableList<String?> ->
  794. sign.add(
  795. SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA512
  796. )
  797. }
  798. }
  799. .build();
  800. ----
  801. ====
  802. NOTE: The snippet above uses the OpenSAML `SignatureConstants` class to supply the algorithm name.
  803. But, that's just for convenience.
  804. Since the datatype is `String`, you can supply the name of the algorithm directly.
  805. [[servlet-saml2login-sp-initiated-factory-binding]]
  806. Some asserting parties require that the `<saml2:AuthnRequest>` be POSTed.
  807. This can be configured automatically via `RelyingPartyRegistrations`, or you can supply it manually, like so:
  808. ====
  809. .Java
  810. [source,java,role="primary"]
  811. ----
  812. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("okta")
  813. // ...
  814. .assertingPartyDetails(party -> party
  815. // ...
  816. .singleSignOnServiceBinding(Saml2MessageBinding.POST)
  817. )
  818. .build();
  819. ----
  820. .Kotlin
  821. [source,kotlin,role="secondary"]
  822. ----
  823. var relyingPartyRegistration: RelyingPartyRegistration? =
  824. RelyingPartyRegistration.withRegistrationId("okta")
  825. // ...
  826. .assertingPartyDetails { party: AssertingPartyDetails.Builder -> party
  827. // ...
  828. .singleSignOnServiceBinding(Saml2MessageBinding.POST)
  829. }
  830. .build()
  831. ----
  832. ====
  833. [[servlet-saml2login-sp-initiated-factory-custom-authnrequest]]
  834. === Customizing OpenSAML's `AuthnRequest` Instance
  835. There are a number of reasons that you may want to adjust an `AuthnRequest`.
  836. For example, you may want `ForceAuthN` to be set to `true`, which Spring Security sets to `false` by default.
  837. If you don't need information from the `HttpServletRequest` to make your decision, then the easiest way is to <<servlet-saml2login-opensaml-customization,register a custom `AuthnRequestMarshaller` with OpenSAML>>.
  838. This will give you access to post-process the `AuthnRequest` instance before it's serialized.
  839. But, if you do need something from the request, then you can use create a custom `Saml2AuthenticationRequestContext` implementation and then a `Converter<Saml2AuthenticationRequestContext, AuthnRequest>` to build an `AuthnRequest` yourself, like so:
  840. ====
  841. .Java
  842. [source,java,role="primary"]
  843. ----
  844. @Component
  845. public class AuthnRequestConverter implements
  846. Converter<MySaml2AuthenticationRequestContext, AuthnRequest> {
  847. private final AuthnRequestBuilder authnRequestBuilder;
  848. private final IssuerBuilder issuerBuilder;
  849. // ... constructor
  850. public AuthnRequest convert(Saml2AuthenticationRequestContext context) {
  851. MySaml2AuthenticationRequestContext myContext = (MySaml2AuthenticationRequestContext) context;
  852. Issuer issuer = issuerBuilder.buildObject();
  853. issuer.setValue(myContext.getIssuer());
  854. AuthnRequest authnRequest = authnRequestBuilder.buildObject();
  855. authnRequest.setIssuer(issuer);
  856. authnRequest.setDestination(myContext.getDestination());
  857. authnRequest.setAssertionConsumerServiceURL(myContext.getAssertionConsumerServiceUrl());
  858. // ... additional settings
  859. authRequest.setForceAuthn(myContext.getForceAuthn());
  860. return authnRequest;
  861. }
  862. }
  863. ----
  864. .Kotlin
  865. [source,kotlin,role="secondary"]
  866. ----
  867. @Component
  868. class AuthnRequestConverter : Converter<MySaml2AuthenticationRequestContext, AuthnRequest> {
  869. private val authnRequestBuilder: AuthnRequestBuilder? = null
  870. private val issuerBuilder: IssuerBuilder? = null
  871. // ... constructor
  872. override fun convert(context: MySaml2AuthenticationRequestContext): AuthnRequest {
  873. val myContext: MySaml2AuthenticationRequestContext = context
  874. val issuer: Issuer = issuerBuilder.buildObject()
  875. issuer.value = myContext.getIssuer()
  876. val authnRequest: AuthnRequest = authnRequestBuilder.buildObject()
  877. authnRequest.issuer = issuer
  878. authnRequest.destination = myContext.getDestination()
  879. authnRequest.assertionConsumerServiceURL = myContext.getAssertionConsumerServiceUrl()
  880. // ... additional settings
  881. authRequest.setForceAuthn(myContext.getForceAuthn())
  882. return authnRequest
  883. }
  884. }
  885. ----
  886. ====
  887. Then, you can construct your own `Saml2AuthenticationRequestContextResolver` and `Saml2AuthenticationRequestFactory` and publish them as ``@Bean``s:
  888. ====
  889. .Java
  890. [source,java,role="primary"]
  891. ----
  892. @Bean
  893. Saml2AuthenticationRequestContextResolver authenticationRequestContextResolver() {
  894. Saml2AuthenticationRequestContextResolver resolver =
  895. new DefaultSaml2AuthenticationRequestContextResolver();
  896. return request -> {
  897. Saml2AuthenticationRequestContext context = resolver.resolve(request);
  898. return new MySaml2AuthenticationRequestContext(context, request.getParameter("force") != null);
  899. };
  900. }
  901. @Bean
  902. Saml2AuthenticationRequestFactory authenticationRequestFactory(
  903. AuthnRequestConverter authnRequestConverter) {
  904. OpenSaml4AuthenticationRequestFactory authenticationRequestFactory =
  905. new OpenSaml4AuthenticationRequestFactory();
  906. authenticationRequestFactory.setAuthenticationRequestContextConverter(authnRequestConverter);
  907. return authenticationRequestFactory;
  908. }
  909. ----
  910. .Kotlin
  911. [source,kotlin,role="secondary"]
  912. ----
  913. @Bean
  914. open fun authenticationRequestContextResolver(): Saml2AuthenticationRequestContextResolver {
  915. val resolver: Saml2AuthenticationRequestContextResolver = DefaultSaml2AuthenticationRequestContextResolver()
  916. return Saml2AuthenticationRequestContextResolver { request: HttpServletRequest ->
  917. val context = resolver.resolve(request)
  918. MySaml2AuthenticationRequestContext(
  919. context,
  920. request.getParameter("force") != null
  921. )
  922. }
  923. }
  924. @Bean
  925. open fun authenticationRequestFactory(
  926. authnRequestConverter: AuthnRequestConverter?
  927. ): Saml2AuthenticationRequestFactory? {
  928. val authenticationRequestFactory = OpenSaml4AuthenticationRequestFactory()
  929. authenticationRequestFactory.setAuthenticationRequestContextConverter(authnRequestConverter)
  930. return authenticationRequestFactory
  931. }
  932. ----
  933. ====
  934. [[servlet-saml2login-authenticate-responses]]
  935. == Authenticating ``<saml2:Response>``s
  936. To verify SAML 2.0 Responses, Spring Security uses <<servlet-saml2login-architecture,`OpenSaml4AuthenticationProvider`>> by default.
  937. You can configure this in a number of ways including:
  938. 1. Setting a clock skew to timestamp validation
  939. 2. Mapping the response to a list of `GrantedAuthority` instances
  940. 3. Customizing the strategy for validating assertions
  941. 4. Customizing the strategy for decrypting response and assertion elements
  942. To configure these, you'll use the `saml2Login#authenticationManager` method in the DSL.
  943. [[servlet-saml2login-opensamlauthenticationprovider-clockskew]]
  944. === Setting a Clock Skew
  945. It's not uncommon for the asserting and relying parties to have system clocks that aren't perfectly synchronized.
  946. For that reason, you can configure `OpenSaml4AuthenticationProvider` 's default assertion validator with some tolerance:
  947. ====
  948. .Java
  949. [source,java,role="primary"]
  950. ----
  951. @EnableWebSecurity
  952. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  953. @Override
  954. protected void configure(HttpSecurity http) throws Exception {
  955. OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
  956. authenticationProvider.setAssertionValidator(OpenSaml4AuthenticationProvider
  957. .createDefaultAssertionValidator(assertionToken -> {
  958. Map<String, Object> params = new HashMap<>();
  959. params.put(CLOCK_SKEW, Duration.ofMinutes(10).toMillis());
  960. // ... other validation parameters
  961. return new ValidationContext(params);
  962. })
  963. );
  964. http
  965. .authorizeRequests(authz -> authz
  966. .anyRequest().authenticated()
  967. )
  968. .saml2Login(saml2 -> saml2
  969. .authenticationManager(new ProviderManager(authenticationProvider))
  970. );
  971. }
  972. }
  973. ----
  974. .Kotlin
  975. [source,kotlin,role="secondary"]
  976. ----
  977. @EnableWebSecurity
  978. open class SecurityConfig : WebSecurityConfigurerAdapter() {
  979. override fun configure(http: HttpSecurity) {
  980. val authenticationProvider = OpenSaml4AuthenticationProvider()
  981. authenticationProvider.setAssertionValidator(
  982. OpenSaml4AuthenticationProvider
  983. .createDefaultAssertionValidator(Converter<OpenSaml4AuthenticationProvider.AssertionToken, ValidationContext> {
  984. val params: MutableMap<String, Any> = HashMap()
  985. params[CLOCK_SKEW] =
  986. Duration.ofMinutes(10).toMillis()
  987. ValidationContext(params)
  988. })
  989. )
  990. http {
  991. authorizeRequests {
  992. authorize(anyRequest, authenticated)
  993. }
  994. saml2Login {
  995. authenticationManager = ProviderManager(authenticationProvider)
  996. }
  997. }
  998. }
  999. }
  1000. ----
  1001. ====
  1002. [[servlet-saml2login-opensamlauthenticationprovider-userdetailsservice]]
  1003. === Coordinating with a `UserDetailsService`
  1004. Or, perhaps you would like to include user details from a legacy `UserDetailsService`.
  1005. In that case, the response authentication converter can come in handy, as can be seen below:
  1006. ====
  1007. .Java
  1008. [source,java,role="primary"]
  1009. ----
  1010. @EnableWebSecurity
  1011. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  1012. @Autowired
  1013. UserDetailsService userDetailsService;
  1014. @Override
  1015. protected void configure(HttpSecurity http) throws Exception {
  1016. OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
  1017. authenticationProvider.setResponseAuthenticationConverter(responseToken -> {
  1018. Saml2Authentication authentication = OpenSaml4AuthenticationProvider
  1019. .createDefaultResponseAuthenticationConverter() <1>
  1020. .convert(responseToken);
  1021. Assertion assertion = responseToken.getResponse().getAssertions().get(0);
  1022. String username = assertion.getSubject().getNameID().getValue();
  1023. UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); <2>
  1024. return MySaml2Authentication(userDetails, authentication); <3>
  1025. });
  1026. http
  1027. .authorizeRequests(authz -> authz
  1028. .anyRequest().authenticated()
  1029. )
  1030. .saml2Login(saml2 -> saml2
  1031. .authenticationManager(new ProviderManager(authenticationProvider))
  1032. );
  1033. }
  1034. }
  1035. ----
  1036. .Kotlin
  1037. [source,kotlin,role="secondary"]
  1038. ----
  1039. @EnableWebSecurity
  1040. open class SecurityConfig : WebSecurityConfigurerAdapter() {
  1041. @Autowired
  1042. var userDetailsService: UserDetailsService? = null
  1043. override fun configure(http: HttpSecurity) {
  1044. val authenticationProvider = OpenSaml4AuthenticationProvider()
  1045. authenticationProvider.setResponseAuthenticationConverter { responseToken: OpenSaml4AuthenticationProvider.ResponseToken ->
  1046. val authentication = OpenSaml4AuthenticationProvider
  1047. .createDefaultResponseAuthenticationConverter() <1>
  1048. .convert(responseToken)
  1049. val assertion: Assertion = responseToken.response.assertions[0]
  1050. val username: String = assertion.subject.nameID.value
  1051. val userDetails = userDetailsService!!.loadUserByUsername(username) <2>
  1052. MySaml2Authentication(userDetails, authentication) <3>
  1053. }
  1054. http {
  1055. authorizeRequests {
  1056. authorize(anyRequest, authenticated)
  1057. }
  1058. saml2Login {
  1059. authenticationManager = ProviderManager(authenticationProvider)
  1060. }
  1061. }
  1062. }
  1063. }
  1064. ----
  1065. ====
  1066. <1> First, call the default converter, which extracts attributes and authorities from the response
  1067. <2> Second, call the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`] using the relevant information
  1068. <3> Third, return a custom authentication that includes the user details
  1069. [NOTE]
  1070. It's not required to call `OpenSaml4AuthenticationProvider` 's default authentication converter.
  1071. It returns a `Saml2AuthenticatedPrincipal` containing the attributes it extracted from ``AttributeStatement``s as well as the single `ROLE_USER` authority.
  1072. [[servlet-saml2login-opensamlauthenticationprovider-additionalvalidation]]
  1073. === Performing Additional Response Validation
  1074. `OpenSaml4AuthenticationProvider` validates the `Issuer` and `Destination` values right after decrypting the `Response`.
  1075. You can customize the validation by extending the default validator concatenating with your own response validator, or you can replace it entirely with yours.
  1076. For example, you can throw a custom exception with any additional information available in the `Response` object, like so:
  1077. [source,java]
  1078. ----
  1079. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  1080. provider.setResponseValidator((responseToken) -> {
  1081. Saml2ResponseValidatorResult result = OpenSamlAuthenticationProvider
  1082. .createDefaultResponseValidator()
  1083. .convert(responseToken)
  1084. .concat(myCustomValidator.convert(responseToken));
  1085. if (!result.getErrors().isEmpty()) {
  1086. String inResponseTo = responseToken.getInResponseTo();
  1087. throw new CustomSaml2AuthenticationException(result, inResponseTo);
  1088. }
  1089. return result;
  1090. });
  1091. ----
  1092. === Performing Additional Assertion Validation
  1093. `OpenSaml4AuthenticationProvider` performs minimal validation on SAML 2.0 Assertions.
  1094. After verifying the signature, it will:
  1095. 1. Validate `<AudienceRestriction>` and `<DelegationRestriction>` conditions
  1096. 2. Validate ``<SubjectConfirmation>``s, expect for any IP address information
  1097. To perform additional validation, you can configure your own assertion validator that delegates to `OpenSaml4AuthenticationProvider` 's default and then performs its own.
  1098. [[servlet-saml2login-opensamlauthenticationprovider-onetimeuse]]
  1099. For example, you can use OpenSAML's `OneTimeUseConditionValidator` to also validate a `<OneTimeUse>` condition, like so:
  1100. ====
  1101. .Java
  1102. [source,java,role="primary"]
  1103. ----
  1104. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  1105. OneTimeUseConditionValidator validator = ...;
  1106. provider.setAssertionValidator(assertionToken -> {
  1107. Saml2ResponseValidatorResult result = OpenSaml4AuthenticationProvider
  1108. .createDefaultAssertionValidator()
  1109. .convert(assertionToken);
  1110. Assertion assertion = assertionToken.getAssertion();
  1111. OneTimeUse oneTimeUse = assertion.getConditions().getOneTimeUse();
  1112. ValidationContext context = new ValidationContext();
  1113. try {
  1114. if (validator.validate(oneTimeUse, assertion, context) = ValidationResult.VALID) {
  1115. return result;
  1116. }
  1117. } catch (Exception e) {
  1118. return result.concat(new Saml2Error(INVALID_ASSERTION, e.getMessage()));
  1119. }
  1120. return result.concat(new Saml2Error(INVALID_ASSERTION, context.getValidationFailureMessage()));
  1121. });
  1122. ----
  1123. .Kotlin
  1124. [source,kotlin,role="secondary"]
  1125. ----
  1126. var provider = OpenSaml4AuthenticationProvider()
  1127. var validator: OneTimeUseConditionValidator = ...
  1128. provider.setAssertionValidator { assertionToken ->
  1129. val result = OpenSaml4AuthenticationProvider
  1130. .createDefaultAssertionValidator()
  1131. .convert(assertionToken)
  1132. val assertion: Assertion = assertionToken.assertion
  1133. val oneTimeUse: OneTimeUse = assertion.conditions.oneTimeUse
  1134. val context = ValidationContext()
  1135. try {
  1136. if (validator.validate(oneTimeUse, assertion, context) = ValidationResult.VALID) {
  1137. return@setAssertionValidator result
  1138. }
  1139. } catch (e: Exception) {
  1140. return@setAssertionValidator result.concat(Saml2Error(INVALID_ASSERTION, e.message))
  1141. }
  1142. result.concat(Saml2Error(INVALID_ASSERTION, context.validationFailureMessage))
  1143. }
  1144. ----
  1145. ====
  1146. [NOTE]
  1147. While recommended, it's not necessary to call `OpenSaml4AuthenticationProvider` 's default assertion validator.
  1148. 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.
  1149. [[servlet-saml2login-opensamlauthenticationprovider-decryption]]
  1150. === Customizing Decryption
  1151. Spring Security decrypts `<saml2:EncryptedAssertion>`, `<saml2:EncryptedAttribute>`, and `<saml2:EncryptedID>` elements automatically by using the decryption <<servlet-saml2login-rpr-credentials,`Saml2X509Credential` instances>> registered in the <<servlet-saml2login-relyingpartyregistration,`RelyingPartyRegistration`>>.
  1152. `OpenSaml4AuthenticationProvider` exposes <<servlet-saml2login-architecture,two decryption strategies>>.
  1153. The response decrypter is for decrypting encrypted elements of the `<saml2:Response>`, like `<saml2:EncryptedAssertion>`.
  1154. The assertion decrypter is for decrypting encrypted elements of the `<saml2:Assertion>`, like `<saml2:EncryptedAttribute>` and `<saml2:EncryptedID>`.
  1155. You can replace `OpenSaml4AuthenticationProvider`'s default decryption strategy with your own.
  1156. For example, if you have a separate service that decrypts the assertions in a `<saml2:Response>`, you can use it instead like so:
  1157. ====
  1158. .Java
  1159. [source,java,role="primary"]
  1160. ----
  1161. MyDecryptionService decryptionService = ...;
  1162. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  1163. provider.setResponseElementsDecrypter((responseToken) -> decryptionService.decrypt(responseToken.getResponse()));
  1164. ----
  1165. .Kotlin
  1166. [source,kotlin,role="secondary"]
  1167. ----
  1168. val decryptionService: MyDecryptionService = ...
  1169. val provider = OpenSaml4AuthenticationProvider()
  1170. provider.setResponseElementsDecrypter { responseToken -> decryptionService.decrypt(responseToken.response) }
  1171. ----
  1172. ====
  1173. If you are also decrypting individual elements in a `<saml2:Assertion>`, you can customize the assertion decrypter, too:
  1174. ====
  1175. .Java
  1176. [source,java,role="primary"]
  1177. ----
  1178. provider.setAssertionElementsDecrypter((assertionToken) -> decryptionService.decrypt(assertionToken.getAssertion()));
  1179. ----
  1180. .Kotlin
  1181. [source,kotlin,role="secondary"]
  1182. ----
  1183. provider.setAssertionElementsDecrypter { assertionToken -> decryptionService.decrypt(assertionToken.assertion) }
  1184. ----
  1185. ====
  1186. NOTE: There are two separate decrypters since assertions can be signed separately from responses.
  1187. Trying to decrypt a signed assertion's elements before signature verification may invalidate the signature.
  1188. If your asserting party signs the response only, then it's safe to decrypt all elements using only the response decrypter.
  1189. [[servlet-saml2login-authenticationmanager-custom]]
  1190. === Using a Custom Authentication Manager
  1191. [[servlet-saml2login-opensamlauthenticationprovider-authenticationmanager]]
  1192. Of course, the `authenticationManager` DSL method can be also used to perform a completely custom SAML 2.0 authentication.
  1193. This authentication manager should expect a `Saml2AuthenticationToken` object containing the SAML 2.0 Response XML data.
  1194. ====
  1195. .Java
  1196. [source,java,role="primary"]
  1197. ----
  1198. @EnableWebSecurity
  1199. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  1200. @Override
  1201. protected void configure(HttpSecurity http) throws Exception {
  1202. AuthenticationManager authenticationManager = new MySaml2AuthenticationManager(...);
  1203. http
  1204. .authorizeRequests(authorize -> authorize
  1205. .anyRequest().authenticated()
  1206. )
  1207. .saml2Login(saml2 -> saml2
  1208. .authenticationManager(authenticationManager)
  1209. )
  1210. ;
  1211. }
  1212. }
  1213. ----
  1214. .Kotlin
  1215. [source,kotlin,role="secondary"]
  1216. ----
  1217. @EnableWebSecurity
  1218. open class SecurityConfig : WebSecurityConfigurerAdapter() {
  1219. override fun configure(http: HttpSecurity) {
  1220. val customAuthenticationManager: AuthenticationManager = MySaml2AuthenticationManager(...)
  1221. http {
  1222. authorizeRequests {
  1223. authorize(anyRequest, authenticated)
  1224. }
  1225. saml2Login {
  1226. authenticationManager = customAuthenticationManager
  1227. }
  1228. }
  1229. }
  1230. }
  1231. ----
  1232. ====
  1233. [[servlet-saml2login-authenticatedprincipal]]
  1234. == Using `Saml2AuthenticatedPrincipal`
  1235. With the relying party correctly configured for a given asserting party, it's ready to accept assertions.
  1236. Once the relying party validates an assertion, the result is a `Saml2Authentication` with a `Saml2AuthenticatedPrincipal`.
  1237. This means that you can access the principal in your controller like so:
  1238. ====
  1239. .Java
  1240. [source,java,role="primary"]
  1241. ----
  1242. @Controller
  1243. public class MainController {
  1244. @GetMapping("/")
  1245. public String index(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal, Model model) {
  1246. String email = principal.getFirstAttribute("email");
  1247. model.setAttribute("email", email);
  1248. return "index";
  1249. }
  1250. }
  1251. ----
  1252. .Kotlin
  1253. [source,kotlin,role="secondary"]
  1254. ----
  1255. @Controller
  1256. class MainController {
  1257. @GetMapping("/")
  1258. fun index(@AuthenticationPrincipal principal: Saml2AuthenticatedPrincipal, model: Model): String {
  1259. val email = principal.getFirstAttribute<String>("email")
  1260. model.setAttribute("email", email)
  1261. return "index"
  1262. }
  1263. }
  1264. ----
  1265. ====
  1266. [TIP]
  1267. 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.
  1268. `getFirstAttribute` is quite handy when you know that there is only one value.