spring-security: Custom Form Login is causing too many redirects and cannot get the login page for Spring Security v6.1.0

I defined the SecurityFilterChain bean like below

@Bean
	public SecurityFilterChain securityFilterChain (HttpSecurity http) throws Exception {
		// We are disabling CSRF so that our forms don't complain about a CSRF token.
		// Beware that it can create a security vulnerability
		return http.csrf(AbstractHttpConfigurer::disable)
				// Here we are configuring our login form
//				.formLogin(Customizer.withDefaults())
				.formLogin(formLogin -> {
							formLogin
									.loginPage("/login") // Login page will be accessed through this endpoint. We will create a controller method for this.
									.loginProcessingUrl("/login-processing") // This endpoint will be mapped internally. This URL will be our Login form post action.
									.usernameParameter("username")
									.passwordParameter("password")
									.permitAll() // We re permitting all for login page
									.defaultSuccessUrl("/") // If the login is successful, user will be redirected to this URL.
									.failureUrl("/login?error=true"); // If the user fails to login, application will redirect the user to this endpoint
						}
				)
		.authorizeHttpRequests(authorize ->
						authorize
								// We are permitting all static resources to be accessed publicly
								.requestMatchers("/images/**", "/css/**", "/js/**").permitAll()
								// We are restricting endpoints for individual roles.
								// Only users with allowed roles will be able to access individual endpoints.
								.requestMatchers("/course/add").hasRole("ADMIN")
								.requestMatchers("/course/show-all").hasAnyRole("ADMIN", "USER")
								.requestMatchers("/course/edit").hasAnyRole("USER")
								// Following line denotes that all requests must be authenticated.
								// Hence, once a request comes to our application, we will check if the user is authenticated or not.
								.anyRequest().authenticated()
				)

				.logout(logout ->
						logout
								.logoutUrl("/logout")
								.logoutSuccessUrl("/")
				)
				.build();

	}

Unfortunately, this code does not work for custom form login, but works perfectly for form login with default configuration (which is also commented in the code),

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 20 (2 by maintainers)

Commits related to this issue

Most upvoted comments

Hello @marcusdacoregio , after enabling the TRACE log for Spring Security, I found the following line in the log. image

So I set the authorization of my view page location, “/WEB-INF/views/**” in my case to permitAll()


authorize
								// We are permitting all static resources to be accessed publicly
								.requestMatchers("/images/**", "/css/**", "/js/**", "/WEB-INF/views/**").permitAll()
								// We are restricting endpoints for individual roles.
								// Only users with allowed roles will be able to access individual endpoints.
								.requestMatchers("/course/add").hasRole("ADMIN")
								.requestMatchers("/course/show-all").hasAnyRole("ADMIN", "USER")
								.requestMatchers("/course/edit").hasAnyRole("USER")
								// Following line denotes that all requests must be authenticated.
								// Hence, once a request comes to our application, we will check if the user is authenticated or not.
								.anyRequest().authenticated()

And it worked like a charm!

Thank you for your kind support 😃

Hey Everyone!! I am stuck with TOO MANY REDIRECTS… Kindly help me with the code

SpringSecurity:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
	http
	.csrf().disable()
	.authorizeRequests().requestMatchers("/logins", "/register", "/webapp/views/**", "/css/**", "/js/**", "/images/**").permitAll()
	.anyRequest().authenticated()
	.and()
	.formLogin()
	.loginPage("/logins")
	.permitAll()
	.defaultSuccessUrl("/", true)
	.and()
	.logout().invalidateHttpSession(true)
	.clearAuthentication(true)
	.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
	.logoutSuccessUrl("/logout-success").permitAll();
	
	return http.build();
    
}

Controller:

@RequestMapping("/")
public String callHome()
{
	System.out.println("Calling Homepage...");
	return "Index";
}

@RequestMapping("/logins")
public String loginPage()
{
	return "demologin";
}

@RequestMapping("/logout-success")
public String logoutPage()
{
	return "logout";
}

demologin.jsp

<%@ page language=“java” contentType=“text/html; charset=UTF-8” pageEncoding=“UTF-8” isELIgnored=“false”%>

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body>

Login

${SPRING_SECURITY_LAST_EXCEPTION.message}
<form action="login" method="POST">
	<table>
		<tr>
			<td>User: </td>
			<td> <input type = "text" name = "username" value = ''> </td>
		</tr>
		
		<tr> 
			<td>Password: </td>
			<td> <input type = "password" name = "password"> </td>
		</tr>
		
		<tr>
			<td> <input name = "submit" type = "submit" value = "submit" /> </td>
		</tr>
	</table>
</form>
</body> </html>

Jsp path:

/springmvcbootdemo/src/main/webapp/views/demologin.jsp

It’s not working when we are using below code with mvc.pattern , which is required in latest version. Any suggestions what could be resolution? @Bean public SecurityFilterChain settingUpSecurityFilterChain() throws Exception {

	httpSecurity.authorizeHttpRequests(customizer->{
		customizer.requestMatchers(mvc.pattern("/hello"),mvc.pattern("/helloworld"))
		.authenticated();
		
		customizer.requestMatchers(mvc.pattern("/bye")).permitAll();
		customizer.requestMatchers(mvc.pattern("/WEB-INF/views/**")).permitAll();
	});
	
	httpSecurity.formLogin(formLoginCustomizer->{
		formLoginCustomizer.loginPage("/myCustomLogin");
	});

// httpSecurity.formLogin(Customizer.withDefaults()); httpSecurity.httpBasic(Customizer.withDefaults());

	return httpSecurity.build();
}

First of all, set /WEB-INF/views/** to permit all, like the code below in your spring security http configuration requestMatchers("/images/**", "/css/**", "/js/**", "/WEB-INF/views/**").permitAll()

Next, in your controller method, return should be only your view name. Replace return "redirect:/login.html"; to return "login";

If your view page is in the correct location, it should work.

The configuration httpSecurity.formLogin(formLoginCustomizer -> formLoginCustomizer.loginPage("/myCustomLogin")); instructs Spring Security to redirect unauthorized requests to /myCustomLogin. To understand why localhost is redirecting excessively, consider this: when an unauthorized request occurs, Spring Security redirects to the login page URL. If this URL requires authentication, it creates a redirect loop back to itself, resulting in the ‘localhost redirected too many times’ error. Solution: The solution is to set up HttpSecurity for form login like so: httpSecurity.formLogin(f -> f.loginPage("/loginpage").permitAll());. If the login page URL is not the URL for the actual page causing the redirection, you should allow “/page.html” without authentication in the request matchers. HttpSecurity.authorizeHttpRequests(customizer -> customizer.requestMatchers(“/page.html”).permitAll());

I’ve configured form login like that but still experiencing a redirect loop. .formLogin(form -> form.loginPage("/login").permitAll())

login is not the page,it returns the page,instead it should be login.jsp or login.html or you can allow it : http…authorizeHttpRequests((authorize) -> authorize .requestMatchers(“/login.extension”) .permitAll().anyRequest().authenticated())

doesn’t matter, /login is a controller that returns “login” or login.html

yes,you are allowing login end point without authentication,but not login.html ,you can also allow it without authentication by : http…authorizeHttpRequests((authorize) -> authorize .requestMatchers(“/login.html”) .permitAll().anyRequest().authenticated())