overview.adoc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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 `WebSecurityConfigurerAdapter` that configures the app as a relying party.
  208. When including `spring-security-saml2-service-provider`, the `WebSecurityConfigurerAdapter` looks like:
  209. .Default JWT Configuration
  210. ====
  211. .Java
  212. [source,java,role="primary"]
  213. ----
  214. protected void configure(HttpSecurity http) {
  215. http
  216. .authorizeRequests(authorize -> authorize
  217. .anyRequest().authenticated()
  218. )
  219. .saml2Login(withDefaults());
  220. }
  221. ----
  222. .Kotlin
  223. [source,kotlin,role="secondary"]
  224. ----
  225. fun configure(http: HttpSecurity) {
  226. http {
  227. authorizeRequests {
  228. authorize(anyRequest, authenticated)
  229. }
  230. saml2Login { }
  231. }
  232. }
  233. ----
  234. ====
  235. If the application doesn't expose a `WebSecurityConfigurerAdapter` bean, then Spring Boot will expose the above default one.
  236. You can replace this by exposing the bean within the application:
  237. .Custom SAML 2.0 Login Configuration
  238. ====
  239. .Java
  240. [source,java,role="primary"]
  241. ----
  242. @EnableWebSecurity
  243. public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
  244. protected void configure(HttpSecurity http) {
  245. http
  246. .authorizeRequests(authorize -> authorize
  247. .mvcMatchers("/messages/**").hasAuthority("ROLE_USER")
  248. .anyRequest().authenticated()
  249. )
  250. .saml2Login(withDefaults());
  251. }
  252. }
  253. ----
  254. .Kotlin
  255. [source,kotlin,role="secondary"]
  256. ----
  257. @EnableWebSecurity
  258. class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
  259. override fun configure(http: HttpSecurity) {
  260. http {
  261. authorizeRequests {
  262. authorize("/messages/**", hasAuthority("ROLE_USER"))
  263. authorize(anyRequest, authenticated)
  264. }
  265. saml2Login {
  266. }
  267. }
  268. }
  269. }
  270. ----
  271. ====
  272. The above requires the role of `USER` for any URL that starts with `/messages/`.
  273. [[servlet-saml2login-relyingpartyregistrationrepository]]
  274. 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.
  275. This includes things like the location of the SSO endpoint the relying party should use when requesting authentication from the asserting party.
  276. You can override the default by publishing your own `RelyingPartyRegistrationRepository` bean.
  277. For example, you can look up the asserting party's configuration by hitting its metadata endpoint like so:
  278. .Relying Party Registration Repository
  279. ====
  280. .Java
  281. [source,java,role="primary"]
  282. ----
  283. @Value("${metadata.location}")
  284. String assertingPartyMetadataLocation;
  285. @Bean
  286. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  287. RelyingPartyRegistration registration = RelyingPartyRegistrations
  288. .fromMetadataLocation(assertingPartyMetadataLocation)
  289. .registrationId("example")
  290. .build();
  291. return new InMemoryRelyingPartyRegistrationRepository(registration);
  292. }
  293. ----
  294. .Kotlin
  295. [source,kotlin,role="secondary"]
  296. ----
  297. @Value("\${metadata.location}")
  298. var assertingPartyMetadataLocation: String? = null
  299. @Bean
  300. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  301. val registration = RelyingPartyRegistrations
  302. .fromMetadataLocation(assertingPartyMetadataLocation)
  303. .registrationId("example")
  304. .build()
  305. return InMemoryRelyingPartyRegistrationRepository(registration)
  306. }
  307. ----
  308. ====
  309. [[servlet-saml2login-relyingpartyregistrationid]]
  310. [NOTE]
  311. The `registrationId` is an arbitrary value that you choose for differentiating between registrations.
  312. Or you can provide each detail manually, as you can see below:
  313. .Relying Party Registration Repository Manual Configuration
  314. ====
  315. .Java
  316. [source,java,role="primary"]
  317. ----
  318. @Value("${verification.key}")
  319. File verificationKey;
  320. @Bean
  321. public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception {
  322. X509Certificate certificate = X509Support.decodeCertificate(this.verificationKey);
  323. Saml2X509Credential credential = Saml2X509Credential.verification(certificate);
  324. RelyingPartyRegistration registration = RelyingPartyRegistration
  325. .withRegistrationId("example")
  326. .assertingPartyDetails(party -> party
  327. .entityId("https://idp.example.com/issuer")
  328. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  329. .wantAuthnRequestsSigned(false)
  330. .verificationX509Credentials(c -> c.add(credential))
  331. )
  332. .build();
  333. return new InMemoryRelyingPartyRegistrationRepository(registration);
  334. }
  335. ----
  336. .Kotlin
  337. [source,kotlin,role="secondary"]
  338. ----
  339. @Value("\${verification.key}")
  340. var verificationKey: File? = null
  341. @Bean
  342. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository {
  343. val certificate: X509Certificate? = X509Support.decodeCertificate(verificationKey!!)
  344. val credential: Saml2X509Credential = Saml2X509Credential.verification(certificate)
  345. val registration = RelyingPartyRegistration
  346. .withRegistrationId("example")
  347. .assertingPartyDetails { party: AssertingPartyDetails.Builder ->
  348. party
  349. .entityId("https://idp.example.com/issuer")
  350. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  351. .wantAuthnRequestsSigned(false)
  352. .verificationX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  353. c.add(
  354. credential
  355. )
  356. }
  357. }
  358. .build()
  359. return InMemoryRelyingPartyRegistrationRepository(registration)
  360. }
  361. ----
  362. ====
  363. [NOTE]
  364. Note that `X509Support` is an OpenSAML class, used here in the snippet for brevity
  365. [[servlet-saml2login-relyingpartyregistrationrepository-dsl]]
  366. Alternatively, you can directly wire up the repository using the DSL, which will also override the auto-configured `WebSecurityConfigurerAdapter`:
  367. .Custom Relying Party Registration DSL
  368. ====
  369. .Java
  370. [source,java,role="primary"]
  371. ----
  372. @EnableWebSecurity
  373. public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
  374. protected void configure(HttpSecurity http) {
  375. http
  376. .authorizeRequests(authorize -> authorize
  377. .mvcMatchers("/messages/**").hasAuthority("ROLE_USER")
  378. .anyRequest().authenticated()
  379. )
  380. .saml2Login(saml2 -> saml2
  381. .relyingPartyRegistrationRepository(relyingPartyRegistrations())
  382. );
  383. }
  384. }
  385. ----
  386. .Kotlin
  387. [source,kotlin,role="secondary"]
  388. ----
  389. @EnableWebSecurity
  390. class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
  391. override fun configure(http: HttpSecurity) {
  392. http {
  393. authorizeRequests {
  394. authorize("/messages/**", hasAuthority("ROLE_USER"))
  395. authorize(anyRequest, authenticated)
  396. }
  397. saml2Login {
  398. relyingPartyRegistrationRepository = relyingPartyRegistrations()
  399. }
  400. }
  401. }
  402. }
  403. ----
  404. ====
  405. [NOTE]
  406. A relying party can be multi-tenant by registering more than one relying party in the `RelyingPartyRegistrationRepository`.
  407. [[servlet-saml2login-relyingpartyregistration]]
  408. == RelyingPartyRegistration
  409. A {security-api-url}org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.html[`RelyingPartyRegistration`]
  410. instance represents a link between an relying party and assering party's metadata.
  411. 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.
  412. 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.
  413. The following `RelyingPartyRegistration` is the minimum required for most setups:
  414. ====
  415. .Java
  416. [source,java,role="primary"]
  417. ----
  418. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
  419. .fromMetadataLocation("https://ap.example.org/metadata")
  420. .registrationId("my-id")
  421. .build();
  422. ----
  423. .Kotlin
  424. [source,kotlin,role="secondary"]
  425. ----
  426. val relyingPartyRegistration = RelyingPartyRegistrations
  427. .fromMetadataLocation("https://ap.example.org/metadata")
  428. .registrationId("my-id")
  429. .build()
  430. ----
  431. ====
  432. Note that you can also create a `RelyingPartyRegistration` from an arbitrary `InputStream` source.
  433. One such example is when the metadata is stored in a database:
  434. [source,java]
  435. ----
  436. String xml = fromDatabase();
  437. try (InputStream source = new ByteArrayInputStream(xml.getBytes())) {
  438. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
  439. .fromMetadata(source)
  440. .registrationId("my-id")
  441. .build();
  442. }
  443. ----
  444. Though a more sophisticated setup is also possible, like so:
  445. ====
  446. .Java
  447. [source,java,role="primary"]
  448. ----
  449. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("my-id")
  450. .entityId("{baseUrl}/{registrationId}")
  451. .decryptionX509Credentials(c -> c.add(relyingPartyDecryptingCredential()))
  452. .assertionConsumerServiceLocation("/my-login-endpoint/{registrationId}")
  453. .assertingPartyDetails(party -> party
  454. .entityId("https://ap.example.org")
  455. .verificationX509Credentials(c -> c.add(assertingPartyVerifyingCredential()))
  456. .singleSignOnServiceLocation("https://ap.example.org/SSO.saml2")
  457. )
  458. .build();
  459. ----
  460. .Kotlin
  461. [source,kotlin,role="secondary"]
  462. ----
  463. val relyingPartyRegistration =
  464. RelyingPartyRegistration.withRegistrationId("my-id")
  465. .entityId("{baseUrl}/{registrationId}")
  466. .decryptionX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  467. c.add(relyingPartyDecryptingCredential())
  468. }
  469. .assertionConsumerServiceLocation("/my-login-endpoint/{registrationId}")
  470. .assertingPartyDetails { party -> party
  471. .entityId("https://ap.example.org")
  472. .verificationX509Credentials { c -> c.add(assertingPartyVerifyingCredential()) }
  473. .singleSignOnServiceLocation("https://ap.example.org/SSO.saml2")
  474. }
  475. .build()
  476. ----
  477. ====
  478. [TIP]
  479. The top-level metadata methods are details about the relying party.
  480. The methods inside `assertingPartyDetails` are details about the asserting party.
  481. [NOTE]
  482. The location where a relying party is expecting SAML Responses is the Assertion Consumer Service Location.
  483. The default for the relying party's `entityId` is `+{baseUrl}/saml2/service-provider-metadata/{registrationId}+`.
  484. This is this value needed when configuring the asserting party to know about your relying party.
  485. The default for the `assertionConsumerServiceLocation` is `+/login/saml2/sso/{registrationId}+`.
  486. It's mapped by default to <<servlet-saml2login-authentication-saml2webssoauthenticationfilter,`Saml2WebSsoAuthenticationFilter`>> in the filter chain.
  487. [[servlet-saml2login-rpr-uripatterns]]
  488. === URI Patterns
  489. You probably noticed in the above examples the `+{baseUrl}+` and `+{registrationId}+` placeholders.
  490. These are useful for generating URIs. As such, the relying party's `entityId` and `assertionConsumerServiceLocation` support the following placeholders:
  491. * `baseUrl` - the scheme, host, and port of a deployed application
  492. * `registrationId` - the registration id for this relying party
  493. * `baseScheme` - the scheme of a deployed application
  494. * `baseHost` - the host of a deployed application
  495. * `basePort` - the port of a deployed application
  496. For example, the `assertionConsumerServiceLocation` defined above was:
  497. `+/my-login-endpoint/{registrationId}+`
  498. which in a deployed application would translate to
  499. `+/my-login-endpoint/adfs+`
  500. The `entityId` above was defined as:
  501. `+{baseUrl}/{registrationId}+`
  502. which in a deployed application would translate to
  503. `+https://rp.example.com/adfs+`
  504. [[servlet-saml2login-rpr-credentials]]
  505. === Credentials
  506. You also likely noticed the credential that was used.
  507. Oftentimes, a relying party will use the same key to sign payloads as well as decrypt them.
  508. Or it will use the same key to verify payloads as well as encrypt them.
  509. Because of this, Spring Security ships with `Saml2X509Credential`, a SAML-specific credential that simplifies configuring the same key for different use cases.
  510. 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.
  511. To construct a `Saml2X509Credential` that you'll use to verify assertions from the asserting party, you can load the file and use
  512. the `CertificateFactory` like so:
  513. ====
  514. .Java
  515. [source,java,role="primary"]
  516. ----
  517. Resource resource = new ClassPathResource("ap.crt");
  518. try (InputStream is = resource.getInputStream()) {
  519. X509Certificate certificate = (X509Certificate)
  520. CertificateFactory.getInstance("X.509").generateCertificate(is);
  521. return Saml2X509Credential.verification(certificate);
  522. }
  523. ----
  524. .Kotlin
  525. [source,kotlin,role="secondary"]
  526. ----
  527. val resource = ClassPathResource("ap.crt")
  528. resource.inputStream.use {
  529. return Saml2X509Credential.verification(
  530. CertificateFactory.getInstance("X.509").generateCertificate(it) as X509Certificate?
  531. )
  532. }
  533. ----
  534. ====
  535. Let's say that the asserting party is going to also encrypt the assertion.
  536. In that case, the relying party will need a private key to be able to decrypt the encrypted value.
  537. In that case, you'll need an `RSAPrivateKey` as well as its corresponding `X509Certificate`.
  538. You can load the first using Spring Security's `RsaKeyConverters` utility class and the second as you did before:
  539. ====
  540. .Java
  541. [source,java,role="primary"]
  542. ----
  543. X509Certificate certificate = relyingPartyDecryptionCertificate();
  544. Resource resource = new ClassPathResource("rp.crt");
  545. try (InputStream is = resource.getInputStream()) {
  546. RSAPrivateKey rsa = RsaKeyConverters.pkcs8().convert(is);
  547. return Saml2X509Credential.decryption(rsa, certificate);
  548. }
  549. ----
  550. .Kotlin
  551. [source,kotlin,role="secondary"]
  552. ----
  553. val certificate: X509Certificate = relyingPartyDecryptionCertificate()
  554. val resource = ClassPathResource("rp.crt")
  555. resource.inputStream.use {
  556. val rsa: RSAPrivateKey = RsaKeyConverters.pkcs8().convert(it)
  557. return Saml2X509Credential.decryption(rsa, certificate)
  558. }
  559. ----
  560. ====
  561. [TIP]
  562. When you specify the locations of these files as the appropriate Spring Boot properties, then Spring Boot will perform these conversions for you.
  563. [[servlet-saml2login-rpr-relyingpartyregistrationresolver]]
  564. === Resolving the Relying Party from the Request
  565. As seen so far, Spring Security resolves the `RelyingPartyRegistration` by looking for the registration id in the URI path.
  566. There are a number of reasons you may want to customize. Among them:
  567. * You may know that you will never be a multi-tenant application and so want to have a simpler URL scheme
  568. * You may identify tenants in a way other than by the URI path
  569. To customize the way that a `RelyingPartyRegistration` is resolved, you can configure a custom `RelyingPartyRegistrationResolver`.
  570. The default looks up the registration id from the URI's last path element and looks it up in your `RelyingPartyRegistrationRepository`.
  571. You can provide a simpler resolver that, for example, always returns the same relying party:
  572. ====
  573. .Java
  574. [source,java,role="primary"]
  575. ----
  576. public class SingleRelyingPartyRegistrationResolver implements RelyingPartyRegistrationResolver {
  577. private final RelyingPartyRegistrationResolver delegate;
  578. public SingleRelyingPartyRegistrationResolver(RelyingPartyRegistrationRepository registrations) {
  579. this.delegate = new DefaultRelyingPartyRegistrationResolver(registrations);
  580. }
  581. @Override
  582. public RelyingPartyRegistration resolve(HttpServletRequest request, String registrationId) {
  583. return this.delegate.resolve(request, "single");
  584. }
  585. }
  586. ----
  587. .Kotlin
  588. [source,kotlin,role="secondary"]
  589. ----
  590. class SingleRelyingPartyRegistrationResolver(delegate: RelyingPartyRegistrationResolver) : RelyingPartyRegistrationResolver {
  591. override fun resolve(request: HttpServletRequest?, registrationId: String?): RelyingPartyRegistration? {
  592. return this.delegate.resolve(request, "single")
  593. }
  594. }
  595. ----
  596. ====
  597. 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].
  598. [NOTE]
  599. Remember that if you have any placeholders in your `RelyingPartyRegistration`, your resolver implementation should resolve them.
  600. [[servlet-saml2login-rpr-duplicated]]
  601. === Duplicated Relying Party Configurations
  602. When an application uses multiple asserting parties, some configuration is duplicated between `RelyingPartyRegistration` instances:
  603. * The relying party's `entityId`
  604. * Its `assertionConsumerServiceLocation`, and
  605. * Its credentials, for example its signing or decryption credentials
  606. What's nice about this setup is credentials may be more easily rotated for some identity providers vs others.
  607. The duplication can be alleviated in a few different ways.
  608. First, in YAML this can be alleviated with references, like so:
  609. [source,yaml]
  610. ----
  611. spring:
  612. security:
  613. saml2:
  614. relyingparty:
  615. okta:
  616. signing.credentials: &relying-party-credentials
  617. - private-key-location: classpath:rp.key
  618. certificate-location: classpath:rp.crt
  619. identityprovider:
  620. entity-id: ...
  621. azure:
  622. signing.credentials: *relying-party-credentials
  623. identityprovider:
  624. entity-id: ...
  625. ----
  626. Second, in a database, it's not necessary to replicate `RelyingPartyRegistration` 's model.
  627. Third, in Java, you can create a custom configuration method, like so:
  628. ====
  629. .Java
  630. [source,java,role="primary"]
  631. ----
  632. private RelyingPartyRegistration.Builder
  633. addRelyingPartyDetails(RelyingPartyRegistration.Builder builder) {
  634. Saml2X509Credential signingCredential = ...
  635. builder.signingX509Credentials(c -> c.addAll(signingCredential));
  636. // ... other relying party configurations
  637. }
  638. @Bean
  639. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  640. RelyingPartyRegistration okta = addRelyingPartyDetails(
  641. RelyingPartyRegistrations
  642. .fromMetadataLocation(oktaMetadataUrl)
  643. .registrationId("okta")).build();
  644. RelyingPartyRegistration azure = addRelyingPartyDetails(
  645. RelyingPartyRegistrations
  646. .fromMetadataLocation(oktaMetadataUrl)
  647. .registrationId("azure")).build();
  648. return new InMemoryRelyingPartyRegistrationRepository(okta, azure);
  649. }
  650. ----
  651. .Kotlin
  652. [source,kotlin,role="secondary"]
  653. ----
  654. private fun addRelyingPartyDetails(builder: RelyingPartyRegistration.Builder): RelyingPartyRegistration.Builder {
  655. val signingCredential: Saml2X509Credential = ...
  656. builder.signingX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  657. c.add(
  658. signingCredential
  659. )
  660. }
  661. // ... other relying party configurations
  662. }
  663. @Bean
  664. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  665. val okta = addRelyingPartyDetails(
  666. RelyingPartyRegistrations
  667. .fromMetadataLocation(oktaMetadataUrl)
  668. .registrationId("okta")
  669. ).build()
  670. val azure = addRelyingPartyDetails(
  671. RelyingPartyRegistrations
  672. .fromMetadataLocation(oktaMetadataUrl)
  673. .registrationId("azure")
  674. ).build()
  675. return InMemoryRelyingPartyRegistrationRepository(okta, azure)
  676. }
  677. ----
  678. ====