Search code examples
spring-bootspring-mvcspring-securityajaxform

Spring security does not redirect after successful login authentication


I am using spring security + thymeleaf to recognise my css and javascript files. These css and javascript files make up my front end login page, and for special reasons, my login form is within a js file and i include this file in my main html file. To authenticate the login credentials, a custom /POST request needs to be called using javascript like below. This function below executes when the form submit button is pressed.

function submitForm() {
        var myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

        var urlencoded = new URLSearchParams();
        urlencoded.append("username", "<removed>");
        urlencoded.append("password", "<removed>");

        var requestOptions = {
            method: 'POST',
            headers: myHeaders,
            body: urlencoded,
            redirect: 'follow'
        };

        fetch("http://localhost:8080/userAuth", requestOptions)
            .then(response => response.text())
            .then(result => console.log(result))
            .catch(error => console.log('error', error));
}

Controller to handle successful login end point

@Controller
public class LoginSuccessController {

    @GetMapping("/login_success")
    public String success() {
        return "success";
    }
}

On the browser, I can infer that authentication is successful and there is something that happens related to my successful login endpoint. However, my browser remains at localhost:8080/login and does not redirect to the login_success endpoint. I am unable to figure out why so. Any help is much appreciated.

Browser network activity after submit button


Solution

  • because you use ajax. if you check networks tab I believe you will see response ans 301/302 with Location header.

    Edit: you have to either use plain html form or redirect manually from js side

    Edit 2:

    fetch("http://localhost:8080/userAuth", requestOptions)
                .then(response => response.text())
                .then(result => {
                    // do some stuff with response
                    location.href = '/my-success-page-after-login'; // <- here is redirect
                })
                .catch(error => console.log('error', error));
    
    

    Explanation: the problem is that browser doesn't follow redirect response for AJAX calls. Ajax call will just return you a response from server(redirect with 301/302 status code in your case) but this will NOT make browser to follow that redirect