参考文章:

https://www.cnblogs.com/maofa/p/6407102.html

https://www.cnblogs.com/learnhow/p/9747134.html

https://www.cnblogs.com/learnhow/p/5694876.html

https://www.sojson.com/shiro

Shiro 简介

Spring MVC 整合Shiro, Shiro是一个强大的安全框架,提供 认证、授权、加密、会话管理等

Authentication(认证、鉴定):身份认证、登陆,验证用户是否拥有响应的身份

Authorization(授权、批准):授权,即权限验证,验证某个认证的用户是否拥有某个权限,某个用户是否拥有操作某个动作的权限,访问某个资源的权限

Session Manager: 会话管理,用户登陆后就是一次会话,在退出之前,所有的信息都保存在会话中。

Cryptography(密码学):加密,保护数据的安全性,如密码加密后存储

Web Support: Web支持,可以非常容易的集成到Web环境中

Caching: 缓存,将用户的信息存储到缓存,不必每次都去数据库查

Concurrency: shiro 支持多线程应用程序的并发验证,在一个线程中开启另一个线程,可以把权限传播过去

Testing : 支持测试

Run As :允许不同的用户身份进行访问

Remember Me :记住我,第一次登陆后,下次直接进入到系统中

注:Shiro 不会维护用户、权限信息,这些需要程序员设计好后通过接口注入给 Shiro

从宏观的角度观察 Shiro 工作原理

图中,应用代码直接通过Subject 交互,也即是说 Shiro 对外API核心就是 Subject,Api含义:

Subject: 主体,代表了当前 用户,也是当前交互的应用都称为 Subject.所有的Subject 绑定到SecurityManager,与Subject 交互的东西委托SecurityManager,Subject 是表面,真正执行的是SecurityManager

SecurityManager:安全管理器,所有的与安全有关的操作都会与SecurityManager 交互,其也是Shiro 的核心,类似于Spring MVC 的 前端控制器(DispatcherServlet)。

Realm: 域,Shiro 从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager 要验证用户身份,需要从Realm 获取相应的用户比较确认用户是否合法;Realm 类似于Shiro 的数据源

从内部角度观察Shiro

Subject:主体,可以看到主体可以是任何可以与应用交互的“用户”;

SecurityManager:相当于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心脏;所有具体的交互都通过SecurityManager进行控制;
        它管理着所有Subject、且负责进行认证和授权、及会话、缓存的管理。 Authenticator:认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了; Authrizer:授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能; Realm:可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC实现,也可以是LDAP实现,或者内存实现等等;由用户提供;
      注意:Shiro不知道你的用户/权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm; SessionManager:如果写过Servlet就应该知道Session的概念,Session呢需要有人去管理它的生命周期,这个组件就是SessionManager;而Shiro并不仅仅可以用在Web环境,
        也可以用在如普通的JavaSE环境、EJB等环境;所有呢,Shiro就抽象了一个自己的Session来管理主体与应用之间交互的数据;这样的话,比如我们在Web环境用,
        刚开始是一台Web服务器;接着又上了台EJB服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到Memcached服务器); SessionDAO:DAO大家都用过,数据访问对象,用于会话的CRUD,比如我们想把Session保存到数据库,那么可以实现自己的SessionDAO,通过如JDBC写到数据库;
        比如想把Session放到Memcached中,可以实现自己的Memcached SessionDAO;另外SessionDAO中可以使用Cache进行缓存,以提高性能; CacheManager:缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能 Cryptography:密码模块,Shiro提高了一些常见的加密组件用于如密码加密/解密的

自定义Realm

public class ShiroRealn extends AuthorizingRealm{
}

1.ShiroRealm 父类 AuthorizingRealm 将获取Subject相关信息分成两步,获取身份验证信息(doGetAuthenticationInfo)以及授权信息(doGetAuthorizationInfo)

2.doGetAuthenticationInfo 获取身份验证相关的信息:

