Set custom response headers on Spring Security authentication success URL

Viewed 638

After a successful SAML 2.0 login on a Spring Security application acting as service provider, I can redirect the user to a static success URL using:

@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.saml2Login(saml2Login -> saml2Login.defaultSuccessUrl(mySuccessUrl);
    }
}

How can I (dynamically) set these other pieces of information?

  • URL parameters
  • Response headers
  • Cookies

So far, I found a (rather cumbersome) solution: set an AuthenticationSuccessHandler with a custom RedirectStrategy.

SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
handler.setDefaultTargetUrl(relayState);
handler.setRedirectStrategy(new DefaultRedirectStrategy() {
    @Override
    public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
        // do stuff ...
        // set response headers ...
        // set cookies ...
        // add a query string to the redirect URL ...
        super.sendRedirect(request, response, url);
    }
});
http.saml2Login(saml2Login -> saml2Login.successHandler(handler));

Are there better alternatives?

I am using Spring Boot 2.3 and Spring Security 5.2.

0 Answers
Related