Search code examples
springspring-security

How to declare spring security to return response code with custome login-form when login is redirected?


Whenever the application gets redirected to custom login form the response code is always 200. Is there any way to identify whether the current 200 status code is either from the URL requested from user OR the custom login URL redirected by spring security.

.and().formLogin()      
      .loginPage("/login").usernameParameter("userName").passwordParameter("password")

Reason for the ask- Because the response from actual user request never come back as failure, spring always just send 200 response with login form.

I have set the customized login form which gets displayed when user send a direct URL request which needs to be authorized and this works fine but here is the catch. so lets say, i requested a URL which needs authentication, and expect that api should returns 401, unauthorized. Obviously spring intercepts the request and it does not reach the backend controller but instead spring redirects to loginform with "200" success response code.

so i will not be able to check whether user has been intercepted and redirected to formlogin by checking the response code. Now why do i need it? because i am using angularJS in front end, so i have different angularJS controllers for all the pages. Now lets say i requested for profile page which needs authentication so i can not just return formlogin until i assign correct angularJS controller to the page. so i need to know when the user has been redirected to formlogin using response code returned.

Another reason is , i am using AgularJS interceptors to check response sucess and failures, so i expectc that once my API call gets rejected due to unauthorized access, i should go into "response rejected" interceptor block but see this comes to "response success" interceptor block as Spring has intercepted the request and change it to 200 success with login form page URL returned.


Solution

  • You can try:

    .and()
    .formLogin()
        .loginPage("/login")
        .usernameParameter("userName")
        .passwordParameter("password")
        .successHandler(
    
           ( request, response, authentication ) -> {
              response.setHeader( "Location", "Your angular url");
              response.setHeader( "message", "authenticated" ); // <-custom http header as redirection does not allow content inside response body
              response.setStatus( HttpServletResponse.SC_FOUND ); // <- redirection status
           }
        )
        .failureHandler( 
    
           ( request, response, authenticationException ) -> {
    
              response.setHeader( "Location", "Your angular url");
              response.setHeader( "message", "error" );
              response.setStatus( HttpServletResponse.SC_FOUND );
           }
        );
    

    There are endless options!! If i haven't understand your question let me know.

    Cheers,