1.SpringSecurity介绍:Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理。
2.SpringSecurity中有几个重要的类:
(1)WebsecurityConfigurerAdapter:自定义Security策略;
(2)AuthenticationManagerBuilder:自定义认证策略
(3)@EnableWebSecurity:开启WebSecurity模式,@Enablexxxx开启某个功能
3.Spring Security的两个主要目标是“认证"和“授权”(访问控制)。“认证”(Authentication),“授权”(Authorization),这个概念是通用的,而不是只在Spring Security中存在。
4.在springboot中,配置security,使用thymeleaf模板引擎,首先导入依赖
<!-- security-thymeleaf整合 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 使用thymeleaf模板引擎基于3.x开发,需要导入的依赖-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
5.编写相应的security配置类,进行相应的需求编写
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
// 首页所有人都可以访问,功能页对应相应权限的人才可以访问
// 请求授权的规则
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
// 没有相应的权限会回到登录页面,需要开启登陆的页面
// 自定义登录页
http.formLogin().loginPage("/toLogin");
// 防止网站攻击
http.csrf().disable(); // 关闭csrf功能
// 注销,开启注销功能,跳回首页
http.logout().logoutSuccessUrl("/");
// 开启记住我功能
http.rememberMe().rememberMeParameter("remember"); // cookie,默认保存两周
}
// 认证 springboot2.1.x可以直接使用
// 密码编码:PasswordEncoder
// Spring Security5.0+新增了很多加密方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kobe").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
6.对前端进行相应的编写,注意:前端使用security时,必须要加上命名空间:xmlns:sec="http://www.thymeleaf.org/extras/spring-security"