RaVin
RaVin

Reputation: 63

Configure Spring Security to return JSON response after authentication

I have a legacy application that is in spring 4 with UI as JSP. Need move the presentation layer from spring to react app. When I call /login with parameters it gives me an HTML, How do I change my existing spring security logic so that it returns a json response.

Here is the code snippet

protected void configure(HttpSecurity http) throws Exception {      
        http.sessionManagement().maximumSessions(1).and().invalidSessionUrl(URLConstants.LOGIN_URL);
        http.csrf().disable();
        http.anonymous().disable()
                .authorizeRequests().antMatchers("/")
                .access("hasRole('USER') or hasRole('ADMIN') or hasRole('DC MANAGER')")
.and().formLogin()          .loginProcessingUrl(URLConstants.LOGIN_URL).usernameParameter("ssoId").passwordParameter("password").and()
.rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)               .tokenValiditySeconds(18400).and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }

Upvotes: 0

Views: 1393

Answers (1)

Marco Behler
Marco Behler

Reputation: 3724

Write a custom AuthenticationSuccessHandler that writes your JSON and plug it into your formLogin().

.formLogin().successHandler(yourSucessHandlerBean);

Your handler could roughly look like this:

@Component
public class Securityhandler implements AuthenticationSuccessHandler {

 public void onAuthenticationSuccess(HttpServletRequest request,   HttpServletResponse response, Authentication authentication) throws IOException  {
    // write your JSON here, directly to the HttpServletResponse
 }

}

Upvotes: 1

Related Questions