Spring Security-从入门到精通-登录失败页面跳转+自定义登录参数
1 SecurityConfig配置类
package com.mangoubiubiu.security.config; 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.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; /** * SecurityConfig 配置类 */ @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //表单登录 http.formLogin() .loginProcessingUrl("/login") .loginPage("/login.html") .successForwardUrl("/main") .failureForwardUrl("/toError") //自定义登录用户名参数 .usernameParameter("user") .passwordParameter("pwd"); //所有请求都必须被认证(登录) http.authorizeRequests() //放行登录页面 .antMatchers("/login.html","/error.html").permitAll() //所有请求都必须被认证(登录) .anyRequest().authenticated(); //关闭 csrf 跨站请求伪造 http.csrf().disable(); } @Bean public PasswordEncoder pw(){ return new BCryptPasswordEncoder(); } }
2 error.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录失败</title> </head> <body> <h1 style="color: red">登录失败</h1> </body> </html>
3 LoginController
package com.mangoubiubiu.security.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginController { @RequestMapping("/main") public String tomain(){ return "redirect:main.html"; } @RequestMapping("/toError") public String error(){ return "redirect:error.html"; } }
本文作者:KwFruit
本文链接:https://www.cnblogs.com/mangoubiubiu/p/16211816.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
Spring Security
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步