Angular 4与Spring Boot登录后跳转404问题求助
看起来你在Spring Security的登录跳转逻辑上踩坑了,我帮你分析下可能的问题和解决办法:
问题拆解
你的自动跳转到/login是正常的,说明未认证请求的拦截逻辑没问题,但登录成功后没跳去目标Dashboard反而回到根路径,还出现404,大概率是自定义AuthenticationSuccessHandler的重定向逻辑出错,或者Dashboard的端点配置/资源映射没做好。
针对性解决方案
1. 修复自定义SuccessHandler的重定向代码
你实现的SimpleAuthenticationSuccessHandler核心问题应该出在onAuthenticationSuccess方法里,要么没明确指定重定向路径,要么路径写错了。给你一个标准的正确实现参考:
@Component public class SimpleAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // 直接重定向到Dashboard路径,相对当前域名的写法更稳妥 response.sendRedirect("/dashboard"); } }
注意:如果你的Dashboard实际路径是http://localhost:8080/dashboard,写/dashboard就足够,不需要写完整域名。
2. 确保Dashboard端点存在且可访问
404错误说明/dashboard这个路径没有对应的处理逻辑,你需要检查:
- 有没有编写对应的控制器:
@Controller public class DashboardController { @GetMapping("/dashboard") public String showDashboard() { // 对应templates目录下的dashboard.html(如果用Thymeleaf等视图框架) return "dashboard"; } }
- 如果是静态页面,要确保
dashboard.html放在src/main/resources/static或src/main/resources/templates目录下(取决于你的视图解析器配置)。 - 还要在Spring Security配置里允许已认证用户访问该路径:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/login", "/css/**", "/js/**").permitAll() .requestMatchers("/dashboard").authenticated() // 放开Dashboard的访问权限 .anyRequest().authenticated() ) // 其他配置... return http.build(); }
3. 确认自定义SuccessHandler被正确引用
如果Spring Security配置里没明确指定用你的自定义处理器,会默认跳转到之前请求的路径(没有的话就跳根路径)。所以一定要在配置里绑定它:
@Autowired private SimpleAuthenticationSuccessHandler successHandler; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .formLogin(form -> form .loginPage("/login") .successHandler(successHandler) // 指定使用你的自定义成功处理器 .permitAll() ) // 其他配置... return http.build(); }
4. 排查路径拼写错误
别忽略这个低级但常见的问题:比如把/dashboard写成/dashbord,或者大小写不匹配(比如/Dashboard),一定要确保路径完全一致。
内容的提问来源于stack exchange,提问作者SK.
相关产品推荐
相关产品推荐

