saml2-login.adoc 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. [[servlet-saml2login]]
  2. == SAML 2.0 Login
  3. :figures: images/servlet/saml2
  4. :icondir: images/icons
  5. The SAML 2.0 Login feature provides an application with the capability to act as a SAML 2.0 Relying Party, having users https://wiki.shibboleth.net/confluence/display/CONCEPT/FlowsAndConfig[log in] to the application by using their existing account at a SAML 2.0 Asserting Party (Okta, ADFS, etc).
  6. NOTE: SAML 2.0 Login is implemented by using the *Web Browser SSO Profile*, as specified in
  7. https://www.oasis-open.org/committees/download.php/35389/sstc-saml-profiles-errata-2.0-wd-06-diff.pdf#page=15[SAML 2 Profiles].
  8. [[servlet-saml2login-spring-security-history]]
  9. Since 2009, support for relying parties has existed as an https://github.com/spring-projects/spring-security-saml/tree/1e013b07a7772defd6a26fcfae187c9bf661ee8f#spring-saml[extension project].
  10. In 2019, the process began to port that into https://github.com/spring-projects/spring-security[Spring Security] proper.
  11. This process is similar to the one started in 2017 for xref:servlet/oauth2/index.adoc[Spring Security's OAuth 2.0 support].
  12. [NOTE]
  13. ====
  14. A working sample for {gh-samples-url}/servlet/spring-boot/java/saml2-login[SAML 2.0 Login] is available in the {gh-samples-url}[Spring Security Samples repository].
  15. ====
  16. Let's take a look at how SAML 2.0 Relying Party Authentication works within Spring Security.
  17. First, we see that, like xref:servlet/oauth2/oauth2-login.adoc[OAuth 2.0 Login], Spring Security takes the user to a third-party for performing authentication.
  18. It does this through a series of redirects.
  19. .Redirecting to Asserting Party Authentication
  20. image::{figures}/saml2webssoauthenticationrequestfilter.png[]
  21. The figure above builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] and xref:servlet/authentication/architecture.adoc#servlet-authentication-abstractprocessingfilter[`AbstractAuthenticationProcessingFilter`] diagrams:
  22. image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized.
  23. 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`.
  24. image:{icondir}/number_3.png[] Since the user lacks authorization, the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__.
  25. 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`.
  26. Or, if you've <<servlet-saml2login-relyingpartyregistrationrepository,configured more than one asserting party>>, it will first redirect to a picker page.
  27. 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`>>.
  28. image:{icondir}/number_5.png[] Then, the browser takes this `<saml2:AuthnRequest>` and presents it to the asserting party.
  29. The asserting party attempts to authentication the user.
  30. If successful, it will return a `<saml2:Response>` back to the browser.
  31. image:{icondir}/number_6.png[] The browser then POSTs the `<saml2:Response>` to the assertion consumer service endpoint.
  32. [[servlet-saml2login-authentication-saml2webssoauthenticationfilter]]
  33. .Authenticating a `<saml2:Response>`
  34. image::{figures}/saml2webssoauthenticationfilter.png[]
  35. The figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram.
  36. image:{icondir}/number_1.png[] When the browser submits a `<saml2:Response>` to the application, it <<servlet-saml2login-authenticate-responses, delegates to `Saml2WebSsoAuthenticationFilter`>>.
  37. This filter calls its configured `AuthenticationConverter` to create a `Saml2AuthenticationToken` by extracting the response from the `HttpServletRequest`.
  38. This converter additionally resolves the <<servlet-saml2login-relyingpartyregistration, `RelyingPartyRegistration`>> and supplies it to `Saml2AuthenticationToken`.
  39. image:{icondir}/number_2.png[] Next, the filter passes the token to its configured xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`].
  40. By default, it will use the <<servlet-saml2login-architecture,`OpenSAML authentication provider`>>.
  41. image:{icondir}/number_3.png[] If authentication fails, then __Failure__
  42. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] is cleared out.
  43. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is invoked to restart the authentication process.
  44. image:{icondir}/number_4.png[] If authentication is successful, then __Success__.
  45. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`].
  46. * The `Saml2WebSsoAuthenticationFilter` invokes `FilterChain#doFilter(request,response)` to continue with the rest of the application logic.
  47. [[servlet-saml2login-minimaldependencies]]
  48. === Minimal Dependencies
  49. SAML 2.0 service provider support resides in `spring-security-saml2-service-provider`.
  50. It builds off of the OpenSAML library.
  51. [[servlet-saml2login-minimalconfiguration]]
  52. === Minimal Configuration
  53. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a service provider consists of two basic steps.
  54. First, include the needed dependencies and second, indicate the necessary asserting party metadata.
  55. [NOTE]
  56. Also, this presupposes that you've already <<servlet-saml2login-metadata, registered the relying party with your asserting party>>.
  57. ==== Specifying Identity Provider Metadata
  58. In a Spring Boot application, to specify an identity provider's metadata, simply do:
  59. [source,yml]
  60. ----
  61. spring:
  62. security:
  63. saml2:
  64. relyingparty:
  65. registration:
  66. adfs:
  67. identityprovider:
  68. entity-id: https://idp.example.com/issuer
  69. verification.credentials:
  70. - certificate-location: "classpath:idp.crt"
  71. singlesignon.url: https://idp.example.com/issuer/sso
  72. singlesignon.sign-request: false
  73. ----
  74. where
  75. * `https://idp.example.com/issuer` is the value contained in the `Issuer` attribute of the SAML responses that the identity provider will issue
  76. * `classpath:idp.crt` is the location on the classpath for the identity provider's certificate for verifying SAML responses, and
  77. * `https://idp.example.com/issuer/sso` is the endpoint where the identity provider is expecting ``AuthnRequest``s.
  78. * `adfs` is <<servlet-saml2login-relyingpartyregistrationid, an arbitrary identifier you choose>>
  79. And that's it!
  80. [NOTE]
  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. ==== Runtime Expectations
  84. As configured above, the application processes any `+POST /login/saml2/sso/{registrationId}+` request containing a `SAMLResponse` parameter:
  85. [source,html]
  86. ----
  87. POST /login/saml2/sso/adfs HTTP/1.1
  88. SAMLResponse=PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZ...
  89. ----
  90. There are two ways to see induce your asserting party to generate a `SAMLResponse`:
  91. * First, you can navigate to your asserting party.
  92. It likely has some kind of link or button for each registered relying party that you can click to send the `SAMLResponse`.
  93. * Second, you can navigate to a protected page in your app, for example, `http://localhost:8080`.
  94. Your app then redirects to the configured asserting party which then sends the `SAMLResponse`.
  95. From here, consider jumping to:
  96. * <<servlet-saml2login-architecture,How SAML 2.0 Login Integrates with OpenSAML>>
  97. * <<servlet-saml2login-authenticatedprincipal,How to Use the `Saml2AuthenticatedPrincipal`>>
  98. * <<servlet-saml2login-sansboot,How to Override or Replace Spring Boot's Auto Configuration>>
  99. [[servlet-saml2login-architecture]]
  100. === How SAML 2.0 Login Integrates with OpenSAML
  101. Spring Security's SAML 2.0 support has a couple of design goals:
  102. * First, rely on a library for SAML 2.0 operations and domain objects.
  103. To achieve this, Spring Security uses OpenSAML.
  104. * Second, ensure this library is not required when using Spring Security's SAML support.
  105. To achieve this, any interfaces or classes where Spring Security uses OpenSAML in the contract remain encapsulated.
  106. This makes it possible for you to switch out OpenSAML for some other library or even an unsupported version of OpenSAML.
  107. As a natural outcome of the above two goals, Spring Security's SAML API is quite small relative to other modules.
  108. Instead, classes like `OpenSaml4AuthenticationRequestFactory` and `OpenSaml4AuthenticationProvider` expose ``Converter``s that customize various steps in the authentication process.
  109. For example, once your application receives a `SAMLResponse` and delegates to `Saml2WebSsoAuthenticationFilter`, the filter will delegate to `OpenSaml4AuthenticationProvider`.
  110. [NOTE]
  111. For backward compatibility, Spring Security will use the latest OpenSAML 3 by default.
  112. Note, though that OpenSAML 3 has reached it's end-of-life and updating to OpenSAML 4.x is recommended.
  113. For that reason, Spring Security supports both OpenSAML 3.x and 4.x.
  114. If you manage your OpenSAML dependency to 4.x, then Spring Security will select its OpenSAML 4.x implementations.
  115. .Authenticating an OpenSAML `Response`
  116. image:{figures}/opensamlauthenticationprovider.png[]
  117. This figure builds off of the <<servlet-saml2login-authentication-saml2webssoauthenticationfilter,`Saml2WebSsoAuthenticationFilter` diagram>>.
  118. image:{icondir}/number_1.png[] The `Saml2WebSsoAuthenticationFilter` formulates the `Saml2AuthenticationToken` and invokes the xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`].
  119. image:{icondir}/number_2.png[] The xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`AuthenticationManager`] invokes the OpenSAML authentication provider.
  120. image:{icondir}/number_3.png[] The authentication provider deserializes the response into an OpenSAML `Response` and checks its signature.
  121. If the signature is invalid, authentication fails.
  122. image:{icondir}/number_4.png[] Then, the provider <<servlet-saml2login-opensamlauthenticationprovider-decryption,decrypts any `EncryptedAssertion` elements>>.
  123. If any decryptions fail, authentication fails.
  124. image:{icondir}/number_5.png[] Next, the provider validates the response's `Issuer` and `Destination` values.
  125. If they don't match what's in the `RelyingPartyRegistration`, authentication fails.
  126. image:{icondir}/number_6.png[] After that, the provider verifies the signature of each `Assertion`.
  127. If any signature is invalid, authentication fails.
  128. Also, if neither the response nor the assertions have signatures, authentication fails.
  129. Either the response or all the assertions must have signatures.
  130. image:{icondir}/number_7.png[] Then, the provider <<servlet-saml2login-opensamlauthenticationprovider-decryption,decrypts any `EncryptedID` or `EncryptedAttribute` elements>>.
  131. If any decryptions fail, authentication fails.
  132. image:{icondir}/number_8.png[] Next, the provider validates each assertion's `ExpiresAt` and `NotBefore` timestamps, the `<Subject>` and any `<AudienceRestriction>` conditions.
  133. If any validations fail, authentication fails.
  134. image:{icondir}/number_9.png[] Following that, the provider takes the first assertion's `AttributeStatement` and maps it to a `Map<String, List<Object>>`.
  135. It also grants the `ROLE_USER` granted authority.
  136. 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`.
  137. Then, it places that principal and the authorities into a `Saml2Authentication`.
  138. The resulting `Authentication#getPrincipal` is a Spring Security `Saml2AuthenticatedPrincipal` object, and `Authentication#getName` maps to the first assertion's `NameID` element.
  139. `Saml2AuthenticatedPrincipal#getRelyingPartyRegistrationId` holds the <<servlet-saml2login-relyingpartyregistrationid,identifier to the associated `RelyingPartyRegistration`>>.
  140. [[servlet-saml2login-opensaml-customization]]
  141. ==== Customizing OpenSAML Configuration
  142. Any class that uses both Spring Security and OpenSAML should statically initialize `OpenSamlInitializationService` at the beginning of the class, like so:
  143. ====
  144. .Java
  145. [source,java,role="primary"]
  146. ----
  147. static {
  148. OpenSamlInitializationService.initialize();
  149. }
  150. ----
  151. .Kotlin
  152. [source,kotlin,role="secondary"]
  153. ----
  154. companion object {
  155. init {
  156. OpenSamlInitializationService.initialize()
  157. }
  158. }
  159. ----
  160. ====
  161. This replaces OpenSAML's `InitializationService#initialize`.
  162. Occasionally, it can be valuable to customize how OpenSAML builds, marshalls, and unmarshalls SAML objects.
  163. In these circumstances, you may instead want to call `OpenSamlInitializationService#requireInitialize(Consumer)` that gives you access to OpenSAML's `XMLObjectProviderFactory`.
  164. For example, when sending an unsigned AuthNRequest, you may want to force reauthentication.
  165. In that case, you can register your own `AuthnRequestMarshaller`, like so:
  166. ====
  167. .Java
  168. [source,java,role="primary"]
  169. ----
  170. static {
  171. OpenSamlInitializationService.requireInitialize(factory -> {
  172. AuthnRequestMarshaller marshaller = new AuthnRequestMarshaller() {
  173. @Override
  174. public Element marshall(XMLObject object, Element element) throws MarshallingException {
  175. configureAuthnRequest((AuthnRequest) object);
  176. return super.marshall(object, element);
  177. }
  178. public Element marshall(XMLObject object, Document document) throws MarshallingException {
  179. configureAuthnRequest((AuthnRequest) object);
  180. return super.marshall(object, document);
  181. }
  182. private void configureAuthnRequest(AuthnRequest authnRequest) {
  183. authnRequest.setForceAuthn(true);
  184. }
  185. }
  186. factory.getMarshallerFactory().registerMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME, marshaller);
  187. });
  188. }
  189. ----
  190. .Kotlin
  191. [source,kotlin,role="secondary"]
  192. ----
  193. companion object {
  194. init {
  195. OpenSamlInitializationService.requireInitialize {
  196. val marshaller = object : AuthnRequestMarshaller() {
  197. override fun marshall(xmlObject: XMLObject, element: Element): Element {
  198. configureAuthnRequest(xmlObject as AuthnRequest)
  199. return super.marshall(xmlObject, element)
  200. }
  201. override fun marshall(xmlObject: XMLObject, document: Document): Element {
  202. configureAuthnRequest(xmlObject as AuthnRequest)
  203. return super.marshall(xmlObject, document)
  204. }
  205. private fun configureAuthnRequest(authnRequest: AuthnRequest) {
  206. authnRequest.isForceAuthn = true
  207. }
  208. }
  209. it.marshallerFactory.registerMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME, marshaller)
  210. }
  211. }
  212. }
  213. ----
  214. ====
  215. The `requireInitialize` method may only be called once per application instance.
  216. [[servlet-saml2login-sansboot]]
  217. === Overriding or Replacing Boot Auto Configuration
  218. There are two ``@Bean``s that Spring Boot generates for a relying party.
  219. The first is a `WebSecurityConfigurerAdapter` that configures the app as a relying party.
  220. When including `spring-security-saml2-service-provider`, the `WebSecurityConfigurerAdapter` looks like:
  221. .Default JWT Configuration
  222. ====
  223. .Java
  224. [source,java,role="primary"]
  225. ----
  226. protected void configure(HttpSecurity http) {
  227. http
  228. .authorizeRequests(authorize -> authorize
  229. .anyRequest().authenticated()
  230. )
  231. .saml2Login(withDefaults());
  232. }
  233. ----
  234. .Kotlin
  235. [source,kotlin,role="secondary"]
  236. ----
  237. fun configure(http: HttpSecurity) {
  238. http {
  239. authorizeRequests {
  240. authorize(anyRequest, authenticated)
  241. }
  242. saml2Login { }
  243. }
  244. }
  245. ----
  246. ====
  247. If the application doesn't expose a `WebSecurityConfigurerAdapter` bean, then Spring Boot will expose the above default one.
  248. You can replace this by exposing the bean within the application:
  249. .Custom SAML 2.0 Login Configuration
  250. ====
  251. .Java
  252. [source,java,role="primary"]
  253. ----
  254. @EnableWebSecurity
  255. public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
  256. protected void configure(HttpSecurity http) {
  257. http
  258. .authorizeRequests(authorize -> authorize
  259. .mvcMatchers("/messages/**").hasAuthority("ROLE_USER")
  260. .anyRequest().authenticated()
  261. )
  262. .saml2Login(withDefaults());
  263. }
  264. }
  265. ----
  266. .Kotlin
  267. [source,kotlin,role="secondary"]
  268. ----
  269. @EnableWebSecurity
  270. class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
  271. override fun configure(http: HttpSecurity) {
  272. http {
  273. authorizeRequests {
  274. authorize("/messages/**", hasAuthority("ROLE_USER"))
  275. authorize(anyRequest, authenticated)
  276. }
  277. saml2Login {
  278. }
  279. }
  280. }
  281. }
  282. ----
  283. ====
  284. The above requires the role of `USER` for any URL that starts with `/messages/`.
  285. [[servlet-saml2login-relyingpartyregistrationrepository]]
  286. 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.
  287. This includes things like the location of the SSO endpoint the relying party should use when requesting authentication from the asserting party.
  288. You can override the default by publishing your own `RelyingPartyRegistrationRepository` bean.
  289. For example, you can look up the asserting party's configuration by hitting its metadata endpoint like so:
  290. .Relying Party Registration Repository
  291. ====
  292. .Java
  293. [source,java,role="primary"]
  294. ----
  295. @Value("${metadata.location}")
  296. String assertingPartyMetadataLocation;
  297. @Bean
  298. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  299. RelyingPartyRegistration registration = RelyingPartyRegistrations
  300. .fromMetadataLocation(assertingPartyMetadataLocation)
  301. .registrationId("example")
  302. .build();
  303. return new InMemoryRelyingPartyRegistrationRepository(registration);
  304. }
  305. ----
  306. .Kotlin
  307. [source,kotlin,role="secondary"]
  308. ----
  309. @Value("\${metadata.location}")
  310. var assertingPartyMetadataLocation: String? = null
  311. @Bean
  312. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  313. val registration = RelyingPartyRegistrations
  314. .fromMetadataLocation(assertingPartyMetadataLocation)
  315. .registrationId("example")
  316. .build()
  317. return InMemoryRelyingPartyRegistrationRepository(registration)
  318. }
  319. ----
  320. ====
  321. [[servlet-saml2login-relyingpartyregistrationid]]
  322. [NOTE]
  323. The `registrationId` is an arbitrary value that you choose for differentiating between registrations.
  324. Or you can provide each detail manually, as you can see below:
  325. .Relying Party Registration Repository Manual Configuration
  326. ====
  327. .Java
  328. [source,java,role="primary"]
  329. ----
  330. @Value("${verification.key}")
  331. File verificationKey;
  332. @Bean
  333. public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception {
  334. X509Certificate certificate = X509Support.decodeCertificate(this.verificationKey);
  335. Saml2X509Credential credential = Saml2X509Credential.verification(certificate);
  336. RelyingPartyRegistration registration = RelyingPartyRegistration
  337. .withRegistrationId("example")
  338. .assertingPartyDetails(party -> party
  339. .entityId("https://idp.example.com/issuer")
  340. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  341. .wantAuthnRequestsSigned(false)
  342. .verificationX509Credentials(c -> c.add(credential))
  343. )
  344. .build();
  345. return new InMemoryRelyingPartyRegistrationRepository(registration);
  346. }
  347. ----
  348. .Kotlin
  349. [source,kotlin,role="secondary"]
  350. ----
  351. @Value("\${verification.key}")
  352. var verificationKey: File? = null
  353. @Bean
  354. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository {
  355. val certificate: X509Certificate? = X509Support.decodeCertificate(verificationKey!!)
  356. val credential: Saml2X509Credential = Saml2X509Credential.verification(certificate)
  357. val registration = RelyingPartyRegistration
  358. .withRegistrationId("example")
  359. .assertingPartyDetails { party: AssertingPartyDetails.Builder ->
  360. party
  361. .entityId("https://idp.example.com/issuer")
  362. .singleSignOnServiceLocation("https://idp.example.com/SSO.saml2")
  363. .wantAuthnRequestsSigned(false)
  364. .verificationX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  365. c.add(
  366. credential
  367. )
  368. }
  369. }
  370. .build()
  371. return InMemoryRelyingPartyRegistrationRepository(registration)
  372. }
  373. ----
  374. ====
  375. [NOTE]
  376. Note that `X509Support` is an OpenSAML class, used here in the snippet for brevity
  377. [[servlet-saml2login-relyingpartyregistrationrepository-dsl]]
  378. Alternatively, you can directly wire up the repository using the DSL, which will also override the auto-configured `WebSecurityConfigurerAdapter`:
  379. .Custom Relying Party Registration DSL
  380. ====
  381. .Java
  382. [source,java,role="primary"]
  383. ----
  384. @EnableWebSecurity
  385. public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
  386. protected void configure(HttpSecurity http) {
  387. http
  388. .authorizeRequests(authorize -> authorize
  389. .mvcMatchers("/messages/**").hasAuthority("ROLE_USER")
  390. .anyRequest().authenticated()
  391. )
  392. .saml2Login(saml2 -> saml2
  393. .relyingPartyRegistrationRepository(relyingPartyRegistrations())
  394. );
  395. }
  396. }
  397. ----
  398. .Kotlin
  399. [source,kotlin,role="secondary"]
  400. ----
  401. @EnableWebSecurity
  402. class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
  403. override fun configure(http: HttpSecurity) {
  404. http {
  405. authorizeRequests {
  406. authorize("/messages/**", hasAuthority("ROLE_USER"))
  407. authorize(anyRequest, authenticated)
  408. }
  409. saml2Login {
  410. relyingPartyRegistrationRepository = relyingPartyRegistrations()
  411. }
  412. }
  413. }
  414. }
  415. ----
  416. ====
  417. [NOTE]
  418. A relying party can be multi-tenant by registering more than one relying party in the `RelyingPartyRegistrationRepository`.
  419. [[servlet-saml2login-relyingpartyregistration]]
  420. === RelyingPartyRegistration
  421. A {security-api-url}org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.html[`RelyingPartyRegistration`]
  422. instance represents a link between an relying party and assering party's metadata.
  423. In a `RelyingPartyRegistration`, you can provide relying party metadata like its `Issuer` value, where it expects SAML Responses to be sent to, and any credentials that it owns for the purposes of signing or decrypting payloads.
  424. Also, you can provide asserting party metadata like its `Issuer` value, where it expects AuthnRequests to be sent to, and any public credentials that it owns for the purposes of the relying party verifying or encrypting payloads.
  425. The following `RelyingPartyRegistration` is the minimum required for most setups:
  426. ====
  427. .Java
  428. [source,java,role="primary"]
  429. ----
  430. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
  431. .fromMetadataLocation("https://ap.example.org/metadata")
  432. .registrationId("my-id")
  433. .build();
  434. ----
  435. .Kotlin
  436. [source,kotlin,role="secondary"]
  437. ----
  438. val relyingPartyRegistration = RelyingPartyRegistrations
  439. .fromMetadataLocation("https://ap.example.org/metadata")
  440. .registrationId("my-id")
  441. .build()
  442. ----
  443. ====
  444. Note that you can also create a `RelyingPartyRegistration` from an arbitrary `InputStream` source.
  445. One such example is when the metadata is stored in a database:
  446. [source,java]
  447. ----
  448. String xml = fromDatabase();
  449. try (InputStream source = new ByteArrayInputStream(xml.getBytes())) {
  450. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations
  451. .fromMetadata(source)
  452. .registrationId("my-id")
  453. .build();
  454. }
  455. ----
  456. Though a more sophisticated setup is also possible, like so:
  457. ====
  458. .Java
  459. [source,java,role="primary"]
  460. ----
  461. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("my-id")
  462. .entityId("{baseUrl}/{registrationId}")
  463. .decryptionX509Credentials(c -> c.add(relyingPartyDecryptingCredential()))
  464. .assertionConsumerServiceLocation("/my-login-endpoint/{registrationId}")
  465. .assertingPartyDetails(party -> party
  466. .entityId("https://ap.example.org")
  467. .verificationX509Credentials(c -> c.add(assertingPartyVerifyingCredential()))
  468. .singleSignOnServiceLocation("https://ap.example.org/SSO.saml2")
  469. )
  470. .build();
  471. ----
  472. .Kotlin
  473. [source,kotlin,role="secondary"]
  474. ----
  475. val relyingPartyRegistration =
  476. RelyingPartyRegistration.withRegistrationId("my-id")
  477. .entityId("{baseUrl}/{registrationId}")
  478. .decryptionX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  479. c.add(relyingPartyDecryptingCredential())
  480. }
  481. .assertionConsumerServiceLocation("/my-login-endpoint/{registrationId}")
  482. .assertingPartyDetails { party -> party
  483. .entityId("https://ap.example.org")
  484. .verificationX509Credentials { c -> c.add(assertingPartyVerifyingCredential()) }
  485. .singleSignOnServiceLocation("https://ap.example.org/SSO.saml2")
  486. }
  487. .build()
  488. ----
  489. ====
  490. [TIP]
  491. The top-level metadata methods are details about the relying party.
  492. The methods inside `assertingPartyDetails` are details about the asserting party.
  493. [NOTE]
  494. The location where a relying party is expecting SAML Responses is the Assertion Consumer Service Location.
  495. The default for the relying party's `entityId` is `+{baseUrl}/saml2/service-provider-metadata/{registrationId}+`.
  496. This is this value needed when configuring the asserting party to know about your relying party.
  497. The default for the `assertionConsumerServiceLocation` is `+/login/saml2/sso/{registrationId}+`.
  498. It's mapped by default to <<servlet-saml2login-authentication-saml2webssoauthenticationfilter,`Saml2WebSsoAuthenticationFilter`>> in the filter chain.
  499. [[servlet-saml2login-rpr-uripatterns]]
  500. ==== URI Patterns
  501. You probably noticed in the above examples the `+{baseUrl}+` and `+{registrationId}+` placeholders.
  502. These are useful for generating URIs. As such, the relying party's `entityId` and `assertionConsumerServiceLocation` support the following placeholders:
  503. * `baseUrl` - the scheme, host, and port of a deployed application
  504. * `registrationId` - the registration id for this relying party
  505. * `baseScheme` - the scheme of a deployed application
  506. * `baseHost` - the host of a deployed application
  507. * `basePort` - the port of a deployed application
  508. For example, the `assertionConsumerServiceLocation` defined above was:
  509. `+/my-login-endpoint/{registrationId}+`
  510. which in a deployed application would translate to
  511. `+/my-login-endpoint/adfs+`
  512. The `entityId` above was defined as:
  513. `+{baseUrl}/{registrationId}+`
  514. which in a deployed application would translate to
  515. `+https://rp.example.com/adfs+`
  516. [[servlet-saml2login-rpr-credentials]]
  517. ==== Credentials
  518. You also likely noticed the credential that was used.
  519. Oftentimes, a relying party will use the same key to sign payloads as well as decrypt them.
  520. Or it will use the same key to verify payloads as well as encrypt them.
  521. Because of this, Spring Security ships with `Saml2X509Credential`, a SAML-specific credential that simplifies configuring the same key for different use cases.
  522. At a minimum, it's necessary to have a certificate from the asserting party so that the asserting party's signed responses can be verified.
  523. To construct a `Saml2X509Credential` that you'll use to verify assertions from the asserting party, you can load the file and use
  524. the `CertificateFactory` like so:
  525. ====
  526. .Java
  527. [source,java,role="primary"]
  528. ----
  529. Resource resource = new ClassPathResource("ap.crt");
  530. try (InputStream is = resource.getInputStream()) {
  531. X509Certificate certificate = (X509Certificate)
  532. CertificateFactory.getInstance("X.509").generateCertificate(is);
  533. return Saml2X509Credential.verification(certificate);
  534. }
  535. ----
  536. .Kotlin
  537. [source,kotlin,role="secondary"]
  538. ----
  539. val resource = ClassPathResource("ap.crt")
  540. resource.inputStream.use {
  541. return Saml2X509Credential.verification(
  542. CertificateFactory.getInstance("X.509").generateCertificate(it) as X509Certificate?
  543. )
  544. }
  545. ----
  546. ====
  547. Let's say that the asserting party is going to also encrypt the assertion.
  548. In that case, the relying party will need a private key to be able to decrypt the encrypted value.
  549. In that case, you'll need an `RSAPrivateKey` as well as its corresponding `X509Certificate`.
  550. You can load the first using Spring Security's `RsaKeyConverters` utility class and the second as you did before:
  551. ====
  552. .Java
  553. [source,java,role="primary"]
  554. ----
  555. X509Certificate certificate = relyingPartyDecryptionCertificate();
  556. Resource resource = new ClassPathResource("rp.crt");
  557. try (InputStream is = resource.getInputStream()) {
  558. RSAPrivateKey rsa = RsaKeyConverters.pkcs8().convert(is);
  559. return Saml2X509Credential.decryption(rsa, certificate);
  560. }
  561. ----
  562. .Kotlin
  563. [source,kotlin,role="secondary"]
  564. ----
  565. val certificate: X509Certificate = relyingPartyDecryptionCertificate()
  566. val resource = ClassPathResource("rp.crt")
  567. resource.inputStream.use {
  568. val rsa: RSAPrivateKey = RsaKeyConverters.pkcs8().convert(it)
  569. return Saml2X509Credential.decryption(rsa, certificate)
  570. }
  571. ----
  572. ====
  573. [TIP]
  574. When you specify the locations of these files as the appropriate Spring Boot properties, then Spring Boot will perform these conversions for you.
  575. [[servlet-saml2login-rpr-relyingpartyregistrationresolver]]
  576. ==== Resolving the Relying Party from the Request
  577. As seen so far, Spring Security resolves the `RelyingPartyRegistration` by looking for the registration id in the URI path.
  578. There are a number of reasons you may want to customize. Among them:
  579. * You may know that you will never be a multi-tenant application and so want to have a simpler URL scheme
  580. * You may identify tenants in a way other than by the URI path
  581. To customize the way that a `RelyingPartyRegistration` is resolved, you can configure a custom `RelyingPartyRegistrationResolver`.
  582. The default looks up the registration id from the URI's last path element and looks it up in your `RelyingPartyRegistrationRepository`.
  583. You can provide a simpler resolver that, for example, always returns the same relying party:
  584. ====
  585. .Java
  586. [source,java,role="primary"]
  587. ----
  588. public class SingleRelyingPartyRegistrationResolver implements RelyingPartyRegistrationResolver {
  589. private final RelyingPartyRegistrationResolver delegate;
  590. public SingleRelyingPartyRegistrationResolver(RelyingPartyRegistrationRepository registrations) {
  591. this.delegate = new DefaultRelyingPartyRegistrationResolver(registrations);
  592. }
  593. @Override
  594. public RelyingPartyRegistration resolve(HttpServletRequest request, String registrationId) {
  595. return this.delegate.resolve(request, "single");
  596. }
  597. }
  598. ----
  599. .Kotlin
  600. [source,kotlin,role="secondary"]
  601. ----
  602. class SingleRelyingPartyRegistrationResolver(delegate: RelyingPartyRegistrationResolver) : RelyingPartyRegistrationResolver {
  603. override fun resolve(request: HttpServletRequest?, registrationId: String?): RelyingPartyRegistration? {
  604. return this.delegate.resolve(request, "single")
  605. }
  606. }
  607. ----
  608. ====
  609. Then, you can provide this resolver to the appropriate filters that <<servlet-saml2login-sp-initiated-factory, produce ``<saml2:AuthnRequest>``s>>, <<servlet-saml2login-authenticate-responses, authenticate ``<saml2:Response>``s>>, and <<servlet-saml2login-metadata, produce `<saml2:SPSSODescriptor>` metadata>>.
  610. [NOTE]
  611. Remember that if you have any placeholders in your `RelyingPartyRegistration`, your resolver implementation should resolve them.
  612. [[servlet-saml2login-rpr-duplicated]]
  613. ==== Duplicated Relying Party Configurations
  614. When an application uses multiple asserting parties, some configuration is duplicated between `RelyingPartyRegistration` instances:
  615. * The relying party's `entityId`
  616. * Its `assertionConsumerServiceLocation`, and
  617. * Its credentials, for example its signing or decryption credentials
  618. What's nice about this setup is credentials may be more easily rotated for some identity providers vs others.
  619. The duplication can be alleviated in a few different ways.
  620. First, in YAML this can be alleviated with references, like so:
  621. [source,yaml]
  622. ----
  623. spring:
  624. security:
  625. saml2:
  626. relyingparty:
  627. okta:
  628. signing.credentials: &relying-party-credentials
  629. - private-key-location: classpath:rp.key
  630. certificate-location: classpath:rp.crt
  631. identityprovider:
  632. entity-id: ...
  633. azure:
  634. signing.credentials: *relying-party-credentials
  635. identityprovider:
  636. entity-id: ...
  637. ----
  638. Second, in a database, it's not necessary to replicate `RelyingPartyRegistration` 's model.
  639. Third, in Java, you can create a custom configuration method, like so:
  640. ====
  641. .Java
  642. [source,java,role="primary"]
  643. ----
  644. private RelyingPartyRegistration.Builder
  645. addRelyingPartyDetails(RelyingPartyRegistration.Builder builder) {
  646. Saml2X509Credential signingCredential = ...
  647. builder.signingX509Credentials(c -> c.addAll(signingCredential));
  648. // ... other relying party configurations
  649. }
  650. @Bean
  651. public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
  652. RelyingPartyRegistration okta = addRelyingPartyDetails(
  653. RelyingPartyRegistrations
  654. .fromMetadataLocation(oktaMetadataUrl)
  655. .registrationId("okta")).build();
  656. RelyingPartyRegistration azure = addRelyingPartyDetails(
  657. RelyingPartyRegistrations
  658. .fromMetadataLocation(oktaMetadataUrl)
  659. .registrationId("azure")).build();
  660. return new InMemoryRelyingPartyRegistrationRepository(okta, azure);
  661. }
  662. ----
  663. .Kotlin
  664. [source,kotlin,role="secondary"]
  665. ----
  666. private fun addRelyingPartyDetails(builder: RelyingPartyRegistration.Builder): RelyingPartyRegistration.Builder {
  667. val signingCredential: Saml2X509Credential = ...
  668. builder.signingX509Credentials { c: MutableCollection<Saml2X509Credential?> ->
  669. c.add(
  670. signingCredential
  671. )
  672. }
  673. // ... other relying party configurations
  674. }
  675. @Bean
  676. open fun relyingPartyRegistrations(): RelyingPartyRegistrationRepository? {
  677. val okta = addRelyingPartyDetails(
  678. RelyingPartyRegistrations
  679. .fromMetadataLocation(oktaMetadataUrl)
  680. .registrationId("okta")
  681. ).build()
  682. val azure = addRelyingPartyDetails(
  683. RelyingPartyRegistrations
  684. .fromMetadataLocation(oktaMetadataUrl)
  685. .registrationId("azure")
  686. ).build()
  687. return InMemoryRelyingPartyRegistrationRepository(okta, azure)
  688. }
  689. ----
  690. ====
  691. [[servlet-saml2login-sp-initiated-factory]]
  692. === Producing ``<saml2:AuthnRequest>``s
  693. As stated earlier, Spring Security's SAML 2.0 support produces a `<saml2:AuthnRequest>` to commence authentication with the asserting party.
  694. Spring Security achieves this in part by registering the `Saml2WebSsoAuthenticationRequestFilter` in the filter chain.
  695. This filter by default responds to endpoint `+/saml2/authenticate/{registrationId}+`.
  696. For example, if you were deployed to `https://rp.example.com` and you gave your registration an ID of `okta`, you could navigate to:
  697. `https://rp.example.org/saml2/authenticate/ping`
  698. and the result would be a redirect that included a `SAMLRequest` parameter containing the signed, deflated, and encoded `<saml2:AuthnRequest>`.
  699. [[servlet-saml2login-store-authn-request]]
  700. ==== Changing How the `<saml2:AuthnRequest>` Gets Stored
  701. `Saml2WebSsoAuthenticationRequestFilter` uses an `Saml2AuthenticationRequestRepository` to persist an `AbstractSaml2AuthenticationRequest` instance before <<servlet-saml2login-sp-initiated-factory,sending the `<saml2:AuthnRequest>`>> to the asserting party.
  702. Additionally, `Saml2WebSsoAuthenticationFilter` and `Saml2AuthenticationTokenConverter` use an `Saml2AuthenticationRequestRepository` to load any `AbstractSaml2AuthenticationRequest` as part of <<servlet-saml2login-authenticate-responses,authenticating the `<saml2:Response>`>>.
  703. By default, Spring Security uses an `HttpSessionSaml2AuthenticationRequestRepository`, which stores the `AbstractSaml2AuthenticationRequest` in the `HttpSession`.
  704. If you have a custom implementation of `Saml2AuthenticationRequestRepository`, you may configure it by exposing it as a `@Bean` as shown in the following example:
  705. ====
  706. .Java
  707. [source,java,role="primary"]
  708. ----
  709. @Bean
  710. Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository() {
  711. return new CustomSaml2AuthenticationRequestRepository();
  712. }
  713. ----
  714. .Kotlin
  715. [source,kotlin,role="secondary"]
  716. ----
  717. @Bean
  718. open fun authenticationRequestRepository(): Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> {
  719. return CustomSaml2AuthenticationRequestRepository()
  720. }
  721. ----
  722. ====
  723. [[servlet-saml2login-sp-initiated-factory-signing]]
  724. ==== Changing How the `<saml2:AuthnRequest>` Gets Sent
  725. By default, Spring Security signs each `<saml2:AuthnRequest>` and send it as a GET to the asserting party.
  726. Many asserting parties don't require a signed `<saml2:AuthnRequest>`.
  727. This can be configured automatically via `RelyingPartyRegistrations`, or you can supply it manually, like so:
  728. .Not Requiring Signed AuthnRequests
  729. ====
  730. .Boot
  731. [source,yaml,role="primary"]
  732. ----
  733. spring:
  734. security:
  735. saml2:
  736. relyingparty:
  737. okta:
  738. identityprovider:
  739. entity-id: ...
  740. singlesignon.sign-request: false
  741. ----
  742. .Java
  743. [source,java,role="secondary"]
  744. ----
  745. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("okta")
  746. // ...
  747. .assertingPartyDetails(party -> party
  748. // ...
  749. .wantAuthnRequestsSigned(false)
  750. )
  751. .build();
  752. ----
  753. .Kotlin
  754. [source,java,role="secondary"]
  755. ----
  756. var relyingPartyRegistration: RelyingPartyRegistration =
  757. RelyingPartyRegistration.withRegistrationId("okta")
  758. // ...
  759. .assertingPartyDetails { party: AssertingPartyDetails.Builder -> party
  760. // ...
  761. .wantAuthnRequestsSigned(false)
  762. }
  763. .build();
  764. ----
  765. ====
  766. Otherwise, you will need to specify a private key to `RelyingPartyRegistration#signingX509Credentials` so that Spring Security can sign the `<saml2:AuthnRequest>` before sending.
  767. [[servlet-saml2login-sp-initiated-factory-algorithm]]
  768. By default, Spring Security will sign the `<saml2:AuthnRequest>` using `rsa-sha256`, though some asserting parties will require a different algorithm, as indicated in their metadata.
  769. You can configure the algorithm based on the asserting party's <<servlet-saml2login-relyingpartyregistrationrepository,metadata using `RelyingPartyRegistrations`>>.
  770. Or, you can provide it manually:
  771. ====
  772. .Java
  773. [source,java,role="primary"]
  774. ----
  775. String metadataLocation = "classpath:asserting-party-metadata.xml";
  776. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistrations.fromMetadataLocation(metadataLocation)
  777. // ...
  778. .assertingPartyDetails((party) -> party
  779. // ...
  780. .signingAlgorithms((sign) -> sign.add(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA512))
  781. )
  782. .build();
  783. ----
  784. .Kotlin
  785. [source,kotlin,role="secondary"]
  786. ----
  787. var metadataLocation = "classpath:asserting-party-metadata.xml"
  788. var relyingPartyRegistration: RelyingPartyRegistration =
  789. RelyingPartyRegistrations.fromMetadataLocation(metadataLocation)
  790. // ...
  791. .assertingPartyDetails { party: AssertingPartyDetails.Builder -> party
  792. // ...
  793. .signingAlgorithms { sign: MutableList<String?> ->
  794. sign.add(
  795. SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA512
  796. )
  797. }
  798. }
  799. .build();
  800. ----
  801. ====
  802. NOTE: The snippet above uses the OpenSAML `SignatureConstants` class to supply the algorithm name.
  803. But, that's just for convenience.
  804. Since the datatype is `String`, you can supply the name of the algorithm directly.
  805. [[servlet-saml2login-sp-initiated-factory-binding]]
  806. Some asserting parties require that the `<saml2:AuthnRequest>` be POSTed.
  807. This can be configured automatically via `RelyingPartyRegistrations`, or you can supply it manually, like so:
  808. ====
  809. .Java
  810. [source,java,role="primary"]
  811. ----
  812. RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("okta")
  813. // ...
  814. .assertingPartyDetails(party -> party
  815. // ...
  816. .singleSignOnServiceBinding(Saml2MessageBinding.POST)
  817. )
  818. .build();
  819. ----
  820. .Kotlin
  821. [source,kotlin,role="secondary"]
  822. ----
  823. var relyingPartyRegistration: RelyingPartyRegistration? =
  824. RelyingPartyRegistration.withRegistrationId("okta")
  825. // ...
  826. .assertingPartyDetails { party: AssertingPartyDetails.Builder -> party
  827. // ...
  828. .singleSignOnServiceBinding(Saml2MessageBinding.POST)
  829. }
  830. .build()
  831. ----
  832. ====
  833. [[servlet-saml2login-sp-initiated-factory-custom-authnrequest]]
  834. ==== Customizing OpenSAML's `AuthnRequest` Instance
  835. There are a number of reasons that you may want to adjust an `AuthnRequest`.
  836. For example, you may want `ForceAuthN` to be set to `true`, which Spring Security sets to `false` by default.
  837. If you don't need information from the `HttpServletRequest` to make your decision, then the easiest way is to <<servlet-saml2login-opensaml-customization,register a custom `AuthnRequestMarshaller` with OpenSAML>>.
  838. This will give you access to post-process the `AuthnRequest` instance before it's serialized.
  839. But, if you do need something from the request, then you can use create a custom `Saml2AuthenticationRequestContext` implementation and then a `Converter<Saml2AuthenticationRequestContext, AuthnRequest>` to build an `AuthnRequest` yourself, like so:
  840. ====
  841. .Java
  842. [source,java,role="primary"]
  843. ----
  844. @Component
  845. public class AuthnRequestConverter implements
  846. Converter<MySaml2AuthenticationRequestContext, AuthnRequest> {
  847. private final AuthnRequestBuilder authnRequestBuilder;
  848. private final IssuerBuilder issuerBuilder;
  849. // ... constructor
  850. public AuthnRequest convert(Saml2AuthenticationRequestContext context) {
  851. MySaml2AuthenticationRequestContext myContext = (MySaml2AuthenticationRequestContext) context;
  852. Issuer issuer = issuerBuilder.buildObject();
  853. issuer.setValue(myContext.getIssuer());
  854. AuthnRequest authnRequest = authnRequestBuilder.buildObject();
  855. authnRequest.setIssuer(issuer);
  856. authnRequest.setDestination(myContext.getDestination());
  857. authnRequest.setAssertionConsumerServiceURL(myContext.getAssertionConsumerServiceUrl());
  858. // ... additional settings
  859. authRequest.setForceAuthn(myContext.getForceAuthn());
  860. return authnRequest;
  861. }
  862. }
  863. ----
  864. .Kotlin
  865. [source,kotlin,role="secondary"]
  866. ----
  867. @Component
  868. class AuthnRequestConverter : Converter<MySaml2AuthenticationRequestContext, AuthnRequest> {
  869. private val authnRequestBuilder: AuthnRequestBuilder? = null
  870. private val issuerBuilder: IssuerBuilder? = null
  871. // ... constructor
  872. override fun convert(context: MySaml2AuthenticationRequestContext): AuthnRequest {
  873. val myContext: MySaml2AuthenticationRequestContext = context
  874. val issuer: Issuer = issuerBuilder.buildObject()
  875. issuer.value = myContext.getIssuer()
  876. val authnRequest: AuthnRequest = authnRequestBuilder.buildObject()
  877. authnRequest.issuer = issuer
  878. authnRequest.destination = myContext.getDestination()
  879. authnRequest.assertionConsumerServiceURL = myContext.getAssertionConsumerServiceUrl()
  880. // ... additional settings
  881. authRequest.setForceAuthn(myContext.getForceAuthn())
  882. return authnRequest
  883. }
  884. }
  885. ----
  886. ====
  887. Then, you can construct your own `Saml2AuthenticationRequestContextResolver` and `Saml2AuthenticationRequestFactory` and publish them as ``@Bean``s:
  888. ====
  889. .Java
  890. [source,java,role="primary"]
  891. ----
  892. @Bean
  893. Saml2AuthenticationRequestContextResolver authenticationRequestContextResolver() {
  894. Saml2AuthenticationRequestContextResolver resolver =
  895. new DefaultSaml2AuthenticationRequestContextResolver();
  896. return request -> {
  897. Saml2AuthenticationRequestContext context = resolver.resolve(request);
  898. return new MySaml2AuthenticationRequestContext(context, request.getParameter("force") != null);
  899. };
  900. }
  901. @Bean
  902. Saml2AuthenticationRequestFactory authenticationRequestFactory(
  903. AuthnRequestConverter authnRequestConverter) {
  904. OpenSaml4AuthenticationRequestFactory authenticationRequestFactory =
  905. new OpenSaml4AuthenticationRequestFactory();
  906. authenticationRequestFactory.setAuthenticationRequestContextConverter(authnRequestConverter);
  907. return authenticationRequestFactory;
  908. }
  909. ----
  910. .Kotlin
  911. [source,kotlin,role="secondary"]
  912. ----
  913. @Bean
  914. open fun authenticationRequestContextResolver(): Saml2AuthenticationRequestContextResolver {
  915. val resolver: Saml2AuthenticationRequestContextResolver = DefaultSaml2AuthenticationRequestContextResolver()
  916. return Saml2AuthenticationRequestContextResolver { request: HttpServletRequest ->
  917. val context = resolver.resolve(request)
  918. MySaml2AuthenticationRequestContext(
  919. context,
  920. request.getParameter("force") != null
  921. )
  922. }
  923. }
  924. @Bean
  925. open fun authenticationRequestFactory(
  926. authnRequestConverter: AuthnRequestConverter?
  927. ): Saml2AuthenticationRequestFactory? {
  928. val authenticationRequestFactory = OpenSaml4AuthenticationRequestFactory()
  929. authenticationRequestFactory.setAuthenticationRequestContextConverter(authnRequestConverter)
  930. return authenticationRequestFactory
  931. }
  932. ----
  933. ====
  934. [[servlet-saml2login-authenticate-responses]]
  935. === Authenticating ``<saml2:Response>``s
  936. To verify SAML 2.0 Responses, Spring Security uses <<servlet-saml2login-architecture,`OpenSaml4AuthenticationProvider`>> by default.
  937. You can configure this in a number of ways including:
  938. 1. Setting a clock skew to timestamp validation
  939. 2. Mapping the response to a list of `GrantedAuthority` instances
  940. 3. Customizing the strategy for validating assertions
  941. 4. Customizing the strategy for decrypting response and assertion elements
  942. To configure these, you'll use the `saml2Login#authenticationManager` method in the DSL.
  943. [[servlet-saml2login-opensamlauthenticationprovider-clockskew]]
  944. ==== Setting a Clock Skew
  945. It's not uncommon for the asserting and relying parties to have system clocks that aren't perfectly synchronized.
  946. For that reason, you can configure `OpenSaml4AuthenticationProvider` 's default assertion validator with some tolerance:
  947. ====
  948. .Java
  949. [source,java,role="primary"]
  950. ----
  951. @EnableWebSecurity
  952. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  953. @Override
  954. protected void configure(HttpSecurity http) throws Exception {
  955. OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
  956. authenticationProvider.setAssertionValidator(OpenSaml4AuthenticationProvider
  957. .createDefaultAssertionValidator(assertionToken -> {
  958. Map<String, Object> params = new HashMap<>();
  959. params.put(CLOCK_SKEW, Duration.ofMinutes(10).toMillis());
  960. // ... other validation parameters
  961. return new ValidationContext(params);
  962. })
  963. );
  964. http
  965. .authorizeRequests(authz -> authz
  966. .anyRequest().authenticated()
  967. )
  968. .saml2Login(saml2 -> saml2
  969. .authenticationManager(new ProviderManager(authenticationProvider))
  970. );
  971. }
  972. }
  973. ----
  974. .Kotlin
  975. [source,kotlin,role="secondary"]
  976. ----
  977. @EnableWebSecurity
  978. open class SecurityConfig : WebSecurityConfigurerAdapter() {
  979. override fun configure(http: HttpSecurity) {
  980. val authenticationProvider = OpenSaml4AuthenticationProvider()
  981. authenticationProvider.setAssertionValidator(
  982. OpenSaml4AuthenticationProvider
  983. .createDefaultAssertionValidator(Converter<OpenSaml4AuthenticationProvider.AssertionToken, ValidationContext> {
  984. val params: MutableMap<String, Any> = HashMap()
  985. params[CLOCK_SKEW] =
  986. Duration.ofMinutes(10).toMillis()
  987. ValidationContext(params)
  988. })
  989. )
  990. http {
  991. authorizeRequests {
  992. authorize(anyRequest, authenticated)
  993. }
  994. saml2Login {
  995. authenticationManager = ProviderManager(authenticationProvider)
  996. }
  997. }
  998. }
  999. }
  1000. ----
  1001. ====
  1002. [[servlet-saml2login-opensamlauthenticationprovider-userdetailsservice]]
  1003. ==== Coordinating with a `UserDetailsService`
  1004. Or, perhaps you would like to include user details from a legacy `UserDetailsService`.
  1005. In that case, the response authentication converter can come in handy, as can be seen below:
  1006. ====
  1007. .Java
  1008. [source,java,role="primary"]
  1009. ----
  1010. @EnableWebSecurity
  1011. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  1012. @Autowired
  1013. UserDetailsService userDetailsService;
  1014. @Override
  1015. protected void configure(HttpSecurity http) throws Exception {
  1016. OpenSaml4AuthenticationProvider authenticationProvider = new OpenSaml4AuthenticationProvider();
  1017. authenticationProvider.setResponseAuthenticationConverter(responseToken -> {
  1018. Saml2Authentication authentication = OpenSaml4AuthenticationProvider
  1019. .createDefaultResponseAuthenticationConverter() <1>
  1020. .convert(responseToken);
  1021. Assertion assertion = responseToken.getResponse().getAssertions().get(0);
  1022. String username = assertion.getSubject().getNameID().getValue();
  1023. UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); <2>
  1024. return MySaml2Authentication(userDetails, authentication); <3>
  1025. });
  1026. http
  1027. .authorizeRequests(authz -> authz
  1028. .anyRequest().authenticated()
  1029. )
  1030. .saml2Login(saml2 -> saml2
  1031. .authenticationManager(new ProviderManager(authenticationProvider))
  1032. );
  1033. }
  1034. }
  1035. ----
  1036. .Kotlin
  1037. [source,kotlin,role="secondary"]
  1038. ----
  1039. @EnableWebSecurity
  1040. open class SecurityConfig : WebSecurityConfigurerAdapter() {
  1041. @Autowired
  1042. var userDetailsService: UserDetailsService? = null
  1043. override fun configure(http: HttpSecurity) {
  1044. val authenticationProvider = OpenSaml4AuthenticationProvider()
  1045. authenticationProvider.setResponseAuthenticationConverter { responseToken: OpenSaml4AuthenticationProvider.ResponseToken ->
  1046. val authentication = OpenSaml4AuthenticationProvider
  1047. .createDefaultResponseAuthenticationConverter() <1>
  1048. .convert(responseToken)
  1049. val assertion: Assertion = responseToken.response.assertions[0]
  1050. val username: String = assertion.subject.nameID.value
  1051. val userDetails = userDetailsService!!.loadUserByUsername(username) <2>
  1052. MySaml2Authentication(userDetails, authentication) <3>
  1053. }
  1054. http {
  1055. authorizeRequests {
  1056. authorize(anyRequest, authenticated)
  1057. }
  1058. saml2Login {
  1059. authenticationManager = ProviderManager(authenticationProvider)
  1060. }
  1061. }
  1062. }
  1063. }
  1064. ----
  1065. ====
  1066. <1> First, call the default converter, which extracts attributes and authorities from the response
  1067. <2> Second, call the xref:servlet/authentication/passwords/user-details-service.adoc#servlet-authentication-userdetailsservice[`UserDetailsService`] using the relevant information
  1068. <3> Third, return a custom authentication that includes the user details
  1069. [NOTE]
  1070. It's not required to call `OpenSaml4AuthenticationProvider` 's default authentication converter.
  1071. It returns a `Saml2AuthenticatedPrincipal` containing the attributes it extracted from ``AttributeStatement``s as well as the single `ROLE_USER` authority.
  1072. [[servlet-saml2login-opensamlauthenticationprovider-additionalvalidation]]
  1073. ==== Performing Additional Response Validation
  1074. `OpenSaml4AuthenticationProvider` validates the `Issuer` and `Destination` values right after decrypting the `Response`.
  1075. You can customize the validation by extending the default validator concatenating with your own response validator, or you can replace it entirely with yours.
  1076. For example, you can throw a custom exception with any additional information available in the `Response` object, like so:
  1077. [source,java]
  1078. ----
  1079. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  1080. provider.setResponseValidator((responseToken) -> {
  1081. Saml2ResponseValidatorResult result = OpenSamlAuthenticationProvider
  1082. .createDefaultResponseValidator()
  1083. .convert(responseToken)
  1084. .concat(myCustomValidator.convert(responseToken));
  1085. if (!result.getErrors().isEmpty()) {
  1086. String inResponseTo = responseToken.getInResponseTo();
  1087. throw new CustomSaml2AuthenticationException(result, inResponseTo);
  1088. }
  1089. return result;
  1090. });
  1091. ----
  1092. ==== Performing Additional Assertion Validation
  1093. `OpenSaml4AuthenticationProvider` performs minimal validation on SAML 2.0 Assertions.
  1094. After verifying the signature, it will:
  1095. 1. Validate `<AudienceRestriction>` and `<DelegationRestriction>` conditions
  1096. 2. Validate ``<SubjectConfirmation>``s, expect for any IP address information
  1097. To perform additional validation, you can configure your own assertion validator that delegates to `OpenSaml4AuthenticationProvider` 's default and then performs its own.
  1098. [[servlet-saml2login-opensamlauthenticationprovider-onetimeuse]]
  1099. For example, you can use OpenSAML's `OneTimeUseConditionValidator` to also validate a `<OneTimeUse>` condition, like so:
  1100. ====
  1101. .Java
  1102. [source,java,role="primary"]
  1103. ----
  1104. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  1105. OneTimeUseConditionValidator validator = ...;
  1106. provider.setAssertionValidator(assertionToken -> {
  1107. Saml2ResponseValidatorResult result = OpenSaml4AuthenticationProvider
  1108. .createDefaultAssertionValidator()
  1109. .convert(assertionToken);
  1110. Assertion assertion = assertionToken.getAssertion();
  1111. OneTimeUse oneTimeUse = assertion.getConditions().getOneTimeUse();
  1112. ValidationContext context = new ValidationContext();
  1113. try {
  1114. if (validator.validate(oneTimeUse, assertion, context) == ValidationResult.VALID) {
  1115. return result;
  1116. }
  1117. } catch (Exception e) {
  1118. return result.concat(new Saml2Error(INVALID_ASSERTION, e.getMessage()));
  1119. }
  1120. return result.concat(new Saml2Error(INVALID_ASSERTION, context.getValidationFailureMessage()));
  1121. });
  1122. ----
  1123. .Kotlin
  1124. [source,kotlin,role="secondary"]
  1125. ----
  1126. var provider = OpenSaml4AuthenticationProvider()
  1127. var validator: OneTimeUseConditionValidator = ...
  1128. provider.setAssertionValidator { assertionToken ->
  1129. val result = OpenSaml4AuthenticationProvider
  1130. .createDefaultAssertionValidator()
  1131. .convert(assertionToken)
  1132. val assertion: Assertion = assertionToken.assertion
  1133. val oneTimeUse: OneTimeUse = assertion.conditions.oneTimeUse
  1134. val context = ValidationContext()
  1135. try {
  1136. if (validator.validate(oneTimeUse, assertion, context) == ValidationResult.VALID) {
  1137. return@setAssertionValidator result
  1138. }
  1139. } catch (e: Exception) {
  1140. return@setAssertionValidator result.concat(Saml2Error(INVALID_ASSERTION, e.message))
  1141. }
  1142. result.concat(Saml2Error(INVALID_ASSERTION, context.validationFailureMessage))
  1143. }
  1144. ----
  1145. ====
  1146. [NOTE]
  1147. While recommended, it's not necessary to call `OpenSaml4AuthenticationProvider` 's default assertion validator.
  1148. A circumstance where you would skip it would be if you don't need it to check the `<AudienceRestriction>` or the `<SubjectConfirmation>` since you are doing those yourself.
  1149. [[servlet-saml2login-opensamlauthenticationprovider-decryption]]
  1150. ==== Customizing Decryption
  1151. Spring Security decrypts `<saml2:EncryptedAssertion>`, `<saml2:EncryptedAttribute>`, and `<saml2:EncryptedID>` elements automatically by using the decryption <<servlet-saml2login-rpr-credentials,`Saml2X509Credential` instances>> registered in the <<servlet-saml2login-relyingpartyregistration,`RelyingPartyRegistration`>>.
  1152. `OpenSaml4AuthenticationProvider` exposes <<servlet-saml2login-architecture,two decryption strategies>>.
  1153. The response decrypter is for decrypting encrypted elements of the `<saml2:Response>`, like `<saml2:EncryptedAssertion>`.
  1154. The assertion decrypter is for decrypting encrypted elements of the `<saml2:Assertion>`, like `<saml2:EncryptedAttribute>` and `<saml2:EncryptedID>`.
  1155. You can replace `OpenSaml4AuthenticationProvider`'s default decryption strategy with your own.
  1156. For example, if you have a separate service that decrypts the assertions in a `<saml2:Response>`, you can use it instead like so:
  1157. ====
  1158. .Java
  1159. [source,java,role="primary"]
  1160. ----
  1161. MyDecryptionService decryptionService = ...;
  1162. OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
  1163. provider.setResponseElementsDecrypter((responseToken) -> decryptionService.decrypt(responseToken.getResponse()));
  1164. ----
  1165. .Kotlin
  1166. [source,kotlin,role="secondary"]
  1167. ----
  1168. val decryptionService: MyDecryptionService = ...
  1169. val provider = OpenSaml4AuthenticationProvider()
  1170. provider.setResponseElementsDecrypter { responseToken -> decryptionService.decrypt(responseToken.response) }
  1171. ----
  1172. ====
  1173. If you are also decrypting individual elements in a `<saml2:Assertion>`, you can customize the assertion decrypter, too:
  1174. ====
  1175. .Java
  1176. [source,java,role="primary"]
  1177. ----
  1178. provider.setAssertionElementsDecrypter((assertionToken) -> decryptionService.decrypt(assertionToken.getAssertion()));
  1179. ----
  1180. .Kotlin
  1181. [source,kotlin,role="secondary"]
  1182. ----
  1183. provider.setAssertionElementsDecrypter { assertionToken -> decryptionService.decrypt(assertionToken.assertion) }
  1184. ----
  1185. ====
  1186. NOTE: There are two separate decrypters since assertions can be signed separately from responses.
  1187. Trying to decrypt a signed assertion's elements before signature verification may invalidate the signature.
  1188. If your asserting party signs the response only, then it's safe to decrypt all elements using only the response decrypter.
  1189. [[servlet-saml2login-authenticationmanager-custom]]
  1190. ==== Using a Custom Authentication Manager
  1191. [[servlet-saml2login-opensamlauthenticationprovider-authenticationmanager]]
  1192. Of course, the `authenticationManager` DSL method can be also used to perform a completely custom SAML 2.0 authentication.
  1193. This authentication manager should expect a `Saml2AuthenticationToken` object containing the SAML 2.0 Response XML data.
  1194. ====
  1195. .Java
  1196. [source,java,role="primary"]
  1197. ----
  1198. @EnableWebSecurity
  1199. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  1200. @Override
  1201. protected void configure(HttpSecurity http) throws Exception {
  1202. AuthenticationManager authenticationManager = new MySaml2AuthenticationManager(...);
  1203. http
  1204. .authorizeRequests(authorize -> authorize
  1205. .anyRequest().authenticated()
  1206. )
  1207. .saml2Login(saml2 -> saml2
  1208. .authenticationManager(authenticationManager)
  1209. )
  1210. ;
  1211. }
  1212. }
  1213. ----
  1214. .Kotlin
  1215. [source,kotlin,role="secondary"]
  1216. ----
  1217. @EnableWebSecurity
  1218. open class SecurityConfig : WebSecurityConfigurerAdapter() {
  1219. override fun configure(http: HttpSecurity) {
  1220. val customAuthenticationManager: AuthenticationManager = MySaml2AuthenticationManager(...)
  1221. http {
  1222. authorizeRequests {
  1223. authorize(anyRequest, authenticated)
  1224. }
  1225. saml2Login {
  1226. authenticationManager = customAuthenticationManager
  1227. }
  1228. }
  1229. }
  1230. }
  1231. ----
  1232. ====
  1233. [[servlet-saml2login-authenticatedprincipal]]
  1234. === Using `Saml2AuthenticatedPrincipal`
  1235. With the relying party correctly configured for a given asserting party, it's ready to accept assertions.
  1236. Once the relying party validates an assertion, the result is a `Saml2Authentication` with a `Saml2AuthenticatedPrincipal`.
  1237. This means that you can access the principal in your controller like so:
  1238. ====
  1239. .Java
  1240. [source,java,role="primary"]
  1241. ----
  1242. @Controller
  1243. public class MainController {
  1244. @GetMapping("/")
  1245. public String index(@AuthenticationPrincipal Saml2AuthenticatedPrincipal principal, Model model) {
  1246. String email = principal.getFirstAttribute("email");
  1247. model.setAttribute("email", email);
  1248. return "index";
  1249. }
  1250. }
  1251. ----
  1252. .Kotlin
  1253. [source,kotlin,role="secondary"]
  1254. ----
  1255. @Controller
  1256. class MainController {
  1257. @GetMapping("/")
  1258. fun index(@AuthenticationPrincipal principal: Saml2AuthenticatedPrincipal, model: Model): String {
  1259. val email = principal.getFirstAttribute<String>("email")
  1260. model.setAttribute("email", email)
  1261. return "index"
  1262. }
  1263. }
  1264. ----
  1265. ====
  1266. [TIP]
  1267. Because the SAML 2.0 specification allows for each attribute to have multiple values, you can either call `getAttribute` to get the list of attributes or `getFirstAttribute` to get the first in the list.
  1268. `getFirstAttribute` is quite handy when you know that there is only one value.
  1269. [[servlet-saml2login-metadata]]
  1270. === Producing `<saml2:SPSSODescriptor>` Metadata
  1271. You can publish a metadata endpoint by adding the `Saml2MetadataFilter` to the filter chain, as you'll see below:
  1272. ====
  1273. .Java
  1274. [source,java,role="primary"]
  1275. ----
  1276. DefaultRelyingPartyRegistrationResolver relyingPartyRegistrationResolver =
  1277. new DefaultRelyingPartyRegistrationResolver(this.relyingPartyRegistrationRepository);
  1278. Saml2MetadataFilter filter = new Saml2MetadataFilter(
  1279. relyingPartyRegistrationResolver,
  1280. new OpenSamlMetadataResolver());
  1281. http
  1282. // ...
  1283. .saml2Login(withDefaults())
  1284. .addFilterBefore(filter, Saml2WebSsoAuthenticationFilter.class);
  1285. ----
  1286. .Kotlin
  1287. [source,kotlin,role="secondary"]
  1288. ----
  1289. val relyingPartyRegistrationResolver: Converter<HttpServletRequest, RelyingPartyRegistration> =
  1290. DefaultRelyingPartyRegistrationResolver(this.relyingPartyRegistrationRepository)
  1291. val filter = Saml2MetadataFilter(
  1292. relyingPartyRegistrationResolver,
  1293. OpenSamlMetadataResolver()
  1294. )
  1295. http {
  1296. //...
  1297. saml2Login { }
  1298. addFilterBefore<Saml2WebSsoAuthenticationFilter>(filter)
  1299. }
  1300. ----
  1301. ====
  1302. You can use this metadata endpoint to register your relying party with your asserting party.
  1303. This is often as simple as finding the correct form field to supply the metadata endpoint.
  1304. By default, the metadata endpoint is `+/saml2/service-provider-metadata/{registrationId}+`.
  1305. You can change this by calling the `setRequestMatcher` method on the filter:
  1306. ====
  1307. .Java
  1308. [source,java,role="primary"]
  1309. ----
  1310. filter.setRequestMatcher(new AntPathRequestMatcher("/saml2/metadata/{registrationId}", "GET"));
  1311. ----
  1312. .Kotlin
  1313. [source,kotlin,role="secondary"]
  1314. ----
  1315. filter.setRequestMatcher(AntPathRequestMatcher("/saml2/metadata/{registrationId}", "GET"))
  1316. ----
  1317. ====
  1318. Or, if you have registered a custom relying party registration resolver in the constructor, then you can specify a path without a `registrationId` hint, like so:
  1319. ====
  1320. .Java
  1321. [source,java,role="primary"]
  1322. ----
  1323. filter.setRequestMatcher(new AntPathRequestMatcher("/saml2/metadata", "GET"));
  1324. ----
  1325. .Kotlin
  1326. [source,kotlin,role="secondary"]
  1327. ----
  1328. filter.setRequestMatcher(AntPathRequestMatcher("/saml2/metadata", "GET"))
  1329. ----
  1330. ====
  1331. [[servlet-saml2login-logout]]
  1332. === Performing Single Logout
  1333. Spring Security ships with support for RP- and AP-initiated SAML 2.0 Single Logout.
  1334. Briefly, there are two use cases Spring Security supports:
  1335. * **RP-Initiated** - Your application has an endpoint that, when POSTed to, will logout the user and send a `saml2:LogoutRequest` to the asserting party.
  1336. Thereafter, the asserting party will send back a `saml2:LogoutResponse` and allow your application to respond
  1337. * **AP-Initiated** - Your application has an endpoint that will receive a `saml2:LogoutRequest` from the asserting party.
  1338. Your application will complete its logout at that point and then send a `saml2:LogoutResponse` to the asserting party.
  1339. [NOTE]
  1340. In the **AP-Initiated** scenario, any local redirection that your application would do post-logout is rendered moot.
  1341. Once your application sends a `saml2:LogoutResponse`, it no longer has control of the browser.
  1342. === Minimal Configuration for Single Logout
  1343. To use Spring Security's SAML 2.0 Single Logout feature, you will need the following things:
  1344. * First, the asserting party must support SAML 2.0 Single Logout
  1345. * Second, the asserting party should be configured to sign and POST `saml2:LogoutRequest` s and `saml2:LogoutResponse` s your application's `/logout/saml2/slo` endpoint
  1346. * Third, your application must have a PKCS#8 private key and X.509 certificate for signing `saml2:LogoutRequest` s and `saml2:LogoutResponse` s
  1347. You can begin from the initial minimal example and add the following configuration:
  1348. [source,java]
  1349. ----
  1350. @Value("${private.key}") RSAPrivateKey key;
  1351. @Value("${public.certificate}") X509Certificate certificate;
  1352. @Bean
  1353. RelyingPartyRegistrationRepository registrations() {
  1354. Saml2X509Credential credential = Saml2X509Credential.signing(key, certificate);
  1355. RelyingPartyRegistration registration = RelyingPartyRegistrations
  1356. .fromMetadataLocation("https://ap.example.org/metadata")
  1357. .registrationId("id")
  1358. .signingX509Credentials((signing) -> signing.add(credential)) <1>
  1359. .build();
  1360. return new InMemoryRelyingPartyRegistrationRepository(registration);
  1361. }
  1362. @Bean
  1363. SecurityFilterChain web(HttpSecurity http, RelyingPartyRegistrationRepository registrations) throws Exception {
  1364. http
  1365. .authorizeRequests((authorize) -> authorize
  1366. .anyRequest().authenticated()
  1367. )
  1368. .saml2Login(withDefaults())
  1369. .saml2Logout(withDefaults()); <2>
  1370. return http.build();
  1371. }
  1372. ----
  1373. <1> - First, add your signing key to the `RelyingPartyRegistration` instance or to <<servlet-saml2login-rpr-duplicated,multiple instances>>
  1374. <2> - Second, indicate that your application wants to use SAML SLO to logout the end user
  1375. ==== Runtime Expectations
  1376. Given the above configuration any logged in user can send a `POST /logout` to your application to perform RP-initiated SLO.
  1377. Your application will then do the following:
  1378. 1. Logout the user and invalidate the session
  1379. 2. Use a `Saml2LogoutRequestResolver` to create, sign, and serialize a `<saml2:LogoutRequest>` based on the <<servlet-saml2login-relyingpartyregistration,`RelyingPartyRegistration`>> associated with the currently logged-in user.
  1380. 3. Send a redirect or post to the asserting party based on the <<servlet-saml2login-relyingpartyregistration,`RelyingPartyRegistration`>>
  1381. 4. Deserialize, verify, and process the `<saml2:LogoutResponse>` sent by the asserting party
  1382. 5. Redirect to any configured successful logout endpoint
  1383. Also, your application can participate in an AP-initiated logout when the asserting party sends a `<saml2:LogoutRequest>` to `/logout/saml2/slo`:
  1384. 1. Use a `Saml2LogoutRequestHandler` to deserialize, verify, and process the `<saml2:LogoutRequest>` sent by the asserting party
  1385. 2. Logout the user and invalidate the session
  1386. 3. Create, sign, and serialize a `<saml2:LogoutResponse>` based on the <<servlet-saml2login-relyingpartyregistration,`RelyingPartyRegistration`>> associated with the just logged-out user
  1387. 4. Send a redirect or post to the asserting party based on the <<servlet-saml2login-relyingpartyregistration,`RelyingPartyRegistration`>>
  1388. === Configuring Logout Endpoints
  1389. There are three behaviors that can be triggered by different endpoints:
  1390. * RP-initiated logout, which allows an authenticated user to `POST` and trigger the logout process by sending the asserting party a `<saml2:LogoutRequest>`
  1391. * AP-initiated logout, which allows an asserting party to send a `<saml2:LogoutRequest>` to the application
  1392. * AP logout response, which allows an asserting party to send a `<saml2:LogoutResponse>` in response to the RP-initiated `<saml2:LogoutRequest>`
  1393. The first is triggered by performing normal `POST /logout` when the principal is of type `Saml2AuthenticatedPrincipal`.
  1394. The second is triggered by POSTing to the `/logout/saml2/slo` endpoint with a `SAMLRequest` signed by the asserting party.
  1395. The third is triggered by POSTing to the `/logout/saml2/slo` endpoint with a `SAMLResponse` signed by the asserting party.
  1396. Because the user is already logged in or the original Logout Request is known, the `registrationId` is already known.
  1397. For this reason, `+{registrationId}+` is not part of these URLs by default.
  1398. This URL is customizable in the DSL.
  1399. For example, if you are migrating your existing relying party over to Spring Security, your asserting party may already be pointing to `GET /SLOService.saml2`.
  1400. To reduce changes in configuration for the asserting party, you can configure the filter in the DSL like so:
  1401. ====
  1402. .Java
  1403. [source,java,role="primary"]
  1404. ----
  1405. http
  1406. .saml2Logout((saml2) -> saml2
  1407. .logoutRequest((request) -> request.logoutUrl("/SLOService.saml2"))
  1408. .logoutResponse((response) -> response.logoutUrl("/SLOService.saml2"))
  1409. );
  1410. ----
  1411. ====
  1412. You should also configure these endpoints in your `RelyingPartyRegistration`.
  1413. === Customizing `<saml2:LogoutRequest>` Resolution
  1414. It's common to need to set other values in the `<saml2:LogoutRequest>` than the defaults that Spring Security provides.
  1415. By default, Spring Security will issue a `<saml2:LogoutRequest>` and supply:
  1416. * The `Destination` attribute - from `RelyingPartyRegistration#getAssertingPartyDetails#getSingleLogoutServiceLocation`
  1417. * The `ID` attribute - a GUID
  1418. * The `<Issuer>` element - from `RelyingPartyRegistration#getEntityId`
  1419. * The `<NameID>` element - from `Authentication#getName`
  1420. To add other values, you can use delegation, like so:
  1421. [source,java]
  1422. ----
  1423. @Bean
  1424. Saml2LogoutRequestResolver logoutRequestResolver(RelyingPartyRegistrationResolver registrationResolver) {
  1425. OpenSaml4LogoutRequestResolver logoutRequestResolver
  1426. new OpenSaml4LogoutRequestResolver(registrationResolver);
  1427. logoutRequestResolver.setParametersConsumer((parameters) -> {
  1428. String name = ((Saml2AuthenticatedPrincipal) parameters.getAuthentication().getPrincipal()).getFirstAttribute("CustomAttribute");
  1429. String format = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient";
  1430. LogoutRequest logoutRequest = parameters.getLogoutRequest();
  1431. NameID nameId = logoutRequest.getNameID();
  1432. nameId.setValue(name);
  1433. nameId.setFormat(format);
  1434. });
  1435. return logoutRequestResolver;
  1436. }
  1437. ----
  1438. Then, you can supply your custom `Saml2LogoutRequestResolver` in the DSL as follows:
  1439. [source,java]
  1440. ----
  1441. http
  1442. .saml2Logout((saml2) -> saml2
  1443. .logoutRequest((request) -> request
  1444. .logoutRequestResolver(this.logoutRequestResolver)
  1445. )
  1446. );
  1447. ----
  1448. === Customizing `<saml2:LogoutResponse>` Resolution
  1449. It's common to need to set other values in the `<saml2:LogoutResponse>` than the defaults that Spring Security provides.
  1450. By default, Spring Security will issue a `<saml2:LogoutResponse>` and supply:
  1451. * The `Destination` attribute - from `RelyingPartyRegistration#getAssertingPartyDetails#getSingleLogoutServiceResponseLocation`
  1452. * The `ID` attribute - a GUID
  1453. * The `<Issuer>` element - from `RelyingPartyRegistration#getEntityId`
  1454. * The `<Status>` element - `SUCCESS`
  1455. To add other values, you can use delegation, like so:
  1456. [source,java]
  1457. ----
  1458. @Bean
  1459. public Saml2LogoutResponseResolver logoutResponseResolver(RelyingPartyRegistrationResolver registrationResolver) {
  1460. OpenSaml4LogoutResponseResolver logoutRequestResolver =
  1461. new OpenSaml3LogoutResponseResolver(relyingPartyRegistrationResolver);
  1462. logoutRequestResolver.setParametersConsumer((parameters) -> {
  1463. if (checkOtherPrevailingConditions(parameters.getRequest())) {
  1464. parameters.getLogoutRequest().getStatus().getStatusCode().setCode(StatusCode.PARTIAL_LOGOUT);
  1465. }
  1466. });
  1467. return logoutRequestResolver;
  1468. }
  1469. ----
  1470. Then, you can supply your custom `Saml2LogoutResponseResolver` in the DSL as follows:
  1471. [source,java]
  1472. ----
  1473. http
  1474. .saml2Logout((saml2) -> saml2
  1475. .logoutRequest((request) -> request
  1476. .logoutRequestResolver(this.logoutRequestResolver)
  1477. )
  1478. );
  1479. ----
  1480. === Customizing `<saml2:LogoutRequest>` Authentication
  1481. To customize validation, you can implement your own `Saml2LogoutRequestValidator`.
  1482. At this point, the validation is minimal, so you may be able to first delegate to the default `Saml2LogoutRequestValidator` like so:
  1483. [source,java]
  1484. ----
  1485. @Component
  1486. public class MyOpenSamlLogoutRequestValidator implements Saml2LogoutRequestValidator {
  1487. private final Saml2LogoutRequestValidator delegate = new OpenSamlLogoutRequestValidator();
  1488. @Override
  1489. public Saml2LogoutRequestValidator logout(Saml2LogoutRequestValidatorParameters parameters) {
  1490. // verify signature, issuer, destination, and principal name
  1491. Saml2LogoutValidatorResult result = delegate.authenticate(authentication);
  1492. LogoutRequest logoutRequest = // ... parse using OpenSAML
  1493. // perform custom validation
  1494. }
  1495. }
  1496. ----
  1497. Then, you can supply your custom `Saml2LogoutRequestValidator` in the DSL as follows:
  1498. [source,java]
  1499. ----
  1500. http
  1501. .saml2Logout((saml2) -> saml2
  1502. .logoutRequest((request) -> request
  1503. .logoutRequestAuthenticator(myOpenSamlLogoutRequestAuthenticator)
  1504. )
  1505. );
  1506. ----
  1507. === Customizing `<saml2:LogoutResponse>` Authentication
  1508. To customize validation, you can implement your own `Saml2LogoutResponseValidator`.
  1509. At this point, the validation is minimal, so you may be able to first delegate to the default `Saml2LogoutResponseValidator` like so:
  1510. [source,java]
  1511. ----
  1512. @Component
  1513. public class MyOpenSamlLogoutResponseValidator implements Saml2LogoutResponseValidator {
  1514. private final Saml2LogoutResponseValidator delegate = new OpenSamlLogoutResponseValidator();
  1515. @Override
  1516. public Saml2LogoutValidatorResult logout(Saml2LogoutResponseValidatorParameters parameters) {
  1517. // verify signature, issuer, destination, and status
  1518. Saml2LogoutValidatorResult result = delegate.authenticate(parameters);
  1519. LogoutResponse logoutResponse = // ... parse using OpenSAML
  1520. // perform custom validation
  1521. }
  1522. }
  1523. ----
  1524. Then, you can supply your custom `Saml2LogoutResponseValidator` in the DSL as follows:
  1525. [source,java]
  1526. ----
  1527. http
  1528. .saml2Logout((saml2) -> saml2
  1529. .logoutResponse((response) -> response
  1530. .logoutResponseAuthenticator(myOpenSamlLogoutResponseAuthenticator)
  1531. )
  1532. );
  1533. ----
  1534. === Customizing `<saml2:LogoutRequest>` storage
  1535. When your application sends a `<saml2:LogoutRequest>`, the value is stored in the session so that the `RelayState` parameter and the `InResponseTo` attribute in the `<saml2:LogoutResponse>` can be verified.
  1536. If you want to store logout requests in some place other than the session, you can supply your custom implementation in the DSL, like so:
  1537. [source,java]
  1538. ----
  1539. http
  1540. .saml2Logout((saml2) -> saml2
  1541. .logoutRequest((request) -> request
  1542. .logoutRequestRepository(myCustomLogoutRequestRepository)
  1543. )
  1544. );
  1545. ----