You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security登录页404:Spring Boot受保护端点无法访问问题

Troubleshooting Spring Security Login Page 404 Issue

Hey there! Let's work through this 404 error you're hitting when trying to access secured endpoints after adding Spring Security to your Spring Boot app. I've dealt with this exact scenario before, so here's a step-by-step breakdown of what to check:

1. Verify Your Spring Security Dependency

First, make sure you're using the correct Spring Boot starter dependency in your build file (Maven or Gradle). Using the starter ensures all necessary auto-configurations are pulled in, including the default login page handler.

For Maven, your pom.xml should have:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

For Gradle:

implementation 'org.springframework.boot:spring-boot-starter-security'

If you're using individual Spring Security libraries instead of the starter, you might miss the auto-configured login endpoint.

2. Check Your Security Configuration

If you've created a custom SecurityConfig class, this is the most likely culprit. Here's what to look for:

Common Mistake 1: Missing formLogin() Configuration

Spring Security's auto-config provides a default /login endpoint, but if you override the security filter chain without including formLogin(), that endpoint won't exist.

Bad example (causes 404):

@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated());
        return http.build();
    }
}

Fix: Add Proper formLogin() Setup

Update your config to include formLogin() and allow unauthenticated access to the login page:

@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/sample").permitAll() // Let /sample be accessible without login
                .anyRequest().authenticated() // Secure all other endpoints
            )
            .formLogin(form -> form
                .permitAll() // Allow everyone to access the login page
            );
        return http.build();
    }

    // Optional: Add an in-memory user for testing
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails testUser = User.withDefaultPasswordEncoder()
            .username("demoUser")
            .password("demoPass")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(testUser);
    }
}

With this setup, accessing /sample2 will redirect you to Spring Security's default login page (no need to write your own controller for /login).

Common Mistake 2: Custom Login Page Without a Controller

If you specified a custom login page path like .loginPage("/custom-login") but didn't create a controller to handle that path, you'll get a 404. To fix this, add a controller that returns your login view:

@Controller
public class LoginController {
    @GetMapping("/custom-login")
    public String showLoginPage() {
        return "custom-login"; // Assumes you have a template (e.g., Thymeleaf) at templates/custom-login.html
    }
}

And update your security config to allow access to this path:

.formLogin(form -> form
    .loginPage("/custom-login")
    .permitAll()
)

3. Enable Debug Logs for Deep Diving

If the above steps don't fix the issue, turn on Spring Security debug logs to see exactly what's happening with requests. Add this line to your application.properties:

logging.level.org.springframework.security=DEBUG

When you start your app and try to access /sample2, check the logs for:

  • Redirects to the login page (should see a 302 to /login)
  • Whether the /login request is being handled by Spring Security's filters or not
  • Any errors related to endpoint mapping

4. Check for Conflicting Endpoint Mappings

Make sure you don't have another controller or handler mapping to /login (or your custom login path). If you do, it might override Spring Security's default endpoint, leading to a 404 if your controller doesn't return a valid view.


内容的提问来源于stack exchange,提问作者Fernando Castilla Ospina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:59:01