SpringMVC+Shiro配置

9 篇文章 0 订阅
1 篇文章 0 订阅

1、第一步当然是要引入jar包啦,至于jar包就不上传了,百度一下有很多

2、配置shiro配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
					http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
					http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
					http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
					http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
					http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
					http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"
	default-lazy-init="true">
	<!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java -->
	<bean id="myRealm" class="com.***.***.common.shiro.realm.MyRealm">
		<!-- <property name="authorizationCachingEnabled" value="false" /> -->
	</bean>
	
	 <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<!-- classpath是缓存属性的配置文件 -->
		<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml" />
	</bean> 
	<!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->
	<!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->
	<!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="myRealm" />
          <!--注入缓存管理器  -->  
        <property name="cacheManager" ref="cacheManager"/>  
	</bean>
	<!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->
	<!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- Shiro的核心安全接口,这个属性是必须的 -->
		<property name="securityManager" ref="securityManager" />
		<!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
		<property name="loginUrl" value="/" />
		<!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码为main.jsp了) -->
		<!-- <property name="successUrl" value="/system/main"/> -->
		<!-- 用户访问未对其授权的资源时,所显示的连接 -->
		<!-- 若想更明显的测试此属性可以修改它的值,如unauthor.jsp,然后用[玄玉]登录后访问/admin/listUser.jsp就看见浏览器会显示unauthor.jsp -->
		<property name="unauthorizedUrl" value="/" />
		<!-- Shiro连接约束配置,即过滤链的定义 -->
		<!-- 此处可配合我的这篇文章来理解各个过滤连的作用http://blog.csdn.net/jadyer/article/details/12172839 -->
		<!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->
		<!-- anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 -->
		<!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
		<property name="filterChainDefinitions">
			<value>
				/mydemo/login=anon
				/mydemo/getVerifyCodeImage=anon
				/main**=authc
				/user/info**=authc
				/admin/listUser**=authc,perms[admin:manage]
			</value>
		</property>
	</bean>

	<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

	<!-- 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 -->
	<!-- 配置以下两个bean即可实现此功能 -->
	<!-- Enable Shiro Annotations for Spring-configured beans. Only run after 
		the lifecycleBeanProcessor has run -->
	<!-- 由于本例中并未使用Shiro注解,故注释掉这两个bean(个人觉得将权限通过注解的方式硬编码在程序中,查看起来不是很方便,没必要使用) -->
	<!-- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" 
		depends-on="lifecycleBeanPostProcessor"/> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> 
		<property name="securityManager" ref="securityManager"/> </bean> -->

</beans>
以及对应的shiro缓存配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
	<diskStore path="java.io.tmpdir/PMS/shiro" />
	<defaultCache maxElementsInMemory="10000" eternal="false"
		timeToIdleSeconds="1200" timeToLiveSeconds="1200" overflowToDisk="true"
		diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
		diskPersistent="false" diskExpiryThreadIntervalSeconds="120" />
	<cache name="com.jeecms.cms.shiro.shiroCache"
		maxElementsInMemory="500" eternal="false" timeToIdleSeconds="1200"
		overflowToDisk="true" diskPersistent="true" />
</ehcache>
3、第三步需要把上面写到的一个自定义的
继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java
<pre name="code" class="html"><bean id="myRealm" class="com.***.***.common.shiro.realm.MyRealm">
		<!-- <property name="authorizationCachingEnabled" value="false" /> -->
	</bean>

 也就是MyRealm类写好 

/**
 * 自定义Realm
 * 
 * @author tianyong
 */
public class MyRealm extends AuthorizingRealm {
	private static final Logger log = LoggerFactory.getLogger(MyRealm.class);
	// 注入service
	@Autowired
	UserService userService;
	@Autowired
	ResourceService resourceService;
	/**
	 * 为当前登录的Subject授予角色和权限
	 * @author jianfei
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		if (principals == null) {
			throw new AuthorizationException(
					"PrincipalCollection method argument cannot be null.");
		}
		// 获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
		String regName = (String) getAvailablePrincipal(principals);

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		List<String> roleList = new ArrayList<String>();
		//用于存放权限信息
		List<Resource> resourceList = new ArrayList<Resource>();
		// //从数据库中获取当前登录用户的详细信息
		User user = userService.queryUserByUserName(regName);
		if (null != user && null != user.getRoles()) {
			//得到角色集合
			Set<Role> roles = user.getRoles();
			//遍历角色
			for(Role role : roles){
				roleList.add(role.getCode());
				//查询权限如果是超级管理员取出所有权限
				if(role.getCode().contains(SystemConstants.SUPER_ADMIN_ROLE_CODE)){
					resourceList = resourceService.getAllResource();
					break;
				}else{
					resourceList.addAll(role.getResources());
				}
			}
			info.addRoles(roleList);
		} else {
			throw new AuthorizationException();
		}
		if(resourceList != null && resourceList.size() > 0){
			//权限集合
			List<String> perList = new ArrayList<String>();
			//遍历资源,取出权限集合
			for(Resource r : resourceList){
				String pre = r.getActions();
				if(null != pre && !pre.equals("")){
					perList.add(pre);
				}
			}
			//遍历权限集合取出权限
			for(String perStr:perList){
    			String[] perArray = perStr.split(",");
    			for(String str:perArray){
    				 if (str!=null && !"".equals(str.trim()))
    					 info.addStringPermission(str);
//    				 	System.out.println("该用户下拥有权限:"+str);
    			}
    		}
		}
		return info;
	}

	/**
	 * 用户登录权限认证
	 * @author jianfei
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		// 获取基于用户名和密码的令牌
		// 实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的
		// 两个token的引用都是一样的
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
//		System.out.println("验证当前Subject时获取到token为"+ ReflectionToStringBuilder.toString(token,ToStringStyle.MULTI_LINE_STYLE));
		//从token中获取用户名
		String userName = token.getUsername();
		if (userName != null && !"".equals(userName)) {
			User user = userService.queryUserByUserName(userName);
			if(null != user){
				if(user.getStatus() == SystemConstants.STATUS_NOT_ACTIVE){
					throw new MyException("用户未激活,请联系管理员");
				}
				SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName, user.getPassword(), getName());
				if (getCredentialsMatcher().doCredentialsMatch(token,authenticationInfo)){
					//用户信息存入session
					Subject currentUser = SecurityUtils.getSubject();
					currentUser.getSession().setAttribute(SystemConstants.SEESION_IUSER, user);
					//如果缓存存在权限信息则清空
					Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
					if (cache != null) {
			            if (log.isTraceEnabled()) {
			                log.trace("Attempting to retrieve the AuthorizationInfo from cache.");
			            }
			            cache.remove(userName);
			        }
					return authenticationInfo;
				}else{
					throw new MyException("密码不正确");
				}
			}else{
				throw new MyException("用户不存在");
			}
		}else{
			throw new MyException("用户名不能为空");
		}
	}
}

以及最后的web.xml文件中的shiro过滤器
<!-- 配置shiro过滤器 -->
	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

以上便是我的shiro配置方法


总体来说shiro流程为

1、当用户登录触发过滤器将会调用自定义myrealm中的AuthenticationInfo查询根据自己写的方法查询是否允许登录

2、登录完成后,当页面上遇到shiro标签后将会调用没有myrealm中的AuthorizationInfo方法,获得当前登录人的具体权限

      如果当前登录用户拥有权限标签中书写的权限,则内容显示,否则不显示。

对与shiro我只是初步理解,欢迎大牛前来指点。。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值