overview.adoc 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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. [NOTE]
  114. ====
  115. For backward compatibility, Spring Security will use the latest OpenSAML 3 by default.
  116. Note, though that OpenSAML 3 has reached it's end-of-life and updating to OpenSAML 4.x is recommended.
  117. For that reason, Spring Security supports both OpenSAML 3.x and 4.x.
  118. If you manage your OpenSAML dependency to 4.x, then Spring Security will select its OpenSAML 4.x implementations.
  119. ====
  120. .Authenticating an OpenSAML `Response`
  121. image:{figures}/opensamlauthenticationprovider.png[]
  122. This figure builds off of the <<servlet-saml2login-authentication-saml2webssoauthenticationfilter,`Saml2WebSsoAuthenticationFilter` diagram>>.
  123. image:{icondir}/number_1.png[] The `Saml2WebSsoAuthenticationFilter` formulates the `Saml2AuthenticationToken` and invokes the xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`].
  124. image:{icondir}/number_2.png[] The xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`] invokes the OpenSAML authentication provider.
  125. image:{icondir}/number_3.png[] The authentication provider deserializes the response into an OpenSAML `Response` and checks its signature.
  126. If the signature is invalid, authentication fails.
  127. image:{icondir}/number_4.png[] Then the provider xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-opensamlauthenticationprovider-decryption[decrypts any `EncryptedAssertion` elements].
  128. If any decryptions fail, authentication fails.
  129. image:{icondir}/number_5.png[] Next, the provider validates the response's `Issuer` and `Destination` values.
  130. If they do not match what's in the `RelyingPartyRegistration`, authentication fails.
  131. image:{icondir}/number_6.png[] After that, the provider verifies the signature of each `Assertion`.
  132. If any signature is invalid, authentication fails.
  133. Also, if neither the response nor the assertions have signatures, authentication fails.
  134. Either the response or all the assertions must have signatures.
  135. image:{icondir}/number_7.png[] Then, the provider xref:servlet/saml2/login/authentication.adoc#servlet-saml2login-opensamlauthenticationprovider-decryption[,]decrypts any `EncryptedID` or `EncryptedAttribute` elements].
  136. If any decryptions fail, authentication fails.
  137. image:{icondir}/number_8.png[] Next, the provider validates each assertion's `ExpiresAt` and `NotBefore` timestamps, the `<Subject>` and any `<AudienceRestriction>` conditions.
  138. If any validations fail, authentication fails.
  139. image:{icondir}/number_9.png[] Following that, the provider takes the first assertion's `AttributeStatement` and maps it to a `Map<String, List<Object>>`.
  140. It also grants the `ROLE_USER` granted authority.
  141. 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`.
  142. Then, it places that principal and the authorities into a `Saml2Authentication`.
  143. The resulting `Authentication#getPrincipal` is a Spring Security `Saml2AuthenticatedPrincipal` object, and `Authentication#getName` maps to the first assertion's `NameID` element.
  144. `Saml2AuthenticatedPrincipal#getRelyingPartyRegistrationId` holds the <<servlet-saml2login-relyingpartyregistrationid,identifier to the associated `RelyingPartyRegistration`>>.
  145. [[servlet-saml2login-opensaml-customization]]
  146. === Customizing OpenSAML Configuration
  147. Any class that uses both Spring Security and OpenSAML should statically initialize `OpenSamlInitializationService` at the beginning of the class:
  148. ====
  149. .Java
  150. [source,java,role="primary"]
  151. ----
  152. static {
  153. OpenSamlInitializationService.initialize();
  154. }
  155. ----
  156. .Kotlin
  157. [source,kotlin,role="secondary"]
  158. ----
  159. companion object {
  160. init {
  161. OpenSamlInitializationService.initialize()
  162. }
  163. }
  164. ----
  165. ====
  166. This replaces OpenSAML's `InitializationService#initialize`.
  167. Occasionally, it can be valuable to customize how OpenSAML builds, marshalls, and unmarshalls SAML objects.
  168. In these circumstances, you may instead want to call `OpenSamlInitializationService#requireInitialize(Consumer)` that gives you access to OpenSAML's `XMLObjectProviderFactory`.
  169. For example, when sending an unsigned AuthNRequest, you may want to force reauthentication.
  170. In that case, you can register your own `AuthnRequestMarshaller`, like so:
  171. ====
  172. .Java
  173. [source,java,role="primary"]
  174. ----
  175. static {
  176. OpenSamlInitializationService.requireInitialize(factory -> {
  177. AuthnRequestMarshaller marshaller = new AuthnRequestMarshaller() {
  178. @Override
  179. public Element marshall(XMLObject object, Element element) throws MarshallingException {
  180. configureAuthnRequest((AuthnRequest) object);
  181. return super.marshall(object, element);
  182. }
  183. public Element marshall(XMLObject object, Document document) throws MarshallingException {
  184. configureAuthnRequest((AuthnRequest) object);
  185. return super.marshall(object, document);
  186. }
  187. private void configureAuthnRequest(AuthnRequest authnRequest) {
  188. authnRequest.setForceAuthn(true);
  189. }
  190. }
  191. factory.getMarshallerFactory().registerMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME, marshaller);
  192. });
  193. }
  194. ----
  195. .Kotlin
  196. [source,kotlin,role="secondary"]
  197. ----
  198. companion object {
  199. init {
  200. OpenSamlInitializationService.requireInitialize {
  201. val marshaller = object : AuthnRequestMarshaller() {
  202. override fun marshall(xmlObject: XMLObject, element: Element): Element {
  203. configureAuthnRequest(xmlObject as AuthnRequest)
  204. return super.marshall(xmlObject, element)
  205. }
  206. override fun marshall(xmlObject: XMLObject, document: Document): Element {
  207. configureAuthnRequest(xmlObject as AuthnRequest)
  208. return super.marshall(xmlObject, document)
  209. }
  210. private fun configureAuthnRequest(authnRequest: AuthnRequest) {
  211. authnRequest.isForceAuthn = true
  212. }
  213. }
  214. it.marshallerFactory.registerMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME, marshaller)
  215. }
  216. }
  217. }
  218. ----
  219. ====
  220. The `requireInitialize` method may be called only once per application instance.
  221. [[servlet-saml2login-sansboot]]
  222. == Overriding or Replacing Boot Auto Configuration
  223. Spring Boot generates two `@Bean` objects for a relying party.
  224. The first is a `WebSecurityConfigurerAdapter` that configures the application as a relying party.
  225. When including `spring-security-saml2-service-provider`, the `WebSecurityConfigurerAdapter` looks like:
  226. .Default JWT Configuration
  227. ====
  228. .Java
  229. [source,java,role="primary"]
  230. ----
  231. protected void configure(HttpSecurity http) {
  232. http
  233. .authorizeHttpRequests(authorize -> authorize
  234. .anyRequest().authenticated()
  235. )
  236. .saml2Login(withDefaults());
  237. }
  238. ----
  239. .Kotlin
  240. [source,kotlin,role="secondary"]
  241. ----
  242. fun configure(http: HttpSecurity) {
  243. http {
  244. authorizeRequests {
  245. authorize(anyRequest, authenticated)
  246. }
  247. saml2Login { }
  248. }
  249. }
  250. ----
  251. ====
  252. If the application does not expose a `WebSecurityConfigurerAdapter` bean, Spring Boot exposes the preceding default one.
  253. You can replace this by exposing the bean within the application:
  254. .Custom SAML 2.0 Login Configuration
  255. ====
  256. .Java
  257. [source,java,role="primary"]
  258. ----
  259. @EnableWebSecurity
  260. public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
  261. protected void configure(HttpSecurity http) {
  262. http
  263. .authorizeHttpRequests(authorize -> authorize
  264. .mvcMatchers("/messages/**").hasAuthority("ROLE_USER")
  265. .anyRequest().authenticated()
  266. )
  267. .saml2Login(withDefaults());
  268. }
  269. }
  270. ----
  271. .Kotlin
  272. [source,kotlin,role="secondary"]
  273. ----
  274. @EnableWebSecurity
  275. class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
  276. override fun configure(http: HttpSecurity) {
  277. http {
  278. authorizeRequests {
  279. authorize("/messages/**", hasAuthority("ROLE_USER"))
  280. authorize(anyRequest, authenticated)
  281. }
  282. saml2Login {
  283. }
  284. }
  285. }
  286. }
  287. ----
  288. ====
  289. The preceding example requires the role of `USER` for any URL that starts with `/messages/`.
  290. [[servlet-saml2login-relyingpartyregistrationrepository]]
  291. 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.
  292. This includes such things as the location of the SSO endpoint the relying party should use when requesting authentication from the asserting party.
  293. You can override the default by publishing your own `RelyingPartyRegistrationRepository` bean.
  294. For example, you can look up the asserting party's configuration by hitting its metadata endpoint:
  295. .Relying Party Registration Repository
  296. ====
  297. .Java
  298. [source,java,role="primary"]
  299. ----
  300. @Value("${metadata.location}")
  301. String assertingPartyMetadataLocation;
  302. @Bean
  303. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  304. RelyingPartyRegistration registration = RelyingPartyRegistrations
  305. .fromMetadataLocation(assertingPartyMetadataLocation)
  306. .registrationId("example")
  307. .build();
  308. return new InMemoryRelyingPartyRegistrationRepository(registration);
  309. }
  310. ----
  311. .Kotlin
  312. [source,kotlin,role="secondary"]
  313. ----
  314. @Value("\${metadata.location}")
  315. var assertingPartyMetadataLocation: String? = null
  316. @Bean
  317. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  318. val registration = RelyingPartyRegistrations
  319. .fromMetadataLocation(assertingPartyMetadataLocation)
  320. .registrationId("example")
  321. .build()
  322. return InMemoryRelyingPartyRegistrationRepository(registration)
  323. }
  324. ----
  325. ====
  326. [[servlet-saml2login-relyingpartyregistrationid]]
  327. [NOTE]
  328. The `registrationId` is an arbitrary value that you choose for differentiating between registrations.
  329. Alternatively, you can provide each detail manually:
  330. .Relying Party Registration Repository Manual Configuration
  331. ====
  332. .Java
  333. [source,java,role="primary"]
  334. ----
  335. @Value("${verification.key}")
  336. File verificationKey;
  337. @Bean
  338. public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception {
  339. X509Certificate certificate = X509Support.decodeCertificate(this.verificationKey);
  340. Saml2X509Credential credential = Saml2X509Credential.verification(certificate);
  341. RelyingPartyRegistration registration = RelyingPartyRegistration
  342. .withRegistrationId("example")
  343. .assertingPartyDetails(party -> party
  344. .entityId("https://idp.example.com/issuer")
  345. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  346. .wantAuthnRequestsSigned(false)
  347. .verificationX509Credentials(c -> c.add(credential))
  348. )
  349. .build();
  350. return new InMemoryRelyingPartyRegistrationRepository(registration);
  351. }
  352. ----
  353. .Kotlin
  354. [source,kotlin,role="secondary"]
  355. ----
  356. @Value("\${verification.key}")
  357. var verificationKey: File? = null
  358. @Bean
  359. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository {
  360. val certificate: X509Certificate? = X509Support.decodeCertificate(verificationKey!!)
  361. val credential: Saml2X509Credential = Saml2X509Credential.verification(certificate)
  362. val registration = RelyingPartyRegistration
  363. .withRegistrationId("example")
  364. .assertingPartyDetails { party: AssertingPartyDetails.Builder ->
  365. party
  366. .entityId("https://idp.example.com/issuer")
  367. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  368. .wantAuthnRequestsSigned(false)
  369. .verificationX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  370. c.add(
  371. credential
  372. )
  373. }
  374. }
  375. .build()
  376. return InMemoryRelyingPartyRegistrationRepository(registration)
  377. }
  378. ----
  379. ====
  380. [NOTE]
  381. ====
  382. `X509Support` is an OpenSAML class, used in the preceding snippet for brevity.
  383. ====
  384. [[servlet-saml2login-relyingpartyregistrationrepository-dsl]]
  385. Alternatively, you can directly wire up the repository by using the DSL, which also overrides the auto-configured `WebSecurityConfigurerAdapter`:
  386. .Custom Relying Party Registration DSL
  387. ====
  388. .Java
  389. [source,java,role="primary"]
  390. ----
  391. @EnableWebSecurity
  392. public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
  393. protected void configure(HttpSecurity http) {
  394. http
  395. .authorizeHttpRequests(authorize -> authorize
  396. .mvcMatchers("/messages/**").hasAuthority("ROLE_USER")
  397. .anyRequest().authenticated()
  398. )
  399. .saml2Login(saml2 -> saml2
  400. .relyingPartyRegistrationRepository(relyingPartyRegistrations())
  401. );
  402. }
  403. }
  404. ----
  405. .Kotlin
  406. [source,kotlin,role="secondary"]
  407. ----
  408. @EnableWebSecurity
  409. class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
  410. override fun configure(http: HttpSecurity) {
  411. http {
  412. authorizeRequests {
  413. authorize("/messages/**", hasAuthority("ROLE_USER"))
  414. authorize(anyRequest, authenticated)
  415. }
  416. saml2Login {
  417. relyingPartyRegistrationRepository = relyingPartyRegistrations()
  418. }
  419. }
  420. }
  421. }
  422. ----
  423. ====
  424. [NOTE]
  425. ====
  426. A relying party can be multi-tenant by registering more than one relying party in the `RelyingPartyRegistrationRepository`.
  427. ====
  428. [[servlet-saml2login-relyingpartyregistration]]
  429. == RelyingPartyRegistration
  430. A {security-api-url}org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.html[`RelyingPartyRegistration`]
  431. instance represents a link between an relying party and an asserting party's metadata.
  432. 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.
  433. 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.
  434. The following `RelyingPartyRegistration` is the minimum required for most setups:
  435. ====
  436. .Java
  437. [source,java,role="primary"]
  438. ----
  439. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
  440. .fromMetadataLocation("https://ap.example.org/metadata")
  441. .registrationId("my-id")
  442. .build();
  443. ----
  444. .Kotlin
  445. [source,kotlin,role="secondary"]
  446. ----
  447. val relyingPartyRegistration = RelyingPartyRegistrations
  448. .fromMetadataLocation("https://ap.example.org/metadata")
  449. .registrationId("my-id")
  450. .build()
  451. ----
  452. ====
  453. Note that you can also create a `RelyingPartyRegistration` from an arbitrary `InputStream` source.
  454. One such example is when the metadata is stored in a database:
  455. [source,java]
  456. ----
  457. String xml = fromDatabase();
  458. try (InputStream source = new ByteArrayInputStream(xml.getBytes())) {
  459. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
  460. .fromMetadata(source)
  461. .registrationId("my-id")
  462. .build();
  463. }
  464. ----
  465. A more sophisticated setup is also possible:
  466. ====
  467. .Java
  468. [source,java,role="primary"]
  469. ----
  470. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("my-id")
  471. .entityId("{baseUrl}/{registrationId}")
  472. .decryptionX509Credentials(c -> c.add(relyingPartyDecryptingCredential()))
  473. .assertionConsumerServiceLocation("/my-login-endpoint/{registrationId}")
  474. .assertingPartyDetails(party -> party
  475. .entityId("https://ap.example.org")
  476. .verificationX509Credentials(c -> c.add(assertingPartyVerifyingCredential()))
  477. .singleSignOnServiceLocation("https://ap.example.org/SSO.saml2")
  478. )
  479. .build();
  480. ----
  481. .Kotlin
  482. [source,kotlin,role="secondary"]
  483. ----
  484. val relyingPartyRegistration =
  485. RelyingPartyRegistration.withRegistrationId("my-id")
  486. .entityId("{baseUrl}/{registrationId}")
  487. .decryptionX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  488. c.add(relyingPartyDecryptingCredential())
  489. }
  490. .assertionConsumerServiceLocation("/my-login-endpoint/{registrationId}")
  491. .assertingPartyDetails { party -> party
  492. .entityId("https://ap.example.org")
  493. .verificationX509Credentials { c -> c.add(assertingPartyVerifyingCredential()) }
  494. .singleSignOnServiceLocation("https://ap.example.org/SSO.saml2")
  495. }
  496. .build()
  497. ----
  498. ====
  499. [TIP]
  500. ====
  501. The top-level metadata methods are details about the relying party.
  502. The methods inside `assertingPartyDetails` are details about the asserting party.
  503. ====
  504. [NOTE]
  505. ====
  506. The location where a relying party is expecting SAML Responses is the Assertion Consumer Service Location.
  507. ====
  508. The default for the relying party's `entityId` is `+{baseUrl}/saml2/service-provider-metadata/{registrationId}+`.
  509. This is this value needed when configuring the asserting party to know about your relying party.
  510. The default for the `assertionConsumerServiceLocation` is `+/login/saml2/sso/{registrationId}+`.
  511. By default, it is mapped to <<servlet-saml2login-authentication-saml2webssoauthenticationfilter,`Saml2WebSsoAuthenticationFilter`>> in the filter chain.
  512. [[servlet-saml2login-rpr-uripatterns]]
  513. === URI Patterns
  514. You probably noticed the `+{baseUrl}+` and `+{registrationId}+` placeholders in the preceding examples.
  515. These are useful for generating URIs. As a result, the relying party's `entityId` and `assertionConsumerServiceLocation` support the following placeholders:
  516. * `baseUrl` - the scheme, host, and port of a deployed application
  517. * `registrationId` - the registration id for this relying party
  518. * `baseScheme` - the scheme of a deployed application
  519. * `baseHost` - the host of a deployed application
  520. * `basePort` - the port of a deployed application
  521. For example, the `assertionConsumerServiceLocation` defined earlier was:
  522. `+/my-login-endpoint/{registrationId}+`
  523. In a deployed application, it translates to:
  524. `+/my-login-endpoint/adfs+`
  525. The `entityId` shown earlier was defined as:
  526. `+{baseUrl}/{registrationId}+`
  527. In a deployed application, that translates to:
  528. `+https://rp.example.com/adfs+`
  529. [[servlet-saml2login-rpr-credentials]]
  530. === Credentials
  531. In the example shown <<servlet-saml2login-relyingpartyregistration,earlier>>, you also likely noticed the credential that was used.
  532. Oftentimes, a relying party uses the same key to sign payloads as well as decrypt them.
  533. Alternatively, it can use the same key to verify payloads as well as encrypt them.
  534. Because of this, Spring Security ships with `Saml2X509Credential`, a SAML-specific credential that simplifies configuring the same key for different use cases.
  535. At a minimum, you need to have a certificate from the asserting party so that the asserting party's signed responses can be verified.
  536. To construct a `Saml2X509Credential` that you can use to verify assertions from the asserting party, you can load the file and use
  537. the `CertificateFactory`:
  538. ====
  539. .Java
  540. [source,java,role="primary"]
  541. ----
  542. Resource resource = new ClassPathResource("ap.crt");
  543. try (InputStream is = resource.getInputStream()) {
  544. X509Certificate certificate = (X509Certificate)
  545. CertificateFactory.getInstance("X.509").generateCertificate(is);
  546. return Saml2X509Credential.verification(certificate);
  547. }
  548. ----
  549. .Kotlin
  550. [source,kotlin,role="secondary"]
  551. ----
  552. val resource = ClassPathResource("ap.crt")
  553. resource.inputStream.use {
  554. return Saml2X509Credential.verification(
  555. CertificateFactory.getInstance("X.509").generateCertificate(it) as X509Certificate?
  556. )
  557. }
  558. ----
  559. ====
  560. Suppose that the asserting party is going to also encrypt the assertion.
  561. In that case, the relying party needs a private key to decrypt the encrypted value.
  562. In that case, you need an `RSAPrivateKey` as well as its corresponding `X509Certificate`.
  563. You can load the first by using Spring Security's `RsaKeyConverters` utility class and the second as you did before:
  564. ====
  565. .Java
  566. [source,java,role="primary"]
  567. ----
  568. X509Certificate certificate = relyingPartyDecryptionCertificate();
  569. Resource resource = new ClassPathResource("rp.crt");
  570. try (InputStream is = resource.getInputStream()) {
  571. RSAPrivateKey rsa = RsaKeyConverters.pkcs8().convert(is);
  572. return Saml2X509Credential.decryption(rsa, certificate);
  573. }
  574. ----
  575. .Kotlin
  576. [source,kotlin,role="secondary"]
  577. ----
  578. val certificate: X509Certificate = relyingPartyDecryptionCertificate()
  579. val resource = ClassPathResource("rp.crt")
  580. resource.inputStream.use {
  581. val rsa: RSAPrivateKey = RsaKeyConverters.pkcs8().convert(it)
  582. return Saml2X509Credential.decryption(rsa, certificate)
  583. }
  584. ----
  585. ====
  586. [TIP]
  587. ====
  588. When you specify the locations of these files as the appropriate Spring Boot properties, Spring Boot performs these conversions for you.
  589. ====
  590. [[servlet-saml2login-rpr-relyingpartyregistrationresolver]]
  591. === Resolving the Relying Party from the Request
  592. As seen so far, Spring Security resolves the `RelyingPartyRegistration` by looking for the registration ID in the URI path.
  593. You may want to customize for a number of reasons, including:
  594. * You may know that your application is never going to be a multi-tenant application and, as a result, want a simpler URL scheme.
  595. * You may identify tenants in a way other than by the URI path.
  596. To customize the way that a `RelyingPartyRegistration` is resolved, you can configure a custom `RelyingPartyRegistrationResolver`.
  597. The default looks up the registration ID from the URI's last path element and looks it up in your `RelyingPartyRegistrationRepository`.
  598. You can provide a simpler resolver that, for example, always returns the same relying party:
  599. ====
  600. .Java
  601. [source,java,role="primary"]
  602. ----
  603. public class SingleRelyingPartyRegistrationResolver implements RelyingPartyRegistrationResolver {
  604. private final RelyingPartyRegistrationResolver delegate;
  605. public SingleRelyingPartyRegistrationResolver(RelyingPartyRegistrationRepository registrations) {
  606. this.delegate = new DefaultRelyingPartyRegistrationResolver(registrations);
  607. }
  608. @Override
  609. public RelyingPartyRegistration resolve(HttpServletRequest request, String registrationId) {
  610. return this.delegate.resolve(request, "single");
  611. }
  612. }
  613. ----
  614. .Kotlin
  615. [source,kotlin,role="secondary"]
  616. ----
  617. class SingleRelyingPartyRegistrationResolver(delegate: RelyingPartyRegistrationResolver) : RelyingPartyRegistrationResolver {
  618. override fun resolve(request: HttpServletRequest?, registrationId: String?): RelyingPartyRegistration? {
  619. return this.delegate.resolve(request, "single")
  620. }
  621. }
  622. ----
  623. ====
  624. 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].
  625. [NOTE]
  626. ====
  627. Remember that if you have any placeholders in your `RelyingPartyRegistration`, your resolver implementation should resolve them.
  628. ====
  629. [[servlet-saml2login-rpr-duplicated]]
  630. === Duplicated Relying Party Configurations
  631. When an application uses multiple asserting parties, some configuration is duplicated between `RelyingPartyRegistration` instances:
  632. * The relying party's `entityId`
  633. * Its `assertionConsumerServiceLocation`
  634. * Its credentials -- for example, its signing or decryption credentials
  635. This setup may let credentials be more easily rotated for some identity providers versus others.
  636. The duplication can be alleviated in a few different ways.
  637. First, in YAML this can be alleviated with references:
  638. ====
  639. [source,yaml]
  640. ----
  641. spring:
  642. security:
  643. saml2:
  644. relyingparty:
  645. okta:
  646. signing.credentials: &relying-party-credentials
  647. - private-key-location: classpath:rp.key
  648. certificate-location: classpath:rp.crt
  649. identityprovider:
  650. entity-id: ...
  651. azure:
  652. signing.credentials: *relying-party-credentials
  653. identityprovider:
  654. entity-id: ...
  655. ----
  656. ====
  657. Second, in a database, you need not replicate the model of `RelyingPartyRegistration`.
  658. Third, in Java, you can create a custom configuration method:
  659. ====
  660. .Java
  661. [source,java,role="primary"]
  662. ----
  663. private RelyingPartyRegistration.Builder
  664. addRelyingPartyDetails(RelyingPartyRegistration.Builder builder) {
  665. Saml2X509Credential signingCredential = ...
  666. builder.signingX509Credentials(c -> c.addAll(signingCredential));
  667. // ... other relying party configurations
  668. }
  669. @Bean
  670. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  671. RelyingPartyRegistration okta = addRelyingPartyDetails(
  672. RelyingPartyRegistrations
  673. .fromMetadataLocation(oktaMetadataUrl)
  674. .registrationId("okta")).build();
  675. RelyingPartyRegistration azure = addRelyingPartyDetails(
  676. RelyingPartyRegistrations
  677. .fromMetadataLocation(oktaMetadataUrl)
  678. .registrationId("azure")).build();
  679. return new InMemoryRelyingPartyRegistrationRepository(okta, azure);
  680. }
  681. ----
  682. .Kotlin
  683. [source,kotlin,role="secondary"]
  684. ----
  685. private fun addRelyingPartyDetails(builder: RelyingPartyRegistration.Builder): RelyingPartyRegistration.Builder {
  686. val signingCredential: Saml2X509Credential = ...
  687. builder.signingX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  688. c.add(
  689. signingCredential
  690. )
  691. }
  692. // ... other relying party configurations
  693. }
  694. @Bean
  695. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  696. val okta = addRelyingPartyDetails(
  697. RelyingPartyRegistrations
  698. .fromMetadataLocation(oktaMetadataUrl)
  699. .registrationId("okta")
  700. ).build()
  701. val azure = addRelyingPartyDetails(
  702. RelyingPartyRegistrations
  703. .fromMetadataLocation(oktaMetadataUrl)
  704. .registrationId("azure")
  705. ).build()
  706. return InMemoryRelyingPartyRegistrationRepository(okta, azure)
  707. }
  708. ----
  709. ====