概要
Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。
Web 应用的安全性包括用户认证(Authentication)和用户授权 (Authorization)两个部分,这两点也是 Spring Security 重要核心功能。
- 用户认证:系统判断用户是否能登陆
- 用户授权:系统判断用户是否具有权限去做某些事情
SpringSecurity 本质是一个过滤器链UsernamePasswordAuthenticationFilter
:对/login 的 POST 请求做拦截,校验表单中用户 名,密码。
Springsecurity和Shiro
SpringSecurity 特点:
- 和 Spring 无缝整合。
- 全面的权限控制。
- 专门为 Web 开发而设计。
- 旧版本不能脱离 Web 环境使用。
- 新版本对整个框架进行了分层抽取,分成了核心模块和 Web 模块。单独引入核心模块就可以脱离 Web 环境。
- 重量级
Shiro特点:
特点:
- 轻量级。Shiro 主张的理念是把复杂的事情变简单。针对对性能有更高要求的互联网应用有更好表现。
- 通用性。
- 好处:不局限于 Web 环境,可以脱离 Web 环境使用。
- 缺陷:在 Web 环境下一些特定的需求需要手动编写代码定制。
权限管理中相关概念:
principle:主体
使用系统的用户或设备或从其他系统远程登录的用户等等。简单说就是谁使用系统谁就是主体。
authentication:认证
权限管理系统确认一个主体的身份,允许主体进入系统。简单说就是“主体”证明自己是谁。
笼统的认为就是以前所做的登录操作
authorization:授权
将操作系统的“权力”“授予”“主体”,这样主体就具备了操作系统中特定功能的能力。
所以简单来说,授权就是给用户分配权限PasswordEncoder 接口讲解
```java // encode :表示把参数按照特定的解析规则进行解析 String encode(CharSequence rawPassword);
// matches :表示验证从存储中获取的编码密码与编码后提交的原始密码是否匹配。如果密码匹 配,则返回 true;如果不匹配,则返回 false。第一个参数表示需要被解析的密码。第二个 参数表示存储的密码。 boolean matches(CharSequence rawPassword, String encodedPassword);
// 表示如果解析的密码能够再次进行解析且达到更安全的结果则返回 true,否则返回 false。默认返回 false。 default boolean upgradeEncoding(String encodedPassword) { return false; }
`BCryptPasswordEncoder `是 Spring Security 官方推荐的**密码解析器**,平时多使用这个解析器。 <br />BCryptPasswordEncoder 是对 bcrypt 强散列方法的具体实现。是基于 Hash 算法实现的单向加密。可以通过 strength 控制加密强度,默认 10.<br />**方法演示:**
```java
@Test
public void test01(){
// 创建密码解析器
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//.encode: 对密码进行加密
String atguigu = bCryptPasswordEncoder.encode("atguigu");
// 打印加密之后的数据
System.out.println("加密之后数据:\t"+atguigu);
//.matches:判断原字符加密后和加密之前是否匹配
boolean result = bCryptPasswordEncoder.matches("atguigu", atguigu);
// 打印比较结果
System.out.println("比较结果:\t"+result);
}
编写配置类放行登录页面及静态资源
protected void configure(HttpSecurity http) throws Exception {
// 配置认证
http.formLogin()
.loginPage("/index") // 配置哪个 url 为登录页面
.loginProcessingUrl("/login") // 设置哪个是登录的 url。
.successForwardUrl("/success") // 登录成功之后跳转到哪个 url
.failureForwardUrl("/fail");// 登录失败之后跳转到哪个 url
http.authorizeRequests()
.antMatchers("/layui/**","/index") //表示配置请求路径
.permitAll() // 指定 URL 无需保护。
.anyRequest() // 其他请求
.authenticated(); //需要认证
// 关闭 csrf
http.csrf().disable();
http.exceptionHandling().accessDeniedPage("/unauth");//修改访问配置类
}
注解
@Secured
判断是否具有角色,另外需要注意的是这里匹配的字符串需要添加前缀“ROLE“。
使用注解先要开启注解功能!
**@EnableGlobalMethodSecurity(securedEnabled=true)_
@PreAuthorize
先开启注解功能:
@EnableGlobalMethodSecurity(prePostEnabled = true)
@PreAuthorize:注解适合进入方法前的权限验证,
@PreAuthorize 可以将登录用
户的 roles/permissions 参数传到方法中
@PostAuthorize
先开启注解功能:
@EnableGlobalMethodSecurity(prePostEnabled = true**)
@PostAuthorize 注解使用并不多,在方法执行后再进行权限验证,适合验证带有返回值
的权限.