首先根据传入的用户名获取User信息,如果user为空,抛出 UnknownAccountException; 如果用户被锁定,抛出LockedAccountException;
最后生成AuthenticationInfo信息,交给父类AuthenticatingRealm 使用 CredentialsMatcher 进行判断密码是否正确。如果不正确,抛出 IncorrectCredentialsException;
在组装SimpleAuthenticationInfo 信息时,需要传入:身份信息(用户名)、凭据(密文密码)、盐(username+salt)、CredentialsMatcher使用盐加密传入的明文和此处的密文进行匹配

3.doGetAuthorizationInfo 获取授权信息: PrincipalCollection 是一个身份集合,直接调用getPrimaryPrincipal 得到之前传入的用户名,然后根据用户名调用 UserService 接口获取角色及授权信息。

AuthenticationTaken

AuthenticationToken 用于收集用户提交的身份及凭据

public interface AuthenticationToken extends Serializable {
Object getPrincipal(); //身份
Object getCredentials(); //凭据
}

Shiro 提供了一个直接拿来用的UsernamePasswordToken,用于实现用户名/密码Token组,另外还有

RememberMeAuthenticationToken 和 HostAuthenticationToken,记住我与主机验证的支持

AuthenticationInfo

AuthenticationInfo有两个作用:

、如果Realm是AuthenticatingRealm子类,则提供给AuthenticatingRealm内部使用的CredentialsMatcher进行凭据验证;(如果没有继承它需要在自己的Realm中自己实现验证);

、提供给SecurityManager来创建Subject(提供身份信息);

PrincipalCollection

可以在Shiro 配置多个 Realm

public interface PrincipalCollection extends Iterable, Serializable {
Object getPrimaryPrincipal(); //得到主要的身份
<T> T oneByType(Class<T> type); //根据身份类型获取第一个
<T> Collection<T> byType(Class<T> type); //根据身份类型获取一组
List asList(); //转换为List
Set asSet(); //转换为Set
Collection fromRealm(String realmName); //根据Realm名字获取
Set<String> getRealmNames(); //获取所有身份验证通过的Realm名字
boolean isEmpty(); //判断是否为空
}

因为PrincipalCollection聚合了多个,此处最需要注意的是getPrimaryPrincipal,如果只有一个Principal那么直接返回即可,如果有多个Principal,

则返回第一个(因为内部使用Map存储,所以可以认为是返回任意一个);

oneByType / byType根据凭据的类型返回相应的Principal;fromRealm根据Realm名字(每个Principal都与一个Realm关联)获取相应的Principal。

目前Shiro只提供了一个实现SimplePrincipalCollection,还记得之前的AuthenticationStrategy实现嘛,用于在多Realm时判断是否满足条件的,

在大多数实现中(继承了AbstractAuthenticationStrategy)afterAttempt方法会进行AuthenticationInfo(实现了MergableAuthenticationInfo)的merge,

比如SimpleAuthenticationInfo会合并多个Principal为一个PrincipalCollection。

AuthorizationInfo

AuthorizationInfo用于聚合授权信息的:

public interface AuthorizationInfo extends Serializable {
Collection<String> getRoles(); //获取角色字符串信息
Collection<String> getStringPermissions(); //获取权限字符串信息
Collection<Permission> getObjectPermissions(); //获取Permission对象信息
}

我的Shiro 实战

application.yml

