Spring Security : Redirecting to login page if the authentication failed

spring security disable redirect to login page
spring security custom login controller
spring security redirect if already logged in
spring security redirect to previous page after successful login
spring security not redirecting after login
spring security login error message
spring boot application redirect to login page
spring redirect to login if not authenticated

We are having two ways of logging in.

  • The user name and password are sent by another app in the request headers. IT is examined and if the user name and password are correct, it goes in. [A custom filter is written for this]
  • If the user name and password are not present in the request headers, the login screen is presented.
  • When the user name and password are present in the request header and if it's wrong, I am shown an HTTP Status 401 - Authentication Failed: Bad credentials page.

    How do I make it show the login page in case the authentication failed?

    Below is the code in the security.xml

        <http auto-config="true" use-expressions="true">
                 <access-denied-handler error-page="/login.jsp"/>
                <intercept-url pattern="/*Login*" access="hasRole('ROLE_ANONYMOUS')"/>
                <intercept-url pattern="/*" access="hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')"/>
                <custom-filter ref="requestHeaderFilter" before="FORM_LOGIN_FILTER"/>
                <form-login login-page="/login.jsp"/>

    Please let me know if you need more information.

    Edit: Adding the code for RequestHeader filter in my application

    public class RequestHeaderProcessingFilter extends AbstractAuthenticationProcessingFilter{
    private String usernameHeader = "j_username";
    private String passwordHeader = "j_password";
    protected RequestHeaderProcessingFilter() {
    //getters and setters
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String username = request.getHeader(usernameHeader);
        String password = request.getHeader(passwordHeader);
         SignedUsernamePasswordAuthenticationToken authRequest =
            new SignedUsernamePasswordAuthenticationToken(username, password);
          return this.getAuthenticationManager().authenticate(authRequest); 


    To show the login page in case the authentication failed you should have the same url in the <access-denied-handler error-page="/login.jsp"/> and the <intercept-url pattern="/*Login*" access="hasRole('ROLE_ANONYMOUS')"/>

    for example:

    <global-method-security secured-annotations="enabled" />
    <http auto-config="true" access-denied-page="/app/sesiones/procesarLogin"> 
        <logout logout-success-url="/app/sesiones/login" />
            login-page="/app/sesiones/login" default-target-url="/app/sesiones/procesarLogin" />
        <intercept-url pattern="/app/privados/*" access="ROLE_USER" />

    in that example, the user is also redirected to login page after he logs out. The /procesarLogin is a method that sent user lo login.jsp page.

    Spring Security Form Login, A short example of redirection after login in Spring Security. Read more → authentication-failure-url = "/login.html?error=true" />. < logout  I have a problem with Spring Security authentication failure handler redirect with parameter. so you are redirected to the login page spring security custom

    The default behavior on authentication failure is to display HTTP status 401. In case SimpleUrlAuthenticationFailureHandler is used to handle failures (as done by AbstractAuthenticationProcessingFilter, this behavior can be overridden by setting the defaultFailureUrl to /login.jsp.

    Alternately, a custom error handler can be defined with suitable action.

    Redirect to the Previous URL After Login with Spring Security , When authenticated via an SSO service, users will be redirected to the originally requested page, with the URL appended. We must ensure the  The login form is part of the navigation menu, there is no login page. I don't want Spring security to redirect to a login page automatically when it encounters a 403 or 401. – greyfox Jul 30 '15 at 4:23

    it's also possible to try this:

    public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) throws Exception {
            http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login").invalidateHttpSession(true).deleteCookies("JSESSIONID").permitAll();

    In the configure Method you can add your filterpipeline and other related stuff. it is also possible to configure role access to specific endpoints like you can see https://docs.spring.io/spring-security/site/docs/current/guides/html5/form-javaconfig.html

    Spring Security authentication without page reloads for better UX, We keep the form login semi-activated even if we do not use it directly. This makes Spring Security take care of the redirects. The custom request In case the authentication failed, we will inform the user about it via the dialog. It is always a  By default, Spring redirects the user back to the login page with a request parameter containing information about the error. In this application, we'll return a 401 response that contains information about the error, as well as the timestamp of its occurrence.

    Can't login to my custom login page in Spring Boot Security – Yawin , In the spring boot security application, when we try to login to the page. It redirects If incorrect user credentials are provided, redirect to the login page by default. The login Configuration; import org.springframework.security.config.​annotation.authentication.builders. Step 6 – Unauthorized Access Denied Error Page  Sometimes its required to redirect user to different pages post login based on the role of the user.For example if an user has an USER role then we want him to be redirected to /user and similarly to /admin for users having ADMIN role.In this post, we will be discussing about how to redirect user to different pages post login based on the role of the user.We will be implementing

    Creating a Custom Login Form, This guide builds off of Hello Spring MVC Security Java Config to when authentication attempt fails, redirect the browser to /login?error (since  Go to localhost:8080/welcome, we will be redirected to the custom login page. Enter the user javainuse and password javainuse, user is redirected to the add employee page. Enter the user employee and password employee, user is redirected to the welcome page. Download Source Code Download it - Spring Boot Security - Redirect using Authentication Handler

    Spring Security Reference, If authentication fails, then Failure when we redirect to the log in page. When the login page is specified in the Spring Security configuration, you are responsible for rendering the page. using HTTP Referer header. saving the original request in the session. appending original URL to the redirected login URL. Using the HTTP Referer header is a straightforward way, for most browsers and HTTP clients set Referer automatically. However, as Referer is forgeable and relies on client implementation, using HTTP Referer header to implement redirection is generally not suggested.