一、概述
目前流行的安全框架有Shiro和Spring Security
Shiro较简单易用
Spring Security较复杂 但功能强大
Spring Security能无缝整合SpringBoot 因此SpringBoot底层使用的是SpringSecurity
Spring Security是针对Spring项目的安全框架 其可以实现强大的web安全控制
对于安全控制 仅需引入spring-boot-starter-security模块 然后进行少量的配置 即可实现强大的安全管理
认证和授权:
应用程序的两个主要区域是“认证”和“授权”(即访问控制)
这两个主要区域是Spring Security的两个控制目标
- “认证”(Authentication)是建立一个声明的主体的过程
一个主体一般是指用户 设备或一些可在应用程序中执行动作的其他系统 - “授权”(Authorization)指确定一个主体是否允许在应用程序中执行某个动作的过程
二、使用
引入Spring Security模块的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
然后 编写配置类:
该配置类必须继承WebSecurityConfigurerAdapter
类
然后给配置类上添加@EnableWebSecurity
注解
@EnableWebSecurity注解已经自带了@Configuration注解 因此无须添加@Configuration注解了
1、访问权限控制及开启默认登录页
重写configure(HttpSecurity http)方法 定制请求的授权规则
使用antMatchers()
方法添加路径 使用permitAll()
方法允许所有用户访问 使用hasRole()
方法指定可访问的角色
根据不同等级的页面设置不同的访问权限
@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");
// 开启自动配置的登录功能 若没有权限则会自动来到登录页面
http.formLogin();
// 通过/login请求来到登录页 若登录失败会重定向到/login?error
}
}
默认的自动生成的登录页:
2、定义认证规则
使用inMemoryAuthentication()
方法来配置内存中的用户
当然 还可从数据库中查询用户 此处为演示方便 只演示保存在内存中的用户
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
// 定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// inMemoryAuthentication() 内存中的用户
// 通过passwordEncoder()指定加密方式 通过withUser()方法来定义用户名 通过password()方法来定义密码 通过roles()方法来定义角色
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2")
.and()
.passwordEncoder(new B