1、简介
常见的两个安全框架shiro|spring security,这里只介绍spring security;
Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型。他可以实现强大的web安全控制。对于安全控制,我们仅需引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理。
几个类:
WebSecurityConfigurerAdapter:自定义Security策略
AuthenticationManagerBuilder:自定义认证策略
@EnableWebSecurity:开启WebSecurity模式
应用程序的两个主要区域是“认证”和“授权”(或者访问控制)。这两个主要区域是Spring Security 的两个目标。
“认证”(Authentication),是建立一个他声明的主体的过程(一个“主体”一般是指用户,设备或一些可以在你的应用程序中执行动作的其他系统)
“授权”(Authorization)指确定一个主体是否允许在你的应用程序执行一个动作的过程。为了抵达需要授权的店,主体的身份已经有认证过程建立。
2、测试安全登录&认证&授权
1、导入依赖
测试环境说明:
springboot:2.2.0、thyemelaf:3.0.11.RELEASE、
<!--引入spring security模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--thyemelaf模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、配置spring security配置类
该类要用@EnableWebSecurity标注并且继承WebSecurityConfigurerAdapter
public class MySecurityConfig extends WebSecurityConfigurerAdapter{
}
3、控制请求的访问权限
重写protected void configure(HttpSecurity http)方法
定制请求的授权规则:
//开启自动配置的登录功能,如果没有登录,没有权限就会来到登录页面
/*formLogin()
* 1、/login 来到登录页面
* 2、重定向到/login?error表示登录失败
* 3、更多详细规定
* 4、默认post形式的/login代表处理登录
* 5、一旦定制loginpage:那么loginPage的post请求就是登录
* */
http.formLogin()
详细代码:
@EnableWebSecurity
public class MySecurityConfig 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");
//开启自动配置的登录功能,如果没有登录,没有权限就会来到登录页面
/*formLogin()
* 1、/login 来到登录页面
* 2、重定向到/login?error表示登录失败
* 3、更多详细规定
* 4、默认post形式的/login代表处理登录
* 5、一旦定制loginpage:那么loginPage的post请求就是登录
* */
http.formLogin()
.usernameParameter("user")
.passwordParameter("pwd ")
.loginPage("/userlogin");
}
4、定制授权规则
重写:protected void configure(AuthenticationManagerBuilder auth)
这里主要从auth.inMemoryAuthentication 从内存中获取