SpringSecurity(安全)
SpringSecurity是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术,它可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量配置,即可实现强大的安全管理。
安全框架有Shiro, SpringSecurity
Shiro, SpringSecurity: 相似,除了类名不一样,名字不一样
作用:
-
过滤器
-
拦截器
-
认证(Authentication)
-
授权(Authorization)
- 功能权限
- 访问权限
- 菜单权限
常用类:
- WebSecurityConfigurerAdapter: 自定义Security策略
- AuthenticationManagerBuilder: 自定义认证也能够策略
- @EnableWebSecurity: 开始WebSecurity模式
参考官网: https://spring.io/projects/spring-security
https://docs.spring.io/spring-security/site/docs/5.3.5.RELEASE/reference/html5
https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/htmlsingle/#using-boot
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
//请求授权的规则~
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限默认会到登录页面
http.formLogin();
// http.formLogin().loginPage("/login"); //指定自己的login地址
//注销
http.logout();
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// super.configure(auth);
String encodePassword = new BCryptPasswordEncoder().encode("123456");
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("root").password(encodePassword).roles("vip1", "vip2", "vip3")
.and()
.withUser("guest").password(encodePassword).roles("vip1")
.and();
}
}