- 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 {@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Beanpublic 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!!!