spring security 指定了 failureForwardUrl 的请求接口 但是没有效果
- springboot版本:3.3.0
- spring security版本:3.3.0
代码如下:
spring security 配置类
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; /** * <p> * spring security 配置类. * </p > * * @author Heqq */ @Configuration public class SecurityConfiguration { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http .authorizeHttpRequests(auth -> { auth.requestMatchers("/error.html").permitAll() // error.html不需要被认证 .requestMatchers("/login.html").permitAll() // login.html不需要被认证 .anyRequest().authenticated(); // 所有请求都必须要被认证,必须登录之后被访问 }) .formLogin(c -> { c.loginProcessingUrl("/login") // 这个login不是随随便便写的,要跟login.html表单的action属性值一致,当发现是/login的时候,认为是登录,会执行UserDetailsServiceImpl的登录逻辑 .loginPage("/login.html")// 自定义登录页面,斜杠不能少!!! // .successForwardUrl("/main.html")// 登录成功后跳转的页面 .successForwardUrl("/to-main")// 登录成功后跳转页面 Post请求 .failureForwardUrl("/to-error"); // 登录失败后跳转页面 Post请求 }) .csrf(csrf -> csrf.disable()) // 关闭csrf防护 .build(); } }
controller接口
import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * <p> * 用户登录控制器. * </p > * * @author Heqq */ @Slf4j @Controller public class LoginController { /** * 登录成功后,跳转到主页. * * @return */ @RequestMapping("to-main") public String toMain() { log.info("登录成功"); return "redirect:main.html"; } /** * 登录失败跳转的页面. * * @return */ @RequestMapping("to-error") public String toError() { log.info("登录失败"); return "redirect:error.html"; } }
静态页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录失败</title> </head> <body> 操作失败,请重新登录 <a href="/login.html">跳转</a> </body> </html>
启动项目后,来到登录页面,输入错误的密码,始终跳转到login.html页面,期望结果是:输入错误密码来到错误页面。
原因:虽然在spring security配置类放行了静态资源,也指定了登录失败的跳转url,但是没有放行跳转到错误页面的url!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~