JAVA全系列 教程
3762个小节阅读:7088.6k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
引入Spring Security
相关依赖
xxxxxxxxxx
<!-- spring-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- thymeleaf整合spring-security -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
编写Spring Security
配置类
xxxxxxxxxx
// Security配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// Spring Security配置
@Override
protected void configure(HttpSecurity http) throws Exception {
// 自定义表单登录
http.formLogin()
.loginPage("/backstage/admin_login") // 自定义登录页面
.usernameParameter("username") // 用户名项
.passwordParameter("password") // 密码项
.loginProcessingUrl("/backstage/admin/login") // 登录提交路径,提交后执行认证逻辑
.successForwardUrl("/backstage/index") // 登录成功后跳转路径
.failureForwardUrl("/backstage/admin_fail"); // 登录失败后跳转路径
// 权限拦截配置
http.authorizeRequests()
.antMatchers("/backstage/admin/login").permitAll() // 登录不需要认证
.antMatchers("/backstage/admin_fail").permitAll() // 登录失败不需要认证
.antMatchers("/backstage/admin_login").permitAll() // 登录页不需要认证
.antMatchers("/**/*.css","/**/*.js").permitAll() //放行静态资源
.antMatchers("/backstage/**").authenticated();//其余都需要认证
// 退出登录配置
http.logout()
.logoutUrl("/backstage/admin/logout")
.logoutSuccessUrl("/backstage/admin_login")
.clearAuthentication(true)
.invalidateHttpSession(true);
// 异常处理
http.exceptionHandling()
.accessDeniedHandler(new MyAccessDeniedHandler()); // 权限不足处理器
// 关闭csrf防护
http.csrf().disable();
//开启跨域访问
http.cors();
}
// 密码编码器
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
编写权限不足处理器
xxxxxxxxxx
// 处理权限不足
public class MyAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.sendRedirect("/backstage/no_permission");
}
}