zoukankan      html  css  js  c++  java
  • shiro权限框架与spring框架轻松整合

    shiro是一个权限框架,用于管理网站的权限,大到网站登录过滤,小到一个菜单或按钮是否显示,shiro学习起来非常简单,以下是shiro的执行流程图:

    20140926152205_672.png

    看完不懂的请下载shiro全套视频教程:

    http://pan.baidu.com/s/1jHOX2MM

    Subject为当前用户,当它访问系统的时候,就会经过SecurityManager安全管理器,安全管理器类似一个中转站,它实际上会让Realm类来处理用户的认证和授权信息,认证和授权说白了就是账号登陆验证和查找用户所具有的权限,并将权限封装起来供SecurityManager来管理的意思(我个人理解)。

    Realm主要是和数据库打交道,相当于数据源,由于数据源有很多种,例如mysql,oracle,sqlserver等,所以使用系统的不行,我们要自己自定义一个类,用来继承Realm,但通常情况下,我们继承Realm的子类比较多,它的子类是AuthorizingRealm,使用方法后面会讲到。

    下面开始介绍shiro权限框架如何与spring框架整合,需要什么jar包请自己百度,记住要在你javaweb项目的基础上增加权限框架哦,因为权限框架并不是一个完整项目,不能独立运行:

    第一步:配置web.xml文件,在web.xml文件中加入shiro过滤器,用于过滤网页的所有请求(最好放在编码filter过滤器前后,‘shiroFilter’要与下面applicationContext-shiro.xml文件中的bean id对应)。

    	<!-- shiro的filter -->
    	<!-- shiro过虑器,DelegatingFilterProxy通过代理模式将spring容器中的bean和filter关联起来 -->
    	<filter>
    		<filter-name>shiroFilter</filter-name>
    		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    		<!-- 设置true由servlet容器控制filter的生命周期 -->
    		<init-param>
    			<param-name>targetFilterLifecycle</param-name>
    			<param-value>true</param-value>
    		</init-param>
    		<!-- 设置spring容器filter的bean id,如果不设置则找与filter-name一致的bean-->
    		<init-param>
    			<param-name>targetBeanName</param-name>	
    			<param-value>shiroFilter</param-value>
    		</init-param>
    	</filter>
    	<filter-mapping>
    		<filter-name>shiroFilter</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>

    第二步:创建applicationContext-shiro.xml文件用于添加与spring整合的相关配置,具体配置的内容请看下面代码的注释。

    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
    		http://www.springframework.org/schema/mvc 
    		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
    		http://www.springframework.org/schema/context 
    		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    		http://www.springframework.org/schema/aop 
    		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
    		http://www.springframework.org/schema/tx 
    		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    
    <!-- web.xml中shiro的filter对应的bean -->
    <!-- Shiro 的Web过滤器 -->
    	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    		<property name="securityManager" ref="securityManager" />
    		<!-- loginUrl认证提交地址,如果没有认证将会请求此地址进行认证,请求此地址将由formAuthenticationFilter进行表单认证 -->
    		<property name="loginUrl" value="/login.action" />
    		<!-- 认证成功统一跳转到first.action,建议不配置,shiro认证成功自动到上一个请求路径 -->
    		<property name="successUrl" value="/first.action"/>
    		<!-- 通过unauthorizedUrl指定没有权限操作时跳转页面-->
    		<property name="unauthorizedUrl" value="/refuse.jsp" />
    		<!-- 自定义filter配置 -->
    		<property name="filters">
    			<map>
    				<!-- 将自定义 的FormAuthenticationFilter注入shiroFilter中-->
    				<entry key="authc" value-ref="formAuthenticationFilter" />
    			</map>
    		</property>
    		
    		<!-- 过虑器链定义,从上向下顺序执行,一般将/**放在最下边 -->
    		<property name="filterChainDefinitions">
    			<value>
    				<!-- 对静态资源设置匿名访问 -->
    				/images/** = anon
    				/js/** = anon
    				/styles/** = anon
    				<!-- 验证码,可匿名访问 -->
    				/validatecode.jsp = anon
    				
    				<!-- 请求 logout.action地址,shiro去清除session-->
    				/logout.action = logout
    				<!--商品查询需要商品查询权限 ,取消url拦截配置,使用注解授权方式 -->
    				<!-- /items/queryItems.action = perms[item:query]
    				/items/editItems.action = perms[item:edit] -->
    				<!-- 配置记住我或认证通过可以访问的地址 -->
    				/index.jsp  = user
    				/first.action = user
    				/welcome.jsp = user
    				<!-- /** = authc 所有url都必须认证通过才可以访问-->
    				/** = authc
    				<!-- /** = anon所有url都可以匿名访问 -->
    				
    			</value>
    		</property>
    	</bean>
    
    <!-- securityManager安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    		<property name="realm" ref="customRealm" />
    		<!-- 注入缓存管理器 -->
    		<property name="cacheManager" ref="cacheManager"/>
    		<!-- 注入session管理器 -->
    		<property name="sessionManager" ref="sessionManager" />
    		<!-- 记住我 -->
    		<property name="rememberMeManager" ref="rememberMeManager"/>
    		
    	</bean>
    
    <!-- realm -->
    <bean id="customRealm" class="cn.itcast.ssm.shiro.CustomRealm">
    	<!-- 将凭证匹配器设置到realm中,realm按照凭证匹配器的要求进行散列 -->
    	<property name="credentialsMatcher" ref="credentialsMatcher"/>
    </bean>
    
    <!-- 凭证匹配器 -->
    <bean id="credentialsMatcher"
    	class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    	<property name="hashAlgorithmName" value="md5" />
    	<property name="hashIterations" value="1" />
    </bean>
    
    <!-- 缓存管理器 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        	<property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
        </bean>
    
    <!-- 会话管理器 -->
        <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
            <!-- session的失效时长,单位毫秒 -->
            <property name="globalSessionTimeout" value="600000"/>
            <!-- 删除失效的session -->
            <property name="deleteInvalidSessions" value="true"/>
        </bean>
    
    <!-- 自定义form认证过虑器 -->
    <!-- 基于Form表单的身份验证过滤器,不配置将也会注册此过虑器,表单中的用户账号、密码及loginurl将采用默认值,建议配置 -->
    	<bean id="formAuthenticationFilter" 
    	class="cn.itcast.ssm.shiro.CustomFormAuthenticationFilter ">
    		<!-- 表单中账号的input名称 -->
    		<property name="usernameParam" value="username" />
    		<!-- 表单中密码的input名称 -->
    		<property name="passwordParam" value="password" />
    		<!-- 记住我input的名称 -->
    		<property name="rememberMeParam" value="rememberMe"/>
     </bean>
    
    <!-- rememberMeManager管理器,写cookie,取出cookie生成用户信息 -->
    	<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
    		<property name="cookie" ref="rememberMeCookie" />
    	</bean>
    	<!-- 记住我cookie -->
    	<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
    		<!-- rememberMe是cookie的名字 -->
    		<constructor-arg value="rememberMe" />
    		<!-- 记住我cookie生效时间30天 -->
    		<property name="maxAge" value="2592000" />
    	</bean>
    </beans>

    上面有两个bean对应的class是需要我们自定义的,一个是我们前面提到的验证和授权的Realm类,另一个表单验证的过滤器,用于验证自定义的表单信息,比如对验证码的验证。

    第三步:自定义Realm,这是这个spring和shiro整合中最重要的一环,主要是从数据库中查询相关信息存储到shhiro框架中,用于后期框架的自动权限认证和授权,里面的方法不太详细,只能告诉你们大致流程是这样的。

    public class CustomRealm extends AuthorizingRealm {
    	
    	//注入service
    	@Autowired
    	private SysService sysService;
    
    	// 设置realm的名称
    	@Override
    	public void setName(String name) {
    		super.setName("customRealm");
    	}
    
    	@Override //用于用户认证
    	protected AuthenticationInfo doGetAuthenticationInfo(
    			AuthenticationToken token) throws AuthenticationException {
    		
    		// token是用户输入的用户名和密码 
    		// 第一步从token中取出用户名
    		String userCode = (String)token.getPrincipal();
    
    		// 第二步:根据用户输入的userCode从数据库查询
    -----------------------------------------------------------------------------
                    这里省略N多字。。。。。。。。。
    -------------------------------------------------------------------------------
    		//这一步很关键,将从数据库中的用户名和密码存储到这个对象中:simpleAuthenticationInfo,它会自动和传过来的token进行对比,如果
    		//验证不通过则会抛出异常。
    		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
    				activeUser, password,ByteSource.Util.bytes(salt), this.getName());
    
    		return simpleAuthenticationInfo;
    	}
    
    	// 用于授权
    	@Override
    	protected AuthorizationInfo doGetAuthorizationInfo(
    			PrincipalCollection principals) {
    		
    		//从 principals获取主身份信息
    		//将getPrimaryPrincipal方法返回值转为真实身份类型(在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型),
    		ActiveUser activeUser =  (ActiveUser) principals.getPrimaryPrincipal();
    		
    		//根据身份信息获取权限信息
    		//从数据库获取到权限数据
    -----------------------------------------------------------------------------
                    这里省略N多字。。。。。。。。。
    -------------------------------------------------------------------------------
    		//查到权限数据,返回授权信息(要包括上边的permissions)
    		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    		//将上边查询到授权信息填充到simpleAuthorizationInfo对象中
    		simpleAuthorizationInfo.addStringPermissions(permissions);
    
    		return simpleAuthorizationInfo;
    	}
    	
    	//清除缓存
    	public void clearCached() {
    		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
    		super.clearCache(principals);
    	}
    
    }

    第四步:表单验证码验证

    public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
    
    	//原FormAuthenticationFilter的认证方法
    	@Override
    	protected boolean onAccessDenied(ServletRequest request,
    			ServletResponse response) throws Exception {
    		//在这里进行验证码的校验
    		
    		//从session获取正确验证码
    		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    		HttpSession session =httpServletRequest.getSession();
    		//取出session的验证码(正确的验证码)
    		String validateCode = (String) session.getAttribute("validateCode");
    		
    		//取出页面的验证码
    		//输入的验证和session中的验证进行对比 
    		String randomcode = httpServletRequest.getParameter("randomcode");
    		if(randomcode!=null && validateCode!=null && !randomcode.equals(validateCode)){
    			//如果校验失败,将验证码错误失败信息,通过shiroLoginFailure设置到request中
    			httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError");
    			//拒绝访问,不再校验账号和密码 
    			return true; 
    		}
    		return super.onAccessDenied(request, response);
    	}
    
    		
    }

    第五步:登录action相关,这个action层不太正规,action层应该将用户的用户名和密码信息封装到token中,传给realm的,也可能是上面的applicationContext-shiro.xml文件中配置了form过滤器,将登陆信息封装到了token中,这里是通过抛异常的方式来判断是否登录成功,后面我会补上。

    	@RequestMapping("login")
    	public String login(HttpServletRequest request)throws Exception{
    		
    		//如果登陆失败从request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名
    		String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
    		//根据shiro返回的异常类路径判断,抛出指定异常信息
    		if(exceptionClassName!=null){
    			if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
    				//最终会抛给异常处理器
    				throw new CustomException("账号不存在");
    			} else if (IncorrectCredentialsException.class.getName().equals(
    					exceptionClassName)) {
    				throw new CustomException("用户名/密码错误");
    			} else if("randomCodeError".equals(exceptionClassName)){
    				throw new CustomException("验证码错误 ");
    			}else {
    				throw new Exception();//最终在异常处理器生成未知错误
    			}
    		}
    		//此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径
    		//登陆失败还到login页面
    		return "login";
    	}

    第六步:配置shiro的ehcache缓存信息,避免频繁访问数据库获取权限造成数据库压力,提高系统效率,创建shiro-ehcache.xml文件,然后添加到上面的applicationContext-shiro.xml文件中。

    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    	<!--diskStore:缓存数据持久化的目录 地址  -->
    	<diskStore path="F:developehcache" />
    	<defaultCache 
    		maxElementsInMemory="1000" 
    		maxElementsOnDisk="10000000"
    		eternal="false" 
    		overflowToDisk="false" 
    		diskPersistent="false"
    		timeToIdleSeconds="120"
    		timeToLiveSeconds="120" 
    		diskExpiryThreadIntervalSeconds="120"
    		memoryStoreEvictionPolicy="LRU">
    	</defaultCache>
    </ehcache>

    第七步:由于上面的自定义Realm中有一个清理缓存的方法,主要是用于当用户权限更改时,能迫使用户马上下线,防止用户因为session问题而一直处于登录状态,我们做一个清理缓存的action方法:

    @Controller
    public class ClearShiroCache {
    	
    	//注入realm
    	@Autowired
    	private CustomRealm customRealm;
    	
    	@RequestMapping("/clearShiroCache")
    	public String clearShiroCache(){
    		
    		//清除缓存,将来正常开发要在service调用customRealm.clearCached()
    		customRealm.clearCached();
    		
    		return "success";
    	}
    
    }

    第八步:在applicationContext.xml中开启shiro注解支持(springmvc.xml文件,也可能是在视图控制器的controller扫描那一行上加)

    	<!-- 使用spring组件扫描 -->
    	<context:component-scan base-package="cn.baidu.ssm.controller" />
    	<!-- 开启aop,对类代理 -->
    	<aop:config proxy-target-class="true"></aop:config>
    	<!-- 开启shiro注解支持 -->
    	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">				
    		<property name="securityManager" ref="securityManager" />
    	</bean>	

    最后面有一个“记住我”的功能需要实现,由于我们在applicationContext-shiro.xml文件中配置了formAuthenticationFilter的form认证过滤器,你只需要在登录界面创建一个<input>的name="rememberMe"属性的checkbox就可以轻松实现记住我的功能了,这样用户就可以在指定的时间内不用再输入用户名和密码了。

    写到这里,完毕。

    补充,shiro框架登录controller层代码,这样就会进入到realm里面了:

    	@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
    	public String doLogin(LoginForm form, RedirectAttributes attr) {
    		Subject subject = SecurityUtils.getSubject();
    		UsernamePasswordToken token = new UsernamePasswordToken(form.getUsername(), form.getPassword());
    		try {
    			subject.login(token);
    		} catch (AuthenticationException e) {
    			attr.addFlashAttribute("error", "用户名或密码错误");
    		}
    		if (subject.isAuthenticated()) {
    			return "redirect:/";
    		}
    		return "redirect:/login";
    	}
    个人分类
  • 相关阅读:
    ASP.NET Razor
    ASP.NET Razor
    ASP.NET Razor
    ASP.NET Razor C# 和 VB 代码语法
    ASP.NET Razor 简介
    aspnet_regiis -i VS 20XX 的开发人员命令提示符
    web.config
    Java_Freemarker
    SQL SELECT INTO 语句
    SQL UNION 和 UNION ALL 操作符
  • 原文地址:https://www.cnblogs.com/jiadp/p/9276785.html
Copyright © 2011-2022 走看看