server:
context-path: /web
port: spring:
datasource:
druid:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring?useSSL=false&characterEncoding=UTF-8
username: root
password:
initial-size: min-idle:
max-active:
max-wait:
time-between-eviction-runs-millis:
min-evictable-idle-time-millis:
validation-query: select '' from dual
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-open-prepared-statements:
max-pool-prepared-statement-per-connection-size:
filters: stat
aop-patterns: com.apusic.servie.* web-stat-filter:
enabled: true
url-pattern: /*
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*' stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: false
login-username: druid
login-password: druid123 filter:
stat:
log-slow-sql: true thymeleaf:
cache: false mybatis:
type-aliases-package: com.apusic.pojo
mapper-locations: classpath:mapper/*.xml
propperty:
order: BEFORE

Shiro 配置文件

@Configuration
public class ShiroConfig { @Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/403"); LinkedHashMap<String,String> filterChainDefinitionMap = new LinkedHashMap<>(); filterChainDefinitionMap.put("/css/**","anon");
filterChainDefinitionMap.put("/js/**","anon");
filterChainDefinitionMap.put("/fonts/**","anon");
filterChainDefinitionMap.put("/img/**","anon");
filterChainDefinitionMap.put("/druid/**","anon");
filterChainDefinitionMap.put("/logout","logout");
filterChainDefinitionMap.put("/","anon");
filterChainDefinitionMap.put("/**","authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
} @Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
securityManager.setRememberMeManager(rememberMeManager());
return securityManager;
} @Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
return new LifecycleBeanPostProcessor();
} @Bean
public ShiroRealm shiroRealm(){
ShiroRealm shiroRealm = new ShiroRealm();
return shiroRealm;
} /**
* 记住我 cookie 对象
*/ public SimpleCookie rememberMeCookie(){
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setMaxAge();
return cookie;
} /**
* cookie 管理
*/
public CookieRememberMeManager rememberMeManager(){
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
//
cookieRememberMeManager.setCipherKey(Base64.decode("3AvVhmFLUs0KTA3Kprsdag=="));
return cookieRememberMeManager;
} @Bean
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
} @Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
} }

ShiroRealm

public class ShiroRealm extends AuthorizingRealm{

