overview.adoc 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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. 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`].
  25. This filter calls its configured `AuthenticationConverter` to create a `Saml2AuthenticationToken` by extracting the response from the `HttpServletRequest`.
  26. This converter additionally resolves the <<servlet-saml2login-relyingpartyregistration, `RelyingPartyRegistration`>> and supplies it to `Saml2AuthenticationToken`.
  27. image:{icondir}/number_2.png[] Next, the filter passes the token to its configured xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`].
  28. By default, it will use the <<servlet-saml2login-architecture,`OpenSAML authentication provider`>>.
  29. image:{icondir}/number_3.png[] If authentication fails, then __Failure__
  30. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] is cleared out.
  31. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is invoked to restart the authentication process.
  32. image:{icondir}/number_4.png[] If authentication is successful, then __Success__.
  33. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`].
  34. * The `Saml2WebSsoAuthenticationFilter` invokes `FilterChain#doFilter(request,response)` to continue with the rest of the application logic.
  35. [[servlet-saml2login-minimaldependencies]]
  36. == Minimal Dependencies
  37. SAML 2.0 service provider support resides in `spring-security-saml2-service-provider`.
  38. It builds off of the OpenSAML library.
  39. [[servlet-saml2login-minimalconfiguration]]
  40. == Minimal Configuration
  41. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a service provider consists of two basic steps.
  42. First, include the needed dependencies and second, indicate the necessary asserting party metadata.
  43. [NOTE]
  44. Also, this presupposes that you've already xref:servlet/saml2/metadata.adoc#servlet-saml2login-metadata[registered the relying party with your asserting party].
  45. === Specifying Identity Provider Metadata
  46. In a Spring Boot application, to specify an identity provider's metadata, simply do:
  47. [source,yml]
  48. ----
  49. spring:
  50. security:
  51. saml2:
  52. relyingparty:
  53. registration:
  54. adfs:
  55. identityprovider:
  56. entity-id: https://idp.example.com/issuer
  57. verification.credentials:
  58. - certificate-location: "classpath:idp.crt"
  59. singlesignon.url: https://idp.example.com/issuer/sso
  60. singlesignon.sign-request: false
  61. ----
  62. where
  63. * `https://idp.example.com/issuer` is the value contained in the `Issuer` attribute of the SAML responses that the identity provider will issue
  64. * `classpath:idp.crt` is the location on the classpath for the identity provider's certificate for verifying SAML responses, and
  65. * `https://idp.example.com/issuer/sso` is the endpoint where the identity provider is expecting ``AuthnRequest``s.
  66. * `adfs` is <<servlet-saml2login-relyingpartyregistrationid, an arbitrary identifier you choose>>
  67. And that's it!
  68. [NOTE]
  69. Identity Provider and Asserting Party are synonymous, as are Service Provider and Relying Party.
  70. These are frequently abbreviated as AP and RP, respectively.
  71. === Runtime Expectations
  72. As configured above, the application processes any `+POST /login/saml2/sso/{registrationId}+` request containing a `SAMLResponse` parameter:
  73. [source,html]
  74. ----
  75. POST /login/saml2/sso/adfs HTTP/1.1
  76. SAMLResponse=PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZ...
  77. ----
  78. There are two ways to see induce your asserting party to generate a `SAMLResponse`:
  79. * First, you can navigate to your asserting party.
  80. It likely has some kind of link or button for each registered relying party that you can click to send the `SAMLResponse`.
  81. * Second, you can navigate to a protected page in your app, for example, `http://localhost:8080`.
  82. Your app then redirects to the configured asserting party which then sends the `SAMLResponse`.
  83. From here, consider jumping to:
  84. * <<servlet-saml2login-architecture,How SAML 2.0 Login Integrates with OpenSAML>>
  85. * xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-authenticatedprincipal[How to Use the `Saml2AuthenticatedPrincipal`]
  86. * <<servlet-saml2login-sansboot,How to Override or Replace Spring Boot's Auto Configuration>>
  87. [[servlet-saml2login-architecture]]
  88. == How SAML 2.0 Login Integrates with OpenSAML
  89. Spring Security's SAML 2.0 support has a couple of design goals:
  90. * First, rely on a library for SAML 2.0 operations and domain objects.
  91. To achieve this, Spring Security uses OpenSAML.
  92. * Second, ensure this library is not required when using Spring Security's SAML support.
  93. To achieve this, any interfaces or classes where Spring Security uses OpenSAML in the contract remain encapsulated.
  94. This makes it possible for you to switch out OpenSAML for some other library or even an unsupported version of OpenSAML.
  95. As a natural outcome of the above two goals, Spring Security's SAML API is quite small relative to other modules.
  96. Instead, classes like `OpenSaml4AuthenticationRequestFactory` and `OpenSaml4AuthenticationProvider` expose ``Converter``s that customize various steps in the authentication process.
  97. For example, once your application receives a `SAMLResponse` and delegates to `Saml2WebSsoAuthenticationFilter`, the filter will delegate to `OpenSaml4AuthenticationProvider`.
  98. [NOTE]
  99. For backward compatibility, Spring Security will use the latest OpenSAML 3 by default.
  100. Note, though that OpenSAML 3 has reached it's end-of-life and updating to OpenSAML 4.x is recommended.
  101. For that reason, Spring Security supports both OpenSAML 3.x and 4.x.
  102. If you manage your OpenSAML dependency to 4.x, then Spring Security will select its OpenSAML 4.x implementations.
  103. .Authenticating an OpenSAML `Response`
  104. image:{figures}/opensamlauthenticationprovider.png[]
  105. This figure builds off of the <<servlet-saml2login-authentication-saml2webssoauthenticationfilter,`Saml2WebSsoAuthenticationFilter` diagram>>.
  106. image:{icondir}/number_1.png[] The `Saml2WebSsoAuthenticationFilter` formulates the `Saml2AuthenticationToken` and invokes the xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`].
  107. image:{icondir}/number_2.png[] The xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`] invokes the OpenSAML authentication provider.
  108. image:{icondir}/number_3.png[] The authentication provider deserializes the response into an OpenSAML `Response` and checks its signature.
  109. If the signature is invalid, authentication fails.
  110. image:{icondir}/number_4.png[] Then, the provider xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-opensamlauthenticationprovider-decryption[decrypts any `EncryptedAssertion` elements].
  111. If any decryptions fail, authentication fails.
  112. image:{icondir}/number_5.png[] Next, the provider validates the response's `Issuer` and `Destination` values.
  113. If they don't match what's in the `RelyingPartyRegistration`, authentication fails.
  114. image:{icondir}/number_6.png[] After that, the provider verifies the signature of each `Assertion`.
  115. If any signature is invalid, authentication fails.
  116. Also, if neither the response nor the assertions have signatures, authentication fails.
  117. Either the response or all the assertions must have signatures.
  118. image:{icondir}/number_7.png[] Then, the provider xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-opensamlauthenticationprovider-decryption[,]decrypts any `EncryptedID` or `EncryptedAttribute` elements].
  119. If any decryptions fail, authentication fails.
  120. image:{icondir}/number_8.png[] Next, the provider validates each assertion's `ExpiresAt` and `NotBefore` timestamps, the `<Subject>` and any `<AudienceRestriction>` conditions.
  121. If any validations fail, authentication fails.
  122. image:{icondir}/number_9.png[] Following that, the provider takes the first assertion's `AttributeStatement` and maps it to a `Map<String, List<Object>>`.
  123. It also grants the `ROLE_USER` granted authority.
  124. 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`.
  125. Then, it places that principal and the authorities into a `Saml2Authentication`.
  126. The resulting `Authentication#getPrincipal` is a Spring Security `Saml2AuthenticatedPrincipal` object, and `Authentication#getName` maps to the first assertion's `NameID` element.
  127. `Saml2AuthenticatedPrincipal#getRelyingPartyRegistrationId` holds the <<servlet-saml2login-relyingpartyregistrationid,identifier to the associated `RelyingPartyRegistration`>>.
  128. [[servlet-saml2login-opensaml-customization]]
  129. === Customizing OpenSAML Configuration
  130. Any class that uses both Spring Security and OpenSAML should statically initialize `OpenSamlInitializationService` at the beginning of the class, like so:
  131. ====
  132. .Java
  133. [source,java,role="primary"]
  134. ----
  135. static {
  136. OpenSamlInitializationService.initialize();
  137. }
  138. ----
  139. .Kotlin
  140. [source,kotlin,role="secondary"]
  141. ----
  142. companion object {
  143. init {
  144. OpenSamlInitializationService.initialize()
  145. }
  146. }
  147. ----
  148. ====
  149. This replaces OpenSAML's `InitializationService#initialize`.
  150. Occasionally, it can be valuable to customize how OpenSAML builds, marshalls, and unmarshalls SAML objects.
  151. In these circumstances, you may instead want to call `OpenSamlInitializationService#requireInitialize(Consumer)` that gives you access to OpenSAML's `XMLObjectProviderFactory`.
  152. For example, when sending an unsigned AuthNRequest, you may want to force reauthentication.
  153. In that case, you can register your own `AuthnRequestMarshaller`, like so:
  154. ====
  155. .Java
  156. [source,java,role="primary"]
  157. ----
  158. static {
  159. OpenSamlInitializationService.requireInitialize(factory -> {
  160. AuthnRequestMarshaller marshaller = new AuthnRequestMarshaller() {
  161. @Override
  162. public Element marshall(XMLObject object, Element element) throws MarshallingException {
  163. configureAuthnRequest((AuthnRequest) object);
  164. return super.marshall(object, element);
  165. }
  166. public Element marshall(XMLObject object, Document document) throws MarshallingException {
  167. configureAuthnRequest((AuthnRequest) object);
  168. return super.marshall(object, document);
  169. }
  170. private void configureAuthnRequest(AuthnRequest authnRequest) {
  171. authnRequest.setForceAuthn(true);
  172. }
  173. }
  174. factory.getMarshallerFactory().registerMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME, marshaller);
  175. });
  176. }
  177. ----
  178. .Kotlin
  179. [source,kotlin,role="secondary"]
  180. ----
  181. companion object {
  182. init {
  183. OpenSamlInitializationService.requireInitialize {
  184. val marshaller = object : AuthnRequestMarshaller() {
  185. override fun marshall(xmlObject: XMLObject, element: Element): Element {
  186. configureAuthnRequest(xmlObject as AuthnRequest)
  187. return super.marshall(xmlObject, element)
  188. }
  189. override fun marshall(xmlObject: XMLObject, document: Document): Element {
  190. configureAuthnRequest(xmlObject as AuthnRequest)
  191. return super.marshall(xmlObject, document)
  192. }
  193. private fun configureAuthnRequest(authnRequest: AuthnRequest) {
  194. authnRequest.isForceAuthn = true
  195. }
  196. }
  197. it.marshallerFactory.registerMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME, marshaller)
  198. }
  199. }
  200. }
  201. ----
  202. ====
  203. The `requireInitialize` method may only be called once per application instance.
  204. [[servlet-saml2login-sansboot]]
  205. == Overriding or Replacing Boot Auto Configuration
  206. There are two ``@Bean``s that Spring Boot generates for a relying party.
  207. The first is a `SecurityFilterChain` that configures the app as a relying party.
  208. When including `spring-security-saml2-service-provider`, the `SecurityFilterChain` looks like:
  209. .Default JWT Configuration
  210. ====
  211. .Java
  212. [source,java,role="primary"]
  213. ----
  214. @Bean
  215. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  216. http
  217. .authorizeHttpRequests(authorize -> authorize
  218. .anyRequest().authenticated()
  219. )
  220. .saml2Login(withDefaults());
  221. return http.build();
  222. }
  223. ----
  224. .Kotlin
  225. [source,kotlin,role="secondary"]
  226. ----
  227. @Bean
  228. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  229. http {
  230. authorizeRequests {
  231. authorize(anyRequest, authenticated)
  232. }
  233. saml2Login { }
  234. }
  235. return http.build()
  236. }
  237. ----
  238. ====
  239. If the application doesn't expose a `SecurityFilterChain` bean, then Spring Boot will expose the above default one.
  240. You can replace this by exposing the bean within the application:
  241. .Custom SAML 2.0 Login Configuration
  242. ====
  243. .Java
  244. [source,java,role="primary"]
  245. ----
  246. @EnableWebSecurity
  247. public class MyCustomSecurityConfiguration {
  248. @Bean
  249. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  250. http
  251. .authorizeHttpRequests(authorize -> authorize
  252. .requestMatchers("/messages/**").hasAuthority("ROLE_USER")
  253. .anyRequest().authenticated()
  254. )
  255. .saml2Login(withDefaults());
  256. return http.build();
  257. }
  258. }
  259. ----
  260. .Kotlin
  261. [source,kotlin,role="secondary"]
  262. ----
  263. @EnableWebSecurity
  264. class MyCustomSecurityConfiguration {
  265. @Bean
  266. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  267. http {
  268. authorizeRequests {
  269. authorize("/messages/**", hasAuthority("ROLE_USER"))
  270. authorize(anyRequest, authenticated)
  271. }
  272. saml2Login {
  273. }
  274. }
  275. return http.build()
  276. }
  277. }
  278. ----
  279. ====
  280. The above requires the role of `USER` for any URL that starts with `/messages/`.
  281. [[servlet-saml2login-relyingpartyregistrationrepository]]
  282. 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.
  283. This includes things like the location of the SSO endpoint the relying party should use when requesting authentication from the asserting party.
  284. You can override the default by publishing your own `RelyingPartyRegistrationRepository` bean.
  285. For example, you can look up the asserting party's configuration by hitting its metadata endpoint like so:
  286. .Relying Party Registration Repository
  287. ====
  288. .Java
  289. [source,java,role="primary"]
  290. ----
  291. @Value("${metadata.location}")
  292. String assertingPartyMetadataLocation;
  293. @Bean
  294. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  295. RelyingPartyRegistration registration = RelyingPartyRegistrations
  296. .fromMetadataLocation(assertingPartyMetadataLocation)
  297. .registrationId("example")
  298. .build();
  299. return new InMemoryRelyingPartyRegistrationRepository(registration);
  300. }
  301. ----
  302. .Kotlin
  303. [source,kotlin,role="secondary"]
  304. ----
  305. @Value("\${metadata.location}")
  306. var assertingPartyMetadataLocation: String? = null
  307. @Bean
  308. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  309. val registration = RelyingPartyRegistrations
  310. .fromMetadataLocation(assertingPartyMetadataLocation)
  311. .registrationId("example")
  312. .build()
  313. return InMemoryRelyingPartyRegistrationRepository(registration)
  314. }
  315. ----
  316. ====
  317. [[servlet-saml2login-relyingpartyregistrationid]]
  318. [NOTE]
  319. The `registrationId` is an arbitrary value that you choose for differentiating between registrations.
  320. Or you can provide each detail manually, as you can see below:
  321. .Relying Party Registration Repository Manual Configuration
  322. ====
  323. .Java
  324. [source,java,role="primary"]
  325. ----
  326. @Value("${verification.key}")
  327. File verificationKey;
  328. @Bean
  329. public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception {
  330. X509Certificate certificate = X509Support.decodeCertificate(this.verificationKey);
  331. Saml2X509Credential credential = Saml2X509Credential.verification(certificate);
  332. RelyingPartyRegistration registration = RelyingPartyRegistration
  333. .withRegistrationId("example")
  334. .assertingPartyDetails(party -> party
  335. .entityId("https://idp.example.com/issuer")
  336. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  337. .wantAuthnRequestsSigned(false)
  338. .verificationX509Credentials(c -> c.add(credential))
  339. )
  340. .build();
  341. return new InMemoryRelyingPartyRegistrationRepository(registration);
  342. }
  343. ----
  344. .Kotlin
  345. [source,kotlin,role="secondary"]
  346. ----
  347. @Value("\${verification.key}")
  348. var verificationKey: File? = null
  349. @Bean
  350. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository {
  351. val certificate: X509Certificate? = X509Support.decodeCertificate(verificationKey!!)
  352. val credential: Saml2X509Credential = Saml2X509Credential.verification(certificate)
  353. val registration = RelyingPartyRegistration
  354. .withRegistrationId("example")
  355. .assertingPartyDetails { party: AssertingPartyDetails.Builder ->
  356. party
  357. .entityId("https://idp.example.com/issuer")
  358. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  359. .wantAuthnRequestsSigned(false)
  360. .verificationX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  361. c.add(
  362. credential
  363. )
  364. }
  365. }
  366. .build()
  367. return InMemoryRelyingPartyRegistrationRepository(registration)
  368. }
  369. ----
  370. ====
  371. [NOTE]
  372. Note that `X509Support` is an OpenSAML class, used here in the snippet for brevity
  373. [[servlet-saml2login-relyingpartyregistrationrepository-dsl]]
  374. Alternatively, you can directly wire up the repository using the DSL, which will also override the auto-configured `SecurityFilterChain`:
  375. .Custom Relying Party Registration DSL
  376. ====
  377. .Java
  378. [source,java,role="primary"]
  379. ----
  380. @EnableWebSecurity
  381. public class MyCustomSecurityConfiguration {
  382. @Bean
  383. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  384. http
  385. .authorizeHttpRequests(authorize -> authorize
  386. .requestMatchers("/messages/**").hasAuthority("ROLE_USER")
  387. .anyRequest().authenticated()
  388. )
  389. .saml2Login(saml2 -> saml2
  390. .relyingPartyRegistrationRepository(relyingPartyRegistrations())
  391. );
  392. return http.build();
  393. }
  394. }
  395. ----
  396. .Kotlin
  397. [source,kotlin,role="secondary"]
  398. ----
  399. @EnableWebSecurity
  400. class MyCustomSecurityConfiguration {
  401. @Bean
  402. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  403. http {
  404. authorizeRequests {
  405. authorize("/messages/**", hasAuthority("ROLE_USER"))
  406. authorize(anyRequest, authenticated)
  407. }
  408. saml2Login {
  409. relyingPartyRegistrationRepository = relyingPartyRegistrations()
  410. }
  411. }
  412. return http.build()
  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 xref:servlet/saml2/login/authentication-requests.adoc#servlet-saml2login-sp-initiated-factory[produce ``<saml2:AuthnRequest>``s], xref:servlet/saml2/login/authentication.adoc#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. ====