SSM集成Shiro安全框架(二)

本文详细介绍了Shiro框架中权限管理和RememberMe功能的实现方式,包括配置文件applicationContext-shiro.xml的设置,如何通过UserController进行登录操作,以及密码重复次数限制的实现。此外,还涉及了自定义RetryLimitCredentialsMatcher类以限制登录尝试次数。

五、RememberMe

1.UserController.java

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest request) {
		System.out.println("UserController的login方法开始执行");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		int rememeberMe = Integer.valueOf(request.getParameter("rememeberMe"));
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		if(rememeberMe == 1) token.setRememberMe(true);
		try {
			//执行认证操作.
			subject.login(token);
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "success";
	}

2.applicationContext-shiro.xml

`<!-- 安全管理器 -->`
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    ……
  <property name="rememberMeManager" ref="rememberMeManager"/>
</bean>&nbsp;
	<!-- rememberMe管理器 -->
	<bean id="rememberMeManager"
		class="org.apache.shiro.web.mgt.CookieRememberMeManager"> <!--注入自定义cookie(主要是设置寿命, 默认的一年太长) -->
		<property name="cookie" ref="rememberMeCookie" />
	</bean>

	<!--手动指定cookie -->
	<bean id="rememberMeCookie"
		class="org.apache.shiro.web.servlet.SimpleCookie">
		<constructor-arg value="rememberMe" />
		<property name="httpOnly" value="true" />
		<property name="maxAge" value="604800" /><!-- 7天 -->
	</bean>
	<bean id="sessionIdCookie"
		class="org.apache.shiro.web.servlet.SimpleCookie">
		<constructor-arg value="sid" />
		<property name="httpOnly" value="true" />
		<property name="maxAge" value="-1" />
	</bean>
/** = user

六、密码重复次数限制

1.applicationContext-shiro.xml

	<!-- 密码重复次数限制 -->
	<!-- 凭证匹配器 -->
	<bean id="credentialsMatcher"
		class="com.yan.shiro.common.RetryLimitCredentialsMatcher"> <!-- 自定义 RetryLimitCredentialsMatcher的相应位置-->
		<constructor-arg index="0" ref="cacheManager" />
		<constructor-arg index="1" value="5" />
		<property name="hashAlgorithmName" value="md5" />
		<property name="hashIterations" value="1024" />
	</bean>
	<bean id="cacheManager"
		class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>  <!-- 密码重复次数限制 -->
	</bean>

2.shiro-ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false"  name="shirocache">
    <diskStore path="java.io.tmpdir"/>
	<!-- name:缓存名称。 maxElementsInMemory:缓存最大数目 maxElementsOnDisk:硬盘最大缓存个数。 eternal:对象是否永久有效,一但设置了,timeout将不起作用。 
		overflowToDisk:是否保存到磁盘,当系统当机时 timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 
		timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。 
		diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts 
		of the Virtual Machine. The default value is false. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。 
		diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 
		clearOnFlush:内存数量最大时是否清除。 memoryStoreEvictionPolicy: Ehcache的三种清空策略; FIFO,first 
		in first out,这个是大家最熟的,先进先出。 LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。 
		LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。 -->
	<defaultCache maxElementsInMemory="10000" eternal="false"
		timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false"
		diskPersistent="false" diskExpiryThreadIntervalSeconds="120" />
	<!-- 登录记录缓存 锁定10分钟 -->
	<cache name="lgoinRetryCache" maxEntriesLocalHeap="2000"
		eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="0"
		overflowToDisk="false" statistics="true">
	</cache>

	<cache name="authorizationCache" maxElementsInMemory="2000"
		eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0"
		overflowToDisk="false" statistics="true">
	</cache>

	<cache name="authenticationCache" maxElementsInMemory="2000"
		eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0"
		overflowToDisk="false" statistics="true">
	</cache>

	<cache name="shiro-activeSessionCache" maxEntriesLocalHeap="2000"
		eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0"
		overflowToDisk="false" statistics="true">
	</cache>
	
	<cache name="shiro_cache" maxElementsInMemory="2000"
		maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="0"
		timeToLiveSeconds="0" maxElementsOnDisk="0" overflowToDisk="true"
		memoryStoreEvictionPolicy="FIFO" statistics="true">
	</cache>
</ehcache>  

3.RetryLimitCredentialsMatcher.java

package com.yan.shiro.common;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 验证器,增加了登录次数校验功能
 */
public class RetryLimitCredentialsMatcher extends HashedCredentialsMatcher {
    private static final Logger log = LoggerFactory.getLogger(RetryLimitCredentialsMatcher.class);
    
    //集群中可能会导致出现验证多过5次的现象,因为AtomicInteger只能保证单节点并发
    private Cache<String, AtomicInteger> lgoinRetryCache;
 
    private int maxRetryCount = 5;
 
    private String lgoinRetryCacheName;
 
    public void setMaxRetryCount(int maxRetryCount) {
        this.maxRetryCount = maxRetryCount;
    }
 
    public RetryLimitCredentialsMatcher(CacheManager cacheManager,String lgoinRetryCacheName) {
        this.lgoinRetryCacheName = lgoinRetryCacheName;
        lgoinRetryCache = cacheManager.getCache(lgoinRetryCacheName);
    }
 
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    	System.out.println("已经进入doCredentialsMatch方法");
        String username = (String) token.getPrincipal();
        //retry count + 1
        AtomicInteger retryCount = lgoinRetryCache.get(username);
        if (null == retryCount) {
            retryCount = new AtomicInteger(0);
            lgoinRetryCache.put(username, retryCount);
        }
        if (retryCount.incrementAndGet() > 5) {
            log.warn("username: " + username + " tried to login more than 5 times in period");
            throw new ExcessiveAttemptsException("username: " + username + " tried to login more than 5 times in period"
            );
        }
        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
            //clear retry data
            lgoinRetryCache.remove(username);
        }
        return matches;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值