一、简介
Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
1.WebSecurityConfigurerAdapter: 自定义Security策略
2.AuthenticationManagerBuilder: 自定义认证策略
3.@EnableWebSecurity: 开启WebSecurity模式
Spring Security的两个主要目标是“认证”和“授权”(访问控制)。
“认证”(Authentication)
"授权”(Authorization)
这个概念是通用的,而不是只在Spring Security中存在。
二、配置Spring Security
1.导入依赖(这里导入了SpringSecurity和Thymeleaf)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
2.编写对应的配置
@EnableWebSecurity//开启Security服务
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");
//没有权限默认跳转到登陆页面,需要开启登陆页面 loginProcessingUrl是指前端请求地址 loginPage是指实际请求地址
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
//开启注销功能
http.logout().logoutSuccessUrl("/");
//将信息存在cookie中
http.rememberMe().rememberMeParameter("remember-me");
// super.configure(http);
}
//认证
//密码编码
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("mi").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
// super.configure(auth);
}
}
具体见文件