    @Autowired
private UserMapper userMapper; @Autowired
private UserRoleMapper userRoleMapper; @Autowired
private UserPermissionMapper userPermissionMapper; /**
* 获取用户角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
String userName = user.getUsername(); System.out.println("用户" + userName + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); //获取用户角色
List<Role> roleList = userRoleMapper.findByUserName(userName);
Set<String> rolegSet = new HashSet<>();
for(Role r : roleList){
rolegSet.add(r.getName());
}
simpleAuthorizationInfo.setRoles(rolegSet); //获取用户权限集
List<Permission> permissionList = userPermissionMapper.findByUserName(userName);
Set<String> permissionSet = new HashSet<>();
for(Permission p : permissionList){
permissionSet.add(p.getName());
}
simpleAuthorizationInfo.setStringPermissions(permissionSet);
return simpleAuthorizationInfo; } /**
* 登录认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials()); System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
User user = userMapper.findByUserName(userName); if (user == null) {
throw new UnknownAccountException("用户名或密码错误!");
}
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("用户名或密码错误!");
}
if (user.getStatus().equals("")) {
throw new LockedAccountException("账号已被锁定,请联系管理员!");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
return info;
} }

用户密码加密:MD5

public class MD5Utils {
private static final String SALT = "ABC"; private static final String ALGORITH_NAME = "md5"; private static final int HASH_ITERATIONS = ; public static String encrypt(String username,String password){
String newPassword =new SimpleHash(ALGORITH_NAME,password, ByteSource.Util.bytes(username+SALT),HASH_ITERATIONS).toHex();
return newPassword;
} public static void main(String[] args){
System.out.println(MD5Utils.encrypt("bai",""));
} }

异常处理:

@ControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler { @ExceptionHandler(value = AuthorizationException.class)
public String handleAuthorizationException(){
return "";
}
}

控制层:

@Controller
@RequestMapping("/user")
public class UserController { @RequiresPermissions("user:user")
@RequestMapping("list")
public String userList(Model model){
model.addAttribute("value","获取用户信息");
return "user";
} @RequiresPermissions("user:add")
@RequestMapping("add")
public String userAdd(Model model){
model.addAttribute("value","新增用户");
return "user";
} @RequiresPermissions("user:delete")
@RequestMapping("delete")
public String userDelete(Model model){
model.addAttribute("value","删除用户");
return "user";
}
}

shiro 入门的更多相关文章

  1. Apache shiro集群实现 (一) shiro入门介绍

    近期在ITOO项目中研究使用Apache shiro集群中要解决的两个问题,一个是Session的共享问题,一个是授权信息的cache共享问题,官网上给的例子是Ehcache的实现,在配置说明上不算很 ...

  2. 用户认证授权和Shiro入门

    1.权限管理基础(认证和授权): 前言 本文主要讲解的知识点有以下: 权限管理的基础知识 模型 粗粒度和细粒度的概念 回顾URL拦截的实现 Shiro的介绍与简单入门 一.Shiro基础知识 在学习S ...

  3. shiro入门教程

    一.shiro入门 shiro.ini和log4j.properties要放在src下面,lib是和src同级别的,然后lib下面的jar包是必须的,lib下面的jar包需要add path,如果报错 ...

  4. 转:JAVAWEB开发之权限管理(二)——shiro入门详解以及使用方法、shiro认证与shiro授权

    原文地址:JAVAWEB开发之权限管理(二)——shiro入门详解以及使用方法.shiro认证与shiro授权 以下是部分内容,具体见原文. shiro介绍 什么是shiro shiro是Apache ...

  5. Shiro入门指引

    最近项目中用到Shiro,专门对其研究了一番,颇有收获,以下是笔者最近写的博客,希望对大家入门有所帮助. Shiro入门资源整理 Shiro在SpringBoot中的使用 Shiro源码解析-登录篇 ...

  6. Shiro——入门Demo

    Shiro——入门Demo 环境-  引入相关maven依赖, shiro-core,commons-logging 配置shiro配置文件:ini后缀 主方法测试: import org.apach ...

  7. Shiro入门学习之shi.ini实现授权(三)

    一.Shiro授权 前提:需要认证通过才会有授权一说 1.授权过程 2.相关方法说明 ①subject.hasRole("role1"):判断是否有该角色 ②subject.has ...

  8. Shiro入门学习与实战(一)

    一.概述 1.Shiro是什么? Apache Shiro是java 的一个安全框架,主要提供:认证.授权.加密.会话管理.与Web集成.缓存等功能,其不依赖于Spring即可使用: Spring S ...

  9. shiro入门学习--使用MD5和salt进行加密|练气后期

    写在前面 在上一篇文章<Shiro入门学习---使用自定义Realm完成认证|练气中期>当中,我们学会了使用自定义Realm实现shiro数据源的切换,我们可以切换成从关系数据库如MySQ ...

  10. 安全框架Shiro入门

    Shiro简介 Apache Shiro是Java的一个安全框架,官网为shiro.apache.org,主要场景为控制登陆,判断用户是否有访问某个功能的权限等等. Shiro的核心功能(入门知识,只 ...

随机推荐

  1. python二进制转换

    例一.题目描述: 输入一个整数,输出该数二进制表示中1的个数.其中负数用补码表示. 分析: python没有unsigned int类型 >>> print ("%x&qu ...

  2. python数组和矩阵使用总结

    python数组和矩阵使用总结 1.数组和矩阵常见用法 Python使用NumPy包完成了对N-维数组的快速便捷操作.使用这个包,需要导入numpy. SciPy包以NumPy包为基础,大大的扩展了n ...

  3. 搭建eclipse开发环境

    eclipse-jee配置 基本配置: 快捷查找:window->perferences->搜索框搜索 utf8: window->perferences->general-& ...

  4. java 基础之 list

    ArrayList 基于 array, 顾名思义. ArrayList是用数组实现的,这个数组的内存是连续的,不存在你说的相邻元素之间还隔着其他内存什么的 索引ArrayList时,速度比原生数组慢是 ...

  5. <转载>css3 概述

    参照 https://www.ibm.com/developerworks/cn/web/1202_zhouxiang_css3/ http://www.cnblogs.com/ghost-xyx/p ...

  6. iOS工程结构理解

    iOS开发中关于工程结构有三个关键部分,分别是:Targets,projects 和 workspaces. Targets指定了工程或者库文件如何编译,包括building setting,comp ...

  7. PHP微信公共号自定义菜单。

    /**微信生成菜单 * [addMennu description] */ public function addMennu(){ $token = $this->getToken(); $ur ...

  8. CKEditor 5

    1.官网 https://ckeditor.com/ckeditor-5/download/ 2.

  9. 数据结构:Queue

    Queue设计与实现 Queue基本概念 队列是一种特殊的线性表 队列仅在线性表的两端进行操作 队头(Front):取出数据元素的一端 队尾(Rear):插入数据元素的一端 队列不允许在中间部位进行操 ...

  10. RabbitMQ.Net 应用(1)

    风浪子 概述 MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法.RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统.他遵循Mozilla Pu ...