overview.adoc 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. = SAML 2.0 Login Overview
  2. :figures: servlet/saml2
  3. :icondir: icons
  4. Let's take a look at how SAML 2.0 Relying Party Authentication works within Spring Security.
  5. First, we see that, like xref:servlet/oauth2/login/index.adoc[OAuth 2.0 Login], Spring Security takes the user to a third-party for performing authentication.
  6. It does this through a series of redirects.
  7. .Redirecting to Asserting Party Authentication
  8. image::{figures}/saml2webssoauthenticationrequestfilter.png[]
  9. The figure above builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] and xref:servlet/authentication/architecture.adoc#servlet-authentication-abstractprocessingfilter[`AbstractAuthenticationProcessingFilter`] diagrams:
  10. image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized.
  11. 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`.
  12. image:{icondir}/number_3.png[] Since the user lacks authorization, the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__.
  13. 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 xref:servlet/saml2/login/authentication-requests.adoc#servlet-saml2login-sp-initiated-factory[the `<saml2:AuthnRequest>` generating endpoint], `Saml2WebSsoAuthenticationRequestFilter`.
  14. Or, if you've <<servlet-saml2login-relyingpartyregistrationrepository,configured more than one asserting party>>, it will first redirect to a picker page.
  15. 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`>>.
  16. image:{icondir}/number_5.png[] Then, the browser takes this `<saml2:AuthnRequest>` and presents it to the asserting party.
  17. The asserting party attempts to authentication the user.
  18. If successful, it will return a `<saml2:Response>` back to the browser.
  19. image:{icondir}/number_6.png[] The browser then POSTs the `<saml2:Response>` to the assertion consumer service endpoint.
  20. [[servlet-saml2login-authentication-saml2webssoauthenticationfilter]]
  21. .Authenticating a `<saml2:Response>`
  22. image::{figures}/saml2webssoauthenticationfilter.png[]
  23. The figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram.
  24. [[servlet-saml2login-authentication-saml2authenticationtokenconverter]]
  25. image:{icondir}/number_1.png[] When the browser submits a `<saml2:Response>` to the application, it xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-authenticate-responses[delegates to `Saml2WebSsoAuthenticationFilter`].
  26. This filter calls its configured `AuthenticationConverter` to create a `Saml2AuthenticationToken` by extracting the response from the `HttpServletRequest`.
  27. This converter additionally resolves the <<servlet-saml2login-relyingpartyregistration, `RelyingPartyRegistration`>> and supplies it to `Saml2AuthenticationToken`.
  28. image:{icondir}/number_2.png[] Next, the filter passes the token to its configured xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`].
  29. By default, it will use the <<servlet-saml2login-architecture,`OpenSAML authentication provider`>>.
  30. image:{icondir}/number_3.png[] If authentication fails, then __Failure__
  31. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] is cleared out.
  32. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is invoked to restart the authentication process.
  33. image:{icondir}/number_4.png[] If authentication is successful, then __Success__.
  34. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`].
  35. * The `Saml2WebSsoAuthenticationFilter` invokes `FilterChain#doFilter(request,response)` to continue with the rest of the application logic.
  36. [[servlet-saml2login-minimaldependencies]]
  37. == Minimal Dependencies
  38. SAML 2.0 service provider support resides in `spring-security-saml2-service-provider`.
  39. It builds off of the OpenSAML library.
  40. [[servlet-saml2login-minimalconfiguration]]
  41. == Minimal Configuration
  42. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a service provider consists of two basic steps.
  43. First, include the needed dependencies and second, indicate the necessary asserting party metadata.
  44. [NOTE]
  45. Also, this presupposes that you've already xref:servlet/saml2/metadata.adoc#servlet-saml2login-metadata[registered the relying party with your asserting party].
  46. === Specifying Identity Provider Metadata
  47. In a Spring Boot application, to specify an identity provider's metadata, simply do:
  48. [source,yml]
  49. ----
  50. spring:
  51. security:
  52. saml2:
  53. relyingparty:
  54. registration:
  55. adfs:
  56. identityprovider:
  57. entity-id: https://idp.example.com/issuer
  58. verification.credentials:
  59. - certificate-location: "classpath:idp.crt"
  60. singlesignon.url: https://idp.example.com/issuer/sso
  61. singlesignon.sign-request: false
  62. ----
  63. where
  64. * `https://idp.example.com/issuer` is the value contained in the `Issuer` attribute of the SAML responses that the identity provider will issue
  65. * `classpath:idp.crt` is the location on the classpath for the identity provider's certificate for verifying SAML responses, and
  66. * `https://idp.example.com/issuer/sso` is the endpoint where the identity provider is expecting ``AuthnRequest``s.
  67. * `adfs` is <<servlet-saml2login-relyingpartyregistrationid, an arbitrary identifier you choose>>
  68. And that's it!
  69. [NOTE]
  70. Identity Provider and Asserting Party are synonymous, as are Service Provider and Relying Party.
  71. These are frequently abbreviated as AP and RP, respectively.
  72. === Runtime Expectations
  73. As configured above, the application processes any `+POST /login/saml2/sso/{registrationId}+` request containing a `SAMLResponse` parameter:
  74. [source,html]
  75. ----
  76. POST /login/saml2/sso/adfs HTTP/1.1
  77. SAMLResponse=PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZ...
  78. ----
  79. There are two ways to see induce your asserting party to generate a `SAMLResponse`:
  80. * First, you can navigate to your asserting party.
  81. It likely has some kind of link or button for each registered relying party that you can click to send the `SAMLResponse`.
  82. * Second, you can navigate to a protected page in your app, for example, `http://localhost:8080`.
  83. Your app then redirects to the configured asserting party which then sends the `SAMLResponse`.
  84. From here, consider jumping to:
  85. * <<servlet-saml2login-architecture,How SAML 2.0 Login Integrates with OpenSAML>>
  86. * xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-authenticatedprincipal[How to Use the `Saml2AuthenticatedPrincipal`]
  87. * <<servlet-saml2login-sansboot,How to Override or Replace Spring Boot's Auto Configuration>>
  88. [[servlet-saml2login-architecture]]
  89. == How SAML 2.0 Login Integrates with OpenSAML
  90. Spring Security's SAML 2.0 support has a couple of design goals:
  91. * First, rely on a library for SAML 2.0 operations and domain objects.
  92. To achieve this, Spring Security uses OpenSAML.
  93. * Second, ensure this library is not required when using Spring Security's SAML support.
  94. To achieve this, any interfaces or classes where Spring Security uses OpenSAML in the contract remain encapsulated.
  95. This makes it possible for you to switch out OpenSAML for some other library or even an unsupported version of OpenSAML.
  96. As a natural outcome of the above two goals, Spring Security's SAML API is quite small relative to other modules.
  97. Instead, classes like `OpenSaml4AuthenticationRequestFactory` and `OpenSaml4AuthenticationProvider` expose ``Converter``s that customize various steps in the authentication process.
  98. For example, once your application receives a `SAMLResponse` and delegates to `Saml2WebSsoAuthenticationFilter`, the filter will delegate to `OpenSaml4AuthenticationProvider`.
  99. [NOTE]
  100. For backward compatibility, Spring Security will use the latest OpenSAML 3 by default.
  101. Note, though that OpenSAML 3 has reached it's end-of-life and updating to OpenSAML 4.x is recommended.
  102. For that reason, Spring Security supports both OpenSAML 3.x and 4.x.
  103. If you manage your OpenSAML dependency to 4.x, then Spring Security will select its OpenSAML 4.x implementations.
  104. .Authenticating an OpenSAML `Response`
  105. image:{figures}/opensamlauthenticationprovider.png[]
  106. This figure builds off of the <<servlet-saml2login-authentication-saml2webssoauthenticationfilter,`Saml2WebSsoAuthenticationFilter` diagram>>.
  107. image:{icondir}/number_1.png[] The `Saml2WebSsoAuthenticationFilter` formulates the `Saml2AuthenticationToken` and invokes the xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`].
  108. image:{icondir}/number_2.png[] The xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`] invokes the OpenSAML authentication provider.
  109. image:{icondir}/number_3.png[] The authentication provider deserializes the response into an OpenSAML `Response` and checks its signature.
  110. If the signature is invalid, authentication fails.
  111. image:{icondir}/number_4.png[] Then, the provider xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-opensamlauthenticationprovider-decryption[decrypts any `EncryptedAssertion` elements].
  112. If any decryptions fail, authentication fails.
  113. image:{icondir}/number_5.png[] Next, the provider validates the response's `Issuer` and `Destination` values.
  114. If they don't match what's in the `RelyingPartyRegistration`, authentication fails.
  115. image:{icondir}/number_6.png[] After that, the provider verifies the signature of each `Assertion`.
  116. If any signature is invalid, authentication fails.
  117. Also, if neither the response nor the assertions have signatures, authentication fails.
  118. Either the response or all the assertions must have signatures.
  119. image:{icondir}/number_7.png[] Then, the provider xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-opensamlauthenticationprovider-decryption[,]decrypts any `EncryptedID` or `EncryptedAttribute` elements].
  120. If any decryptions fail, authentication fails.
  121. image:{icondir}/number_8.png[] Next, the provider validates each assertion's `ExpiresAt` and `NotBefore` timestamps, the `<Subject>` and any `<AudienceRestriction>` conditions.
  122. If any validations fail, authentication fails.
  123. image:{icondir}/number_9.png[] Following that, the provider takes the first assertion's `AttributeStatement` and maps it to a `Map<String, List<Object>>`.
  124. It also grants the `ROLE_USER` granted authority.
  125. 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`.
  126. Then, it places that principal and the authorities into a `Saml2Authentication`.
  127. The resulting `Authentication#getPrincipal` is a Spring Security `Saml2AuthenticatedPrincipal` object, and `Authentication#getName` maps to the first assertion's `NameID` element.
  128. `Saml2AuthenticatedPrincipal#getRelyingPartyRegistrationId` holds the <<servlet-saml2login-relyingpartyregistrationid,identifier to the associated `RelyingPartyRegistration`>>.
  129. [[servlet-saml2login-opensaml-customization]]
  130. === Customizing OpenSAML Configuration
  131. Any class that uses both Spring Security and OpenSAML should statically initialize `OpenSamlInitializationService` at the beginning of the class, like so:
  132. ====
  133. .Java
  134. [source,java,role="primary"]
  135. ----
  136. static {
  137. OpenSamlInitializationService.initialize();
  138. }
  139. ----
  140. .Kotlin
  141. [source,kotlin,role="secondary"]
  142. ----
  143. companion object {
  144. init {
  145. OpenSamlInitializationService.initialize()
  146. }
  147. }
  148. ----
  149. ====
  150. This replaces OpenSAML's `InitializationService#initialize`.
  151. Occasionally, it can be valuable to customize how OpenSAML builds, marshalls, and unmarshalls SAML objects.
  152. In these circumstances, you may instead want to call `OpenSamlInitializationService#requireInitialize(Consumer)` that gives you access to OpenSAML's `XMLObjectProviderFactory`.
  153. For example, when sending an unsigned AuthNRequest, you may want to force reauthentication.
  154. In that case, you can register your own `AuthnRequestMarshaller`, like so:
  155. ====
  156. .Java
  157. [source,java,role="primary"]
  158. ----
  159. static {
  160. OpenSamlInitializationService.requireInitialize(factory -> {
  161. AuthnRequestMarshaller marshaller = new AuthnRequestMarshaller() {
  162. @Override
  163. public Element marshall(XMLObject object, Element element) throws MarshallingException {
  164. configureAuthnRequest((AuthnRequest) object);
  165. return super.marshall(object, element);
  166. }
  167. public Element marshall(XMLObject object, Document document) throws MarshallingException {
  168. configureAuthnRequest((AuthnRequest) object);
  169. return super.marshall(object, document);
  170. }
  171. private void configureAuthnRequest(AuthnRequest authnRequest) {
  172. authnRequest.setForceAuthn(true);
  173. }
  174. }
  175. factory.getMarshallerFactory().registerMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME, marshaller);
  176. });
  177. }
  178. ----
  179. .Kotlin
  180. [source,kotlin,role="secondary"]
  181. ----
  182. companion object {
  183. init {
  184. OpenSamlInitializationService.requireInitialize {
  185. val marshaller = object : AuthnRequestMarshaller() {
  186. override fun marshall(xmlObject: XMLObject, element: Element): Element {
  187. configureAuthnRequest(xmlObject as AuthnRequest)
  188. return super.marshall(xmlObject, element)
  189. }
  190. override fun marshall(xmlObject: XMLObject, document: Document): Element {
  191. configureAuthnRequest(xmlObject as AuthnRequest)
  192. return super.marshall(xmlObject, document)
  193. }
  194. private fun configureAuthnRequest(authnRequest: AuthnRequest) {
  195. authnRequest.isForceAuthn = true
  196. }
  197. }
  198. it.marshallerFactory.registerMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME, marshaller)
  199. }
  200. }
  201. }
  202. ----
  203. ====
  204. The `requireInitialize` method may only be called once per application instance.
  205. [[servlet-saml2login-sansboot]]
  206. == Overriding or Replacing Boot Auto Configuration
  207. There are two ``@Bean``s that Spring Boot generates for a relying party.
  208. The first is a `SecurityFilterChain` that configures the app as a relying party.
  209. When including `spring-security-saml2-service-provider`, the `SecurityFilterChain` looks like:
  210. .Default SAML 2.0 Login Configuration
  211. ====
  212. .Java
  213. [source,java,role="primary"]
  214. ----
  215. @Bean
  216. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  217. http
  218. .authorizeHttpRequests(authorize -> authorize
  219. .anyRequest().authenticated()
  220. )
  221. .saml2Login(withDefaults());
  222. return http.build();
  223. }
  224. ----
  225. .Kotlin
  226. [source,kotlin,role="secondary"]
  227. ----
  228. @Bean
  229. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  230. http {
  231. authorizeRequests {
  232. authorize(anyRequest, authenticated)
  233. }
  234. saml2Login { }
  235. }
  236. return http.build()
  237. }
  238. ----
  239. ====
  240. If the application doesn't expose a `SecurityFilterChain` bean, then Spring Boot will expose the above default one.
  241. You can replace this by exposing the bean within the application:
  242. .Custom SAML 2.0 Login Configuration
  243. ====
  244. .Java
  245. [source,java,role="primary"]
  246. ----
  247. @EnableWebSecurity
  248. public class MyCustomSecurityConfiguration {
  249. @Bean
  250. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  251. http
  252. .authorizeHttpRequests(authorize -> authorize
  253. .requestMatchers("/messages/**").hasAuthority("ROLE_USER")
  254. .anyRequest().authenticated()
  255. )
  256. .saml2Login(withDefaults());
  257. return http.build();
  258. }
  259. }
  260. ----
  261. .Kotlin
  262. [source,kotlin,role="secondary"]
  263. ----
  264. @EnableWebSecurity
  265. class MyCustomSecurityConfiguration {
  266. @Bean
  267. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  268. http {
  269. authorizeRequests {
  270. authorize("/messages/**", hasAuthority("ROLE_USER"))
  271. authorize(anyRequest, authenticated)
  272. }
  273. saml2Login {
  274. }
  275. }
  276. return http.build()
  277. }
  278. }
  279. ----
  280. ====
  281. The above requires the role of `USER` for any URL that starts with `/messages/`.
  282. [[servlet-saml2login-relyingpartyregistrationrepository]]
  283. 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.
  284. This includes things like the location of the SSO endpoint the relying party should use when requesting authentication from the asserting party.
  285. You can override the default by publishing your own `RelyingPartyRegistrationRepository` bean.
  286. For example, you can look up the asserting party's configuration by hitting its metadata endpoint like so:
  287. .Relying Party Registration Repository
  288. ====
  289. .Java
  290. [source,java,role="primary"]
  291. ----
  292. @Value("${metadata.location}")
  293. String assertingPartyMetadataLocation;
  294. @Bean
  295. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  296. RelyingPartyRegistration registration = RelyingPartyRegistrations
  297. .fromMetadataLocation(assertingPartyMetadataLocation)
  298. .registrationId("example")
  299. .build();
  300. return new InMemoryRelyingPartyRegistrationRepository(registration);
  301. }
  302. ----
  303. .Kotlin
  304. [source,kotlin,role="secondary"]
  305. ----
  306. @Value("\${metadata.location}")
  307. var assertingPartyMetadataLocation: String? = null
  308. @Bean
  309. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  310. val registration = RelyingPartyRegistrations
  311. .fromMetadataLocation(assertingPartyMetadataLocation)
  312. .registrationId("example")
  313. .build()
  314. return InMemoryRelyingPartyRegistrationRepository(registration)
  315. }
  316. ----
  317. ====
  318. [[servlet-saml2login-relyingpartyregistrationid]]
  319. [NOTE]
  320. The `registrationId` is an arbitrary value that you choose for differentiating between registrations.
  321. Or you can provide each detail manually, as you can see below:
  322. .Relying Party Registration Repository Manual Configuration
  323. ====
  324. .Java
  325. [source,java,role="primary"]
  326. ----
  327. @Value("${verification.key}")
  328. File verificationKey;
  329. @Bean
  330. public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception {
  331. X509Certificate certificate = X509Support.decodeCertificate(this.verificationKey);
  332. Saml2X509Credential credential = Saml2X509Credential.verification(certificate);
  333. RelyingPartyRegistration registration = RelyingPartyRegistration
  334. .withRegistrationId("example")
  335. .assertingPartyDetails(party -> party
  336. .entityId("https://idp.example.com/issuer")
  337. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  338. .wantAuthnRequestsSigned(false)
  339. .verificationX509Credentials(c -> c.add(credential))
  340. )
  341. .build();
  342. return new InMemoryRelyingPartyRegistrationRepository(registration);
  343. }
  344. ----
  345. .Kotlin
  346. [source,kotlin,role="secondary"]
  347. ----
  348. @Value("\${verification.key}")
  349. var verificationKey: File? = null
  350. @Bean
  351. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository {
  352. val certificate: X509Certificate? = X509Support.decodeCertificate(verificationKey!!)
  353. val credential: Saml2X509Credential = Saml2X509Credential.verification(certificate)
  354. val registration = RelyingPartyRegistration
  355. .withRegistrationId("example")
  356. .assertingPartyDetails { party: AssertingPartyDetails.Builder ->
  357. party
  358. .entityId("https://idp.example.com/issuer")
  359. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  360. .wantAuthnRequestsSigned(false)
  361. .verificationX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  362. c.add(
  363. credential
  364. )
  365. }
  366. }
  367. .build()
  368. return InMemoryRelyingPartyRegistrationRepository(registration)
  369. }
  370. ----
  371. ====
  372. [NOTE]
  373. Note that `X509Support` is an OpenSAML class, used here in the snippet for brevity
  374. [[servlet-saml2login-relyingpartyregistrationrepository-dsl]]
  375. Alternatively, you can directly wire up the repository using the DSL, which will also override the auto-configured `SecurityFilterChain`:
  376. .Custom Relying Party Registration DSL
  377. ====
  378. .Java
  379. [source,java,role="primary"]
  380. ----
  381. @EnableWebSecurity
  382. public class MyCustomSecurityConfiguration {
  383. @Bean
  384. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  385. http
  386. .authorizeHttpRequests(authorize -> authorize
  387. .requestMatchers("/messages/**").hasAuthority("ROLE_USER")
  388. .anyRequest().authenticated()
  389. )
  390. .saml2Login(saml2 -> saml2
  391. .relyingPartyRegistrationRepository(relyingPartyRegistrations())
  392. );
  393. return http.build();
  394. }
  395. }
  396. ----
  397. .Kotlin
  398. [source,kotlin,role="secondary"]
  399. ----
  400. @EnableWebSecurity
  401. class MyCustomSecurityConfiguration {
  402. @Bean
  403. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  404. http {
  405. authorizeRequests {
  406. authorize("/messages/**", hasAuthority("ROLE_USER"))
  407. authorize(anyRequest, authenticated)
  408. }
  409. saml2Login {
  410. relyingPartyRegistrationRepository = relyingPartyRegistrations()
  411. }
  412. }
  413. return http.build()
  414. }
  415. }
  416. ----
  417. ====
  418. [NOTE]
  419. A relying party can be multi-tenant by registering more than one relying party in the `RelyingPartyRegistrationRepository`.
  420. [[servlet-saml2login-relyingpartyregistration]]
  421. == RelyingPartyRegistration
  422. A {security-api-url}org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.html[`RelyingPartyRegistration`]
  423. instance represents a link between an relying party and assering party's metadata.
  424. 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.
  425. 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.
  426. The following `RelyingPartyRegistration` is the minimum required for most setups:
  427. ====
  428. .Java
  429. [source,java,role="primary"]
  430. ----
  431. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
  432. .fromMetadataLocation("https://ap.example.org/metadata")
  433. .registrationId("my-id")
  434. .build();
  435. ----
  436. .Kotlin
  437. [source,kotlin,role="secondary"]
  438. ----
  439. val relyingPartyRegistration = RelyingPartyRegistrations
  440. .fromMetadataLocation("https://ap.example.org/metadata")
  441. .registrationId("my-id")
  442. .build()
  443. ----
  444. ====
  445. Note that you can also create a `RelyingPartyRegistration` from an arbitrary `InputStream` source.
  446. One such example is when the metadata is stored in a database:
  447. [source,java]
  448. ----
  449. String xml = fromDatabase();
  450. try (InputStream source = new ByteArrayInputStream(xml.getBytes())) {
  451. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
  452. .fromMetadata(source)
  453. .registrationId("my-id")
  454. .build();
  455. }
  456. ----
  457. Though a more sophisticated setup is also possible, like so:
  458. ====
  459. .Java
  460. [source,java,role="primary"]
  461. ----
  462. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("my-id")
  463. .entityId("{baseUrl}/{registrationId}")
  464. .decryptionX509Credentials(c -> c.add(relyingPartyDecryptingCredential()))
  465. .assertionConsumerServiceLocation("/my-login-endpoint/{registrationId}")
  466. .assertingPartyDetails(party -> party
  467. .entityId("https://ap.example.org")
  468. .verificationX509Credentials(c -> c.add(assertingPartyVerifyingCredential()))
  469. .singleSignOnServiceLocation("https://ap.example.org/SSO.saml2")
  470. )
  471. .build();
  472. ----
  473. .Kotlin
  474. [source,kotlin,role="secondary"]
  475. ----
  476. val relyingPartyRegistration =
  477. RelyingPartyRegistration.withRegistrationId("my-id")
  478. .entityId("{baseUrl}/{registrationId}")
  479. .decryptionX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  480. c.add(relyingPartyDecryptingCredential())
  481. }
  482. .assertionConsumerServiceLocation("/my-login-endpoint/{registrationId}")
  483. .assertingPartyDetails { party -> party
  484. .entityId("https://ap.example.org")
  485. .verificationX509Credentials { c -> c.add(assertingPartyVerifyingCredential()) }
  486. .singleSignOnServiceLocation("https://ap.example.org/SSO.saml2")
  487. }
  488. .build()
  489. ----
  490. ====
  491. [TIP]
  492. The top-level metadata methods are details about the relying party.
  493. The methods inside `assertingPartyDetails` are details about the asserting party.
  494. [NOTE]
  495. The location where a relying party is expecting SAML Responses is the Assertion Consumer Service Location.
  496. The default for the relying party's `entityId` is `+{baseUrl}/saml2/service-provider-metadata/{registrationId}+`.
  497. This is this value needed when configuring the asserting party to know about your relying party.
  498. The default for the `assertionConsumerServiceLocation` is `+/login/saml2/sso/{registrationId}+`.
  499. It's mapped by default to <<servlet-saml2login-authentication-saml2webssoauthenticationfilter,`Saml2WebSsoAuthenticationFilter`>> in the filter chain.
  500. [[servlet-saml2login-rpr-uripatterns]]
  501. === URI Patterns
  502. You probably noticed in the above examples the `+{baseUrl}+` and `+{registrationId}+` placeholders.
  503. These are useful for generating URIs. As such, the relying party's `entityId` and `assertionConsumerServiceLocation` support the following placeholders:
  504. * `baseUrl` - the scheme, host, and port of a deployed application
  505. * `registrationId` - the registration id for this relying party
  506. * `baseScheme` - the scheme of a deployed application
  507. * `baseHost` - the host of a deployed application
  508. * `basePort` - the port of a deployed application
  509. For example, the `assertionConsumerServiceLocation` defined above was:
  510. `+/my-login-endpoint/{registrationId}+`
  511. which in a deployed application would translate to
  512. `+/my-login-endpoint/adfs+`
  513. The `entityId` above was defined as:
  514. `+{baseUrl}/{registrationId}+`
  515. which in a deployed application would translate to
  516. `+https://rp.example.com/adfs+`
  517. The prevailing URI patterns are as follows:
  518. * `+/saml2/authenticate/{registrationId}+` - The endpoint that xref:servlet/saml2/login/authentication-requests.adoc[generates a `<saml2:AuthnRequest>`] based on the configurations for that `RelyingPartyRegistration` and sends it to the asserting party
  519. * `+/saml2/login/sso/{registrationId}+` - The endpoint that xref:servlet/saml2/login/authentication.adoc[authenticates an asserting party's `<saml2:Response>`] based on the configurations for that `RelyingPartyRegistration`
  520. * `+/saml2/logout/sso+` - The endpoint that xref:servlet/saml2/logout.adoc[processes `<saml2:LogoutRequest>` and `<saml2:LogoutResponse>` payloads]; the `RelyingPartyRegistration` is looked up from previously authenticated state
  521. * `+/saml2/saml2-service-provider/metadata/{registrationId}+` - The xref:servlet/saml2/metadata.adoc[relying party metadata] for that `RelyingPartyRegistration`
  522. Since the `registrationId` is the primary identifier for a `RelyingPartyRegistration`, it is needed in the URL for unauthenticated scenarios.
  523. If you wish to remove the `registrationId` from the URL for any reason, you can <<servlet-saml2login-rpr-relyingpartyregistrationresolver,specify a `RelyingPartyRegistrationResolver`>> to tell Spring Security how to look up the `registrationId`.
  524. [[servlet-saml2login-rpr-credentials]]
  525. === Credentials
  526. You also likely noticed the credential that was used.
  527. Oftentimes, a relying party will use the same key to sign payloads as well as decrypt them.
  528. Or it will use the same key to verify payloads as well as encrypt them.
  529. Because of this, Spring Security ships with `Saml2X509Credential`, a SAML-specific credential that simplifies configuring the same key for different use cases.
  530. 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.
  531. To construct a `Saml2X509Credential` that you'll use to verify assertions from the asserting party, you can load the file and use
  532. the `CertificateFactory` like so:
  533. ====
  534. .Java
  535. [source,java,role="primary"]
  536. ----
  537. Resource resource = new ClassPathResource("ap.crt");
  538. try (InputStream is = resource.getInputStream()) {
  539. X509Certificate certificate = (X509Certificate)
  540. CertificateFactory.getInstance("X.509").generateCertificate(is);
  541. return Saml2X509Credential.verification(certificate);
  542. }
  543. ----
  544. .Kotlin
  545. [source,kotlin,role="secondary"]
  546. ----
  547. val resource = ClassPathResource("ap.crt")
  548. resource.inputStream.use {
  549. return Saml2X509Credential.verification(
  550. CertificateFactory.getInstance("X.509").generateCertificate(it) as X509Certificate?
  551. )
  552. }
  553. ----
  554. ====
  555. Let's say that the asserting party is going to also encrypt the assertion.
  556. In that case, the relying party will need a private key to be able to decrypt the encrypted value.
  557. In that case, you'll need an `RSAPrivateKey` as well as its corresponding `X509Certificate`.
  558. You can load the first using Spring Security's `RsaKeyConverters` utility class and the second as you did before:
  559. ====
  560. .Java
  561. [source,java,role="primary"]
  562. ----
  563. X509Certificate certificate = relyingPartyDecryptionCertificate();
  564. Resource resource = new ClassPathResource("rp.crt");
  565. try (InputStream is = resource.getInputStream()) {
  566. RSAPrivateKey rsa = RsaKeyConverters.pkcs8().convert(is);
  567. return Saml2X509Credential.decryption(rsa, certificate);
  568. }
  569. ----
  570. .Kotlin
  571. [source,kotlin,role="secondary"]
  572. ----
  573. val certificate: X509Certificate = relyingPartyDecryptionCertificate()
  574. val resource = ClassPathResource("rp.crt")
  575. resource.inputStream.use {
  576. val rsa: RSAPrivateKey = RsaKeyConverters.pkcs8().convert(it)
  577. return Saml2X509Credential.decryption(rsa, certificate)
  578. }
  579. ----
  580. ====
  581. [TIP]
  582. When you specify the locations of these files as the appropriate Spring Boot properties, then Spring Boot will perform these conversions for you.
  583. [[servlet-saml2login-rpr-duplicated]]
  584. === Duplicated Relying Party Configurations
  585. When an application uses multiple asserting parties, some configuration is duplicated between `RelyingPartyRegistration` instances:
  586. * The relying party's `entityId`
  587. * Its `assertionConsumerServiceLocation`, and
  588. * Its credentials, for example its signing or decryption credentials
  589. What's nice about this setup is credentials may be more easily rotated for some identity providers vs others.
  590. The duplication can be alleviated in a few different ways.
  591. First, in YAML this can be alleviated with references, like so:
  592. [source,yaml]
  593. ----
  594. spring:
  595. security:
  596. saml2:
  597. relyingparty:
  598. okta:
  599. signing.credentials: &relying-party-credentials
  600. - private-key-location: classpath:rp.key
  601. certificate-location: classpath:rp.crt
  602. identityprovider:
  603. entity-id: ...
  604. azure:
  605. signing.credentials: *relying-party-credentials
  606. identityprovider:
  607. entity-id: ...
  608. ----
  609. Second, in a database, it's not necessary to replicate `RelyingPartyRegistration` 's model.
  610. Third, in Java, you can create a custom configuration method, like so:
  611. ====
  612. .Java
  613. [source,java,role="primary"]
  614. ----
  615. private RelyingPartyRegistration.Builder
  616. addRelyingPartyDetails(RelyingPartyRegistration.Builder builder) {
  617. Saml2X509Credential signingCredential = ...
  618. builder.signingX509Credentials(c -> c.addAll(signingCredential));
  619. // ... other relying party configurations
  620. }
  621. @Bean
  622. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  623. RelyingPartyRegistration okta = addRelyingPartyDetails(
  624. RelyingPartyRegistrations
  625. .fromMetadataLocation(oktaMetadataUrl)
  626. .registrationId("okta")).build();
  627. RelyingPartyRegistration azure = addRelyingPartyDetails(
  628. RelyingPartyRegistrations
  629. .fromMetadataLocation(oktaMetadataUrl)
  630. .registrationId("azure")).build();
  631. return new InMemoryRelyingPartyRegistrationRepository(okta, azure);
  632. }
  633. ----
  634. .Kotlin
  635. [source,kotlin,role="secondary"]
  636. ----
  637. private fun addRelyingPartyDetails(builder: RelyingPartyRegistration.Builder): RelyingPartyRegistration.Builder {
  638. val signingCredential: Saml2X509Credential = ...
  639. builder.signingX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  640. c.add(
  641. signingCredential
  642. )
  643. }
  644. // ... other relying party configurations
  645. }
  646. @Bean
  647. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  648. val okta = addRelyingPartyDetails(
  649. RelyingPartyRegistrations
  650. .fromMetadataLocation(oktaMetadataUrl)
  651. .registrationId("okta")
  652. ).build()
  653. val azure = addRelyingPartyDetails(
  654. RelyingPartyRegistrations
  655. .fromMetadataLocation(oktaMetadataUrl)
  656. .registrationId("azure")
  657. ).build()
  658. return InMemoryRelyingPartyRegistrationRepository(okta, azure)
  659. }
  660. ----
  661. ====
  662. [[servlet-saml2login-rpr-relyingpartyregistrationresolver]]
  663. === Resolving the `RelyingPartyRegistration` from the Request
  664. As seen so far, Spring Security resolves the `RelyingPartyRegistration` by looking for the registration id in the URI path.
  665. There are a number of reasons you may want to customize that. Among them:
  666. * You may already <<relyingpartyregistrationresolver-single, know which `RelyingPartyRegistration` you need>>
  667. * You may be <<relyingpartyregistrationresolver-entityid, federating many asserting parties>>
  668. To customize the way that a `RelyingPartyRegistration` is resolved, you can configure a custom `RelyingPartyRegistrationResolver`.
  669. The default looks up the registration id from the URI's last path element and looks it up in your `RelyingPartyRegistrationRepository`.
  670. [NOTE]
  671. Remember that if you have any placeholders in your `RelyingPartyRegistration`, your resolver implementation should resolve them.
  672. [[relyingpartyregistrationresolver-single]]
  673. ==== Resolving to a Single Consistent `RelyingPartyRegistration`
  674. You can provide a resolver that, for example, always returns the same `RelyingPartyRegistration`:
  675. ====
  676. .Java
  677. [source,java,role="primary"]
  678. ----
  679. public class SingleRelyingPartyRegistrationResolver implements RelyingPartyRegistrationResolver {
  680. private final RelyingPartyRegistrationResolver delegate;
  681. public SingleRelyingPartyRegistrationResolver(RelyingPartyRegistrationRepository registrations) {
  682. this.delegate = new DefaultRelyingPartyRegistrationResolver(registrations);
  683. }
  684. @Override
  685. public RelyingPartyRegistration resolve(HttpServletRequest request, String registrationId) {
  686. return this.delegate.resolve(request, "single");
  687. }
  688. }
  689. ----
  690. .Kotlin
  691. [source,kotlin,role="secondary"]
  692. ----
  693. class SingleRelyingPartyRegistrationResolver(delegate: RelyingPartyRegistrationResolver) : RelyingPartyRegistrationResolver {
  694. override fun resolve(request: HttpServletRequest?, registrationId: String?): RelyingPartyRegistration? {
  695. return this.delegate.resolve(request, "single")
  696. }
  697. }
  698. ----
  699. ====
  700. [TIP]
  701. You might next take a look at how to use this resolver to customize xref:servlet/saml2/metadata.adoc#servlet-saml2login-metadata[`<saml2:SPSSODescriptor>` metadata production].
  702. [[relyingpartyregistrationresolver-entityid]]
  703. ==== Resolving Based on the `<saml2:Response#Issuer>`
  704. When you have one relying party that can accept assertions from multiple asserting parties, you will have as many ``RelyingPartyRegistration``s as asserting parties, with the <<servlet-saml2login-rpr-duplicated, relying party information duplicated across each instance>>.
  705. This carries the implication that the assertion consumer service endpoint will be different for each asserting party, which may not be desirable.
  706. You can instead resolve the `registrationId` via the `Issuer`.
  707. A custom implementation of `RelyingPartyRegistrationResolver` that does this may look like:
  708. ====
  709. .Java
  710. [source,java,role="primary"]
  711. ----
  712. public class SamlResponseIssuerRelyingPartyRegistrationResolver implements RelyingPartyRegistrationResolver {
  713. private final InMemoryRelyingPartyRegistrationRepository registrations;
  714. // ... constructor
  715. @Override
  716. RelyingPartyRegistration resolve(HttpServletRequest request, String registrationId) {
  717. if (registrationId != null) {
  718. return this.registrations.findByRegistrationId(registrationId);
  719. }
  720. String entityId = resolveEntityIdFromSamlResponse(request);
  721. for (RelyingPartyRegistration registration : this.registrations) {
  722. if (registration.getAssertingPartyDetails().getEntityId().equals(entityId)) {
  723. return registration;
  724. }
  725. }
  726. return null;
  727. }
  728. private String resolveEntityIdFromSamlResponse(HttpServletRequest request) {
  729. // ...
  730. }
  731. }
  732. ----
  733. .Kotlin
  734. [source,kotlin,role="secondary"]
  735. ----
  736. class SamlResponseIssuerRelyingPartyRegistrationResolver(val registrations: InMemoryRelyingPartyRegistrationRepository):
  737. RelyingPartyRegistrationResolver {
  738. @Override
  739. fun resolve(val request: HttpServletRequest, val registrationId: String): RelyingPartyRegistration {
  740. if (registrationId != null) {
  741. return this.registrations.findByRegistrationId(registrationId)
  742. }
  743. String entityId = resolveEntityIdFromSamlResponse(request)
  744. for (val registration : this.registrations) {
  745. if (registration.getAssertingPartyDetails().getEntityId().equals(entityId)) {
  746. return registration
  747. }
  748. }
  749. return null
  750. }
  751. private resolveEntityIdFromSamlResponse(val request: HttpServletRequest): String {
  752. // ...
  753. }
  754. }
  755. ----
  756. ====
  757. [TIP]
  758. You might next take a look at how to use this resolver to customize xref:servlet/saml2/login/authentication.adoc#relyingpartyregistrationresolver-apply[`<saml2:Response>` authentication].
  759. [[federating-saml2-login]]
  760. === Federating Login
  761. One common arrangement with SAML 2.0 is an identity provider that has multiple asserting parties.
  762. In this case, the identity provider's metadata endpoint returns multiple `<md:IDPSSODescriptor>` elements.
  763. These multiple asserting parties can be accessed in a single call to `RelyingPartyRegistrations` like so:
  764. ====
  765. .Java
  766. [source,java,role="primary"]
  767. ----
  768. Collection<RelyingPartyRegistration> registrations = RelyingPartyRegistrations
  769. .collectionFromMetadataLocation("https://example.org/saml2/idp/metadata.xml")
  770. .stream().map((builder) -> builder
  771. .registrationId(UUID.randomUUID().toString())
  772. .entityId("https://example.org/saml2/sp")
  773. .build()
  774. )
  775. .collect(Collectors.toList()));
  776. ----
  777. .Kotlin
  778. [source,java,role="secondary"]
  779. ----
  780. var registrations: Collection<RelyingPartyRegistration> = RelyingPartyRegistrations
  781. .collectionFromMetadataLocation("https://example.org/saml2/idp/metadata.xml")
  782. .stream().map { builder : RelyingPartyRegistration.Builder -> builder
  783. .registrationId(UUID.randomUUID().toString())
  784. .entityId("https://example.org/saml2/sp")
  785. .build()
  786. }
  787. .collect(Collectors.toList()));
  788. ----
  789. ====
  790. Note that because the registration id is set to a random value, this will change certain SAML 2.0 endpoints to be unpredictable.
  791. There are several ways to address this; let's focus on a way that suits the specific use case of federation.
  792. In many federation cases, all the asserting parties share service provider configuration.
  793. Given that Spring Security will by default include the `registrationId` in all many of its SAML 2.0 URIs, the next step is often to change these URIs to exclude the `registrationId`.
  794. There are two main URIs you will want to change along those lines:
  795. * <<relyingpartyregistrationresolver-entityid,Resolve by `<saml2:Response#Issuer>`>>
  796. * <<relyingpartyregistrationresolver-single,Resolve with a default `RelyingPartyRegistration`>>
  797. [NOTE]
  798. Optionally, you may also want to change the Authentication Request location, but since this is a URI internal to the app and not published to asserting parties, the benefit is often minimal.
  799. You can see a completed example of this in {gh-samples-url}/servlet/spring-boot/java/saml2/saml-extension-federation[our `saml-extension-federation` sample].
  800. [[using-spring-security-saml-extension-uris]]
  801. === Using Spring Security SAML Extension URIs
  802. In the event that you are migrating from the Spring Security SAML Extension, there may be some benefit to configuring your application to use the SAML Extension URI defaults.
  803. For more information on this, please see {gh-samples-url}/servlet/spring-boot/java/saml2/custom-urls[our `custom-urls` sample] and {gh-samples-url}/servlet/spring-boot/java/saml2/saml-extension-federation[our `saml-extension-federation` sample].