1. SpringSecurity 特点:
- 和 Spring 无缝整合。
- 全面的权限控制。
- 专门为 Web 开发而设计。
- 旧版本不能脱离 Web 环境使用。
- 新版本对整个框架进行了分层抽取,分成了核心模块和 Web 模块。单独引入核心模块就可以脱离 Web 环境。
- 重量级
1.1Shiro特点
- 轻量级。Shiro 主张的理念是把复杂的事情变简单。针对对性能有更高要求的互联网应用有更好表现。
- 通用性。
- 好处:不局限于 Web 环境,可以脱离 Web 环境使用。
- 缺陷:在 Web 环境下一些特定的需求需要手动编写代码定制
1.2 重点看三个过滤器
FilterSecurityInterceptor:是一个方法级的权限过滤器, 基本位于过滤链的最底部
ExceptionTranslationFilter:是个异常过滤器,用来处理在认证授权过程中抛出的异常
UsernamePasswordAuthenticationFilter :对/login 的 POST 请求做拦截,校验表单中用户
名,密码
2.常见的接口讲解
正常来说需要我们自己配置SpringSecurity,但SpringBoot已经自动为我们配置好了,那么过滤器是如何进行加载的呢?
2.1UserDetailsService 接口
当什么也没有配置的时候,账号和密码是由 Spring Security 定义生成的。而在实际项目中
账号和密码都是从数据库中查询出来的。 所以我们要通过自定义逻辑控制认证逻辑。
①创建类继承UsernamePasswordAuthenticationFilter,重写三个方法
②创建类实现UserDetailService,编写查询数据过程,返回User对象,这个对象就是我们安全框架中提供的对象
2.2 PasswordEncoder 接口
数据加密接口,用于对User 对象中的密码进行加密
3.SpringSecurity Web 权限方案
3.1 设置登录系统的账号、密码
方式一:在 application.properties
spring.security.user.name=ty
spring.security.user.password=tyty123
方式二:编写类实现接口
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
PasswordEncoder passwordEncoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
String encode = passwordEncoder.encode("123456");
auth.inMemoryAuthentication().withUser("ty").password(encode).roles("admin");
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
方式三:用自定义类进行配置
①创建配置类,设置使用哪个userDetailService实现类
②编写实现类,返回User对象,User对象有用户名和密码操作权限
package com.ty.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Autowired
PasswordEncoder passwordEncoder;
@Override
protected void configure