overview.adoc 35 KB

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