Shiro框架在学习项目(基于maven下ssm+shiro)中的简单回顾

目录

零、框架使用三步骤

1.使用框架为目的的三步骤:

2.已学习框架为目的的步骤:待完善

一、Shiro框架简介

二、Shiro框架架构

1.Shiro简单架构:Subject--SecurityManager--Realm

2.Shiro详细架构:

Shiro架构相关要素

Shiro架构常用功能

三、Shiro框架基本配置

扫描二维码关注公众号,回复: 3393978 查看本文章

1.Shiro依赖配置:Spring整合Shiro

2.Shiro组件配置

3.自己写一个Realm类,把这个类ShiroUserRealm.java注入安全管理器的Realm属性

4.在web.xm配置(委托过滤器代理DelegatingFilterProxy)Shiro中的核心过滤器,负责拦截过滤请求信息

四、Shiro框架应用

0.在数据库资源(菜单)表中添加权限标志符字段permission

1.登录认证大致流程 基于spring、半注解方式

Controller层代码示意

2.授权流程 基于spring、半注解方式

用户授权大致流程

授权检测:使用注解修饰方法method或class类

五、Shiro框架的SessionManager和CacheManager

Shiro缓存配置

1.添加Shiro缓存依赖

2.Shiro缓存的配置文件ehcache.xml

3.其他内容待更新


零、框架使用三步骤

1.使用框架为目的的三步骤:

  • 导jar包
  • 写配置文件
  • 具体使用

2.已学习框架为目的的步骤:待完善

  • 用熟框架
  • 断点调试
  • uml类关系结构图
  • ...

一、Shiro框架简介

二、Shiro框架架构

1.Shiro简单架构:Subject--SecurityManager--Realm

2.Shiro详细架构:

Shiro架构相关要素

  • Subject(主体):与软件交互的一个特定的实体(用户、第三方服务等)。
  • SecurityManager(安全管理器) :Shiro 的核心,用来协调管理组件工作。
  • Authenticator(认证管理器):负责执行认证操作
  • Authorizer(授权管理器):负责授权检测
  • SessionManager(会话管理):负责创建并管理用户 Session 生命周期,提供一个强有力的 Session 体验。
  • SessionDAO:代表 SessionManager 执行 Session 持久(CRUD)动作,它允许任何存储的数据挂接到 session 管理基础上。
  • CacheManager(缓存管理器):提供创建缓存实例和管理缓存生命周期的功能
  • Cryptography(加密管理器):提供了加密方式的设计及管理。
  • Realms(领域对象):是shiro和你的应用程序安全数据之间的桥梁。

Shiro架构常用功能

  • 认证资源访问权限

  • 授权资源访问权限<不使用Shiro授权管理还可以通过interceptor,aop实现>

  • 缓存实例的创建和生命周期管理
  • 加密方式设计和管理

三、Shiro框架基本配置

1.Shiro依赖配置:Spring整合Shiro

<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-spring</artifactId>
   <version>1.3.2</version>
</dependency>

2.Shiro组件配置

  • 向IOC注入安全管理SecurityManager对象,并为其realm属性注入引用实例shiroUserRealm<自己写的Realm>
  • 向IOC注入Shiro过滤工厂ShiroFilterFactory:
    • 为其securityManager属性注入securityManager
    • 为其loginUrl属性注入登录页url,例如本例:"/doLoginUI.do"
    • 为其FilterChainDefinitionMap属性注入过滤链Map,哪些资源要过滤key:资源路径,什么权限可以访问value:anon匿名,即不登录也可以访问/logout登出时可访问/authc需要认证才能访问
  • 向IOC注入生命周期管理LifecycleBeanPostProcessor

    备注:官文+有道... Spring的Bean post处理器,它在实现可初始化或可销毁接口的Shiro对象上自动调用init()和/或destroy()方法。这个post处理器使在Spring中配置Shiro bean变得更加容易,因为用户不必担心是否必须指定init-method和-method bean属性。

  • 向IOC注入Bean对象的代理DefaultAdvisorAutoProxyCreator
  • 向IOC注入授权属性AuthorizationAttributeSourceAdvisor,并向其注入属性securityManager
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="  
       http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd  
       http://www.springframework.org/schema/mvc   
       http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd   
       http://www.springframework.org/schema/tx   
       http://www.springframework.org/schema/tx/spring-tx-4.3.xsd   
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/util 
       http://www.springframework.org/schema/util/spring-util-4.3.xsd
       http://www.springframework.org/schema/data/jpa 
       http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd" >
       
       <!-- 配置shiro中的SecurityManager -->
       <bean id="securityManager" 
             class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
             <property name="Realm" ref="shiroUserRealm"/>
       </bean>
       <!-- 配置Shiro的FilterFactoryBean对象 -->
       <bean id="shiroFilterFactory" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
         <property name="SecurityManager" ref="securityManager"/>
         <!-- 设置此项的目的是让用户进行登录认证 -->
         <property name="LoginUrl" value="/doLoginUI.do"/>
         <!-- 设置请求过滤规则 -->
         <property name="FilterChainDefinitionMap">
            <map>
               <entry key="/bower_components/**" value="anon"/>
               <entry key="/build/**" value="anon"/>
               <entry key="/dist/**" value="anon"/>
               <entry key="/plugins/**" value="anon"/>
               <entry key="/user/doLogin.do" value="anon"/>
               <entry key="/doLogout.do" value="logout"/>
               <entry key="/**" value="authc"/><!-- 必须认证 -->
            </map>
         </property>
       </bean>
       
     <!-- 配置bean对象的生命周期管理 -->
     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor">
     </bean>
     <!-- 配置Bean对象的代理 -->
     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
           depends-on="lifecycleBeanPostProcessor">
     </bean> 
     <!-- 配置授权属性-->
     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
         <property name="SecurityManager" ref="securityManager"/>
     </bean>     
</beans>

3.自己写一个Realm类,把这个类ShiroUserRealm.java注入安全管理器的Realm属性

自定义一个Realm类继承自授权域AuthorizingRealm,包含信息:

  • 密码加密方式(加密算法/次数等):重写public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher);
  • 认证信息:重写protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token);
  • 授权信息:重写protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
/**
 * 此对象中要完成用户认证信息,授权信息
 * 的获取和封装等业务操作。
 */
@Service
public class ShiroUserRealm extends AuthorizingRealm {
	@Autowired
	private SysUserDao sysUserDao;	
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysRoleMenuDao sysRoleMenuDao;
	@Autowired
	private SysMenuDao sysMenuDao;
	
	/**
	 * 指定加密算法和加密次数(默认就是1次)
	 * @param credentialsMatcher
	 */
    @Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		HashedCredentialsMatcher hashMatcher=
		new HashedCredentialsMatcher("MD5");
		hashMatcher.setHashIterations(1);//默认加密次数为一次
		super.setCredentialsMatcher(hashMatcher);
	}
	/**
	 * 负责用户认证信息的获取以及封装
	 */
	@Override//认证
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		System.out.println("doGetAuthenticationInfo");
		//1.获取用户身份信息(例如用户名)
		String userName=(String)token.getPrincipal();//身份(控制层提交)
		//2.基于用户名访问数据库获取用户信息
		SysUser user=sysUserDao.findUserByUserName(userName);
		//3.对用户信息进行验证
		//3.1验证是否为空(为空说明此此用户不存在)
		if(user==null)
		throw new UnknownAccountException();
		//3.2验证此用户是否被禁用了(禁用则不允许登录)
		if(user.getValid()==0)
		throw new LockedAccountException();
		//4.基于业务封装用户数据?(例如密码,盐值)
		ByteSource credentialsSalt=
		ByteSource.Util.bytes(user.getSalt());
		SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(
			user, //principal (身份)
			user.getPassword(),//hashedCredentials(已加密的密码)
			credentialsSalt, //credentialsSalt
			this.getName());//realmName(当前类的名字)
		System.out.println("realmName="+this.getName());
		return info;//将此值返回给认证管理器(Authentication)
	}
	/**负责用户授权信息({"sys:user:valid",...})
	 * 的获取及封装*/
	@Override//授权
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("doGetAuthorizationInfo");
		//1.获取用户id(基于此id逐步获取用户具备的权限)
		SysUser user=(SysUser)principals.getPrimaryPrincipal();
		//2.基于用户id获取角色信息(用户角色中间表:user_id,role_id)
		List<Integer> roleIds=sysUserRoleDao.findRoleIdsByUserId(user.getId());
		//3.基于角色id获取菜单id(角色菜单关系表:role_id,menu_id)
		List<Integer> menuIds=
		sysRoleMenuDao.findMenuIdsByRoleIds(
		roleIds.toArray(new Integer[]{}));
		//4.基于菜单id获取权限标识(例如"sys:user:valid")
		List<String> permissions=
		sysMenuDao.findPermissions(
		menuIds.toArray(new Integer[]{}));
		//5.封装权限信息
		SimpleAuthorizationInfo info=
		new SimpleAuthorizationInfo();
		Set<String> perSet=new HashSet<>();
		for(String per:permissions){
			if(!StringUtils.isEmpty(per)){
				perSet.add(per);
			}
		}
		System.out.println("user.permissions="+perSet);
		info.setStringPermissions(perSet);
		return info;//此对象会传递给谁?授权管理器
	}
}

4.在web.xm配置(委托过滤器代理DelegatingFilterProxy)Shiro中的核心过滤器,负责拦截过滤请求信息

<!-- Shiro中的核心过滤器(负责拦截请求) -->
	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<param-name>targetBeanName</param-name>
			<param-value>shiroFilterFactory</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

四、Shiro框架应用

0.在数据库资源(菜单)表中添加权限标志符字段permission

三表关系:用户对应角色,角色对应资源

  • 用户表
  • 角色表
  • 资源表     添加权限标志字段

1.登录认证大致流程 基于spring、半注解方式

  • 基本场景:客户端用户输入用户名+密码点击确定按钮,后台认证用户信息并做出正确响应;
  • Dao层:提供通过用户名查询用户表信息的方法
  • Service层:提供***Realm类(含密码加密方式/认证信息/授权信息),如public class ShiroUserRealm extends AuthorizingRealm
  • Controller层:提供登录页跳转@RequestMapping("doLoginUI"),登录信息认证响@RequestMapping("doLogin")+@ResponseBody
  • 登录页login.html编写:提供点击事件进行点击登录操作,实现异步登录操作

Controller层代码示意

@RequestMapping("/")
@Controller
public class SysLoginController {
	   @RequestMapping("doLoginUI")
	   public String doLoginUI(){
		   return "login";
	   }
	   @RequestMapping("doLogin")
	   @ResponseBody
	   public JsonResult doLogin(String username,String password){
		   //1.获取Subject对象
		   Subject subject=SecurityUtils.getSubject();
		   //2.通过Subject提交用户信息,交给shiro框架进行认证操作
		   //2.1对用户进行封装
		   UsernamePasswordToken token=
		   new UsernamePasswordToken(
				   username,//身份信息
				   password);//凭证信息
		   //2.2对用户信息进行身份认证
		   subject.login(token);
		   //分析:
		   //1)token会传给shiro的SecurityManager
		   //2)SecurityManager将token传递给认证管理器
		   //3)认证管理器会将token传递给realm
		   return new JsonResult("login ok");
	   }
}

2.授权流程 基于spring、半注解方式

用户授权大致流程

  • 基本场景
  • Dao层:
    • 提供通过用户id查询用户角色中间表信息的方法;
    • 提供同过用户角色id查询角色资源中间表信息的方法;
    • 提供通过资源id查询资源表信息的方法;
  • Service层:与登录认证一样在自定义Realm里提供授权所需的用户拥有的权限标志符
  • 授权过程在后台完成所以不需要在Controller层写相关代码,只需要注解方式注明相关方法要求的权限标志符 

授权检测:使用注解修饰方法method或class类

//For example, this declaration: 

@RequiresPermissions( {"file:read", "write:aFile.txt"} )
void someMethod(); 
@RequiresPermissions("sys:user:valid")

五、Shiro框架的SessionManager和CacheManager

Shiro缓存配置

1.添加Shiro缓存依赖

  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
   <version>1.3.2</version>
  </dependency>

2.Shiro缓存的配置文件ehcache.xml

  • 在IOC中注入EhCacheManager,并为其缓存管理配置文件cacheManagerConfigFile属性注入值
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/> 
</bean>
  • 在IOC中注入的安全管理DefaultWebSecurityManager
    • 缓存管理属性值注入
    • 域属性值注入
<bean id="securityManager" 
           class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
         <property name="cacheManager" ref="cacheManager"/>
         <property name="realm" ref="shiroUserRealm"></property>
</bean>

3.其他内容待更新

猜你喜欢

转载自blog.csdn.net/GUARDIANONE/article/details/82856192