一、Shiro
Shiro是一个强大而灵活的开源安全框架,,执行身份验证、授权、密码和会话管理。使用Shiro易于理解的API,可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。(和Spring Security,Shiro在保持强大功能的同时,还在简单性和灵活性方面拥有巨大优势)
三个核心组件:Subject, SecurityManager 和 Realms
Subject:是“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。
SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。
Realm: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。
从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。当配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。配置多个Realm是可以的,但是至少需要一个。
Shiro内置了可以连接大量安全数据源(又名目录)的Realm,如LDAP、关系数据库(JDBC)、类似INI的文本配置资源以及属性文件等。如果系统默认的Realm不能满足需求,你还可以插入代表自定义数据源的自己的Realm实现。
实现代码:
坐标:
<!--shiro和spring整合-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--shiro核心包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
创建realm
@Configuration
public class ShiroConfiguration {
//1.创建realm
@Bean
public CustomRealm getRealm() {
return new CustomRealm();
}
//2.创建安全管理器
@Bean
public SecurityManager getSecurityManager(CustomRealm realm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm);
return securityManager;
}
//3.配置shiro的过滤器工厂再web程序中,shiro进行权限控制全部是通过一组过滤器集合进行控制
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
//1.创建过滤器工厂
ShiroFilterFactoryBean filterFactory = new ShiroFilterFactoryBean();
//2.设置安全管理器
filterFactory.setSecurityManager(securityManager);
//3.通用配置(跳转登录页面,为授权跳转的页面)
filterFactory.setLoginUrl("/autherror");//跳转url地址
//4.设置过滤器集合
//key = 拦截的url地址
//value = 过滤器类型
Map<String,String> filterMap = new LinkedHashMap<>();
filterMap.put("/login","anon");//当前请求地址可以匿名访问
filterMap.put("/user/**","authc");//当前请求地址必须认证之后可以访问
//在过滤器工程内设置过滤器
filterFactory.setFilterChainDefinitionMap(filterMap);
return filterFactory;
}
//开启对shior注解的支持
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
//启对shior注解的支持2
@Bean
@ConditionalOnMissingBean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator app=new DefaultAdvisorAutoProxyCreator();
app.setProxyTargetClass(true);
return app;
}
}
认证和授权方法
public class CustomRealm extends AuthorizingRealm {
public void setName(String name) {
super.setName("customRealm");
}
@Autowired
private UserService userService;
/**
* 授权方法
* 操作的时候,判断用户是否具有响应的权限
* 一定先认证再授权
* 先认证 -- 安全数据
* 再授权 -- 根据安全数据获取用户具有的所有操作权限
*/
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//1.获取已认证的用户数据
User user = (User) principalCollection.getPrimaryPrincipal();//得到唯一的安全数据
//2.根据用户数据获取用户的权限信息(所有角色,所有权限)
Set<String> roles = new HashSet<>();//所有角色
Set<String> perms = new HashSet<>();//所有权限
for (Role role : user.getRoles()) {
roles.add(role.getName());
for (Permission perm : role.getPermissions()) {
perms.add(perm.getCode());
}
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setStringPermissions(perms);
info.setRoles(roles);
return info;
}
/**
* 认证方法
* 参数:传递的用户名密码
*/
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//1.获取登录的用户名密码(token)
UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
String username = upToken.getUsername();//用户录入的账号
//2.根据用户名查询数据库
//mybatis情景下:user对象中包含ID,name,pwd(匿名)
//JPA情景下:user对象中包含ID,name,pwd(匿名),set<角色>,set<权限>
User user = userService.findByName(username);
//3.判断用户是否存在或者密码是否一致
if(user != null) {
//4.如果一致返回安全数据
//构造方法:安全数据,密码(匿名),混淆字符串(salt),realm域名
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
return info;
}
//5.不一致,返回null(抛出异常)
return null;
}
/**
* 自定义密码比较器
*/
@PostConstruct
public void initCredentialsMatcher() {
//指定密码算法
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(DigestsUtil.SHA1);
//指定迭代次数
hashedCredentialsMatcher.setHashIterations(DigestsUtil.COUNTS);
//生效密码比较器
setCredentialsMatcher(hashedCredentialsMatcher);
}
}
密码加密
public class DigestsUtil {
//加密方式
public static final String SHA1 = "SHA-1";
//循环次数
public static final Integer COUNTS =520;
public static String sha1(String input, String salt) {
return new SimpleHash(SHA1, input, salt,COUNTS).toString();
}
// 随机获得salt字符串
public static String generateSalt(){
SecureRandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
return randomNumberGenerator.nextBytes().toHex();
}
//生成密码字符密文和salt密文
public static Map<String,String> entryptPassword(String passwordPlain) {
Map<String,String> map = new HashMap<>();
String salt = generateSalt();
String password =sha1(passwordPlain,salt);
map.put("salt", salt);
map.put("password", password);
return map;
}
}
二、Spring Security
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。(除了不能脱离Spring,shiro的功能它都有。而且Spring Security对Oauth、OpenID也有支持,Shiro则需要自己手动实现。Spring Security的权限细粒度更高)
实现代码:坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
@Configuration //就相当于springmvc.xml文件
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//访问登陆页面,安全框架所提供的
registry.addViewController("/loginPage").setViewName("login");
}
}
安全拦截机制(重点)
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 定义用户信息服务(查询用户信息)
* 方式1:通过内存定义
* 方式2:查询数据库
*/
@Bean //密码编码器
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
//安全拦截机制(最重要)
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable() //关闭csrf防火墙,避免csrf现象
.authorizeRequests() //所有请求
.antMatchers("/r/r1").hasAuthority("p1")
//访问/r/r1资源的 url需要拥有p1权限。
.antMatchers("/r/r2").hasAuthority("p2")
//访问/r/r2资源的 url需要拥有p2权限
.antMatchers("/r/**").authenticated()
//所有/r/**的请求必须认证通过
.anyRequest().permitAll()
//除了/r/**,其它的请求可以访问
.and()
.formLogin()
.loginPage("/loginPage") //允许表单登录
.loginProcessingUrl("/doLogin") //登录的提交接口
.successForwardUrl("/login-success"); //自定义登录成功的页面地址
}
}
启动类注解
@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
@ServletComponentScan
public class SecuritySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SecuritySpringBootApp.class,args);
}
授权注解
@GetMapping(value = "/r/r1")
@PreAuthorize("hasAuthority('user-find')")//拥有p1权限才可以访问
public String r1(){
return " 访问资源1";
}
总结:
相同点:
1.其核心都是一组过滤器链。
2.认证功能
3.授权功能
4.加密功能
5.会话管理
6.缓存支持
7.rememberMe功能
区别:
1.Spring Security是一个重量级的安全管理框架;Shiro则是一个轻量级的安全管理框架
2.Spring Security 基于Spring开发,项目若使用Spring作为基础,配合Spring Security 做权限更便捷,而Shiro需要和Spring 进行整合开发;
3.Spring Security 功能比Shiro更加丰富些,例如安全维护方面;
4.Spring Security 社区资源相对于Shiro更加丰富;
5.Shiro 的配置和使用比较简单,Spring Security 上手复杂些;
6.Shiro 依赖性低,不需要任何框架和容器,可以独立运行, Spring Security依赖Spring容器;
7.Shiro 不仅仅可以使用在web中,它可以工作在任何应用环境中。在集群会话时Shiro最重要的一个好处或许就是它的会话是独立于容器的;
Shiro有很多地方都比Spring Security方便简单直接,比起Spring Security的庞大模式更容易理解和切入一些,而Spring Security比Shiro功能上要多一点,再就是和spring框架的无缝对接,比如支持spel等,有时候比Shiro更方便灵活。