Shiro关于session时间刷新规则重写,变更调用touch()逻辑,shiro可不刷新session

Shiro关于session时间刷新规则重写

为了迎合代码需求,前端需要对后台做轮训请求,于是遇到一个问题:由于每次请求shiro会对session做LastAccessTime时间更新,则导致用户只要浏览器保持页面,session将永远无法失效,那关于30分钟失效时间在这种场景下就不再有意义,所以我们需要做是的指定接口请求时不再刷新session时间,保证用户静默时能在理论失效时间后自动登出系统。

实际需求

指定请求路径,依旧会过shiro鉴权、有效判断,但不会刷新当前session时间。

源码分析

首先我查阅相关资料,没发现对指定请求路径做类似情况处理,如果有实际接口,那以下仅供参考。

shiro的Session接口提供了一个touch方法,负责session的刷新;session的代理对象最终会调用SimpleSession的touch():

public void touch() {
    this.lastAccessTime = new Date();        // 更新最后被访问时间为当前时间
}

但是touch方法是什么时候被调用的呢?每次进入ShiroFilter都会自动调用session.touch()来更新最后访问时间,ShiroFilter的类图如下:

在这里插入图片描述
session的失效时间是通过 session.getLastAccessTime()这个去判断的,也就是通过session的最后一次刷新时间去判断,而session最后一次操作时间是由shiro框架自动去刷新,调用的是touch()方法,而具体的实现是通过这个 AbstractShiroFilter类实现的,而这类实现是继承自OncePerRequestFilter这个类,实现了其中的 doFilterInternal 这个方法实现的,而AbstractShiroFilter 类是通过ShiroFilterFactoryBean 中的一个内部类SpringShiroFilter 这个类的构造方法来调用。 而ShiroFilterFactoryBean这各类又是通过DelegatingFilterProxy 代理来调用,这个DelegatingFilterProxy 代理最后注册到FilterRegistrationBean 这个类中,实现了shiro的功能。

ShiroFilterFactoryBean

protected AbstractShiroFilter createInstance() throws Exception {

        log.debug("Creating Shiro Filter instance.");

        SecurityManager securityManager = getSecurityManager();
        if (securityManager == null) {
            String msg = "SecurityManager property must be set.";
            throw new BeanInitializationException(msg);
        }

        if (!(securityManager instanceof WebSecurityManager)) {
            String msg = "The security manager does not implement the WebSecurityManager interface.";
            throw new BeanInitializationException(msg);
        }

        FilterChainManager manager = createFilterChainManager();

        //Expose the constructed FilterChainManager by first wrapping it in a
        // FilterChainResolver implementation. The AbstractShiroFilter implementations
        // do not know about FilterChainManagers - only resolvers:
        PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver();
        chainResolver.setFilterChainManager(manager);

        //Now create a concrete ShiroFilter instance and apply the acquired SecurityManager and built
        //FilterChainResolver.  It doesn't matter that the instance is an anonymous inner class
        //here - we're just using it because it is a concrete AbstractShiroFilter instance that accepts
        //injection of the SecurityManager and FilterChainResolver:
        return new SpringShiroFilter((WebSecurityManager) securityManager, chainResolver);
    }

因此,我们需要重写这个内部类,以重写我们session刷新的逻辑代码。

源码分析

创建一个自己所需要的类。继承ShiroFilterFactoryBean.java重写createInstance()
PersonShiroFilterFactoryBean.java

package **.bean;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.ExecutionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.BeanInitializationException;

import **.utils.StringUtilsAG;

public class PersonShiroFilterFactoryBean extends ShiroFilterFactoryBean {
	private List<String> WHITELIST;
    protected AbstractShiroFilter createInstance() throws Exception {


        SecurityManager securityManager = getSecurityManager();
        if (securityManager == null) {
            String msg = "SecurityManager property must be set.";
            throw new BeanInitializationException(msg);
        }

        if (!(securityManager instanceof WebSecurityManager)) {
            String msg = "The security manager does not implement the WebSecurityManager interface.";
            throw new BeanInitializationException(msg);
        }

        FilterChainManager manager = createFilterChainManager();

        //Expose the constructed FilterChainManager by first wrapping it in a
        // FilterChainResolver implementation. The AbstractShiroFilter implementations
        // do not know about FilterChainManagers - only resolvers:
        PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver();
        chainResolver.setFilterChainManager(manager);

        //Now create a concrete ShiroFilter instance and apply the acquired SecurityManager and built
        //FilterChainResolver.  It doesn't matter that the instance is an anonymous inner class
        //here - we're just using it because it is a concrete AbstractShiroFilter instance that accepts
        //injection of the SecurityManager and FilterChainResolver:
        return new PersonSpringShiroFilter ((WebSecurityManager) securityManager, chainResolver,WHITELIST.toArray(new String[WHITELIST.size()]));
    }
    public List<String> getWHITELIST() {
		return WHITELIST;
	}
	public void setWHITELIST(List<String> wHITELIST) {
		WHITELIST = wHITELIST;
	}
	private static final class PersonSpringShiroFilter extends AbstractShiroFilter {
		private String[] WHITELIST;
        protected PersonSpringShiroFilter (WebSecurityManager webSecurityManager, FilterChainResolver resolver,String [] WHITELIST) {
            super();
            this.WHITELIST = WHITELIST;
            if (webSecurityManager == null) {
                throw new IllegalArgumentException("WebSecurityManager property cannot be null.");
            }
            setSecurityManager(webSecurityManager);
            if (resolver != null) {
                setFilterChainResolver(resolver);
            }
        }
        @SuppressWarnings({ "unchecked", "rawtypes" })
		@Override
        protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, final FilterChain chain)
                throws ServletException, IOException {

            Throwable t = null;

            try {
                final ServletRequest request = prepareServletRequest(servletRequest, servletResponse, chain);
                final ServletResponse response = prepareServletResponse(request, servletResponse, chain);

                final Subject subject = createSubject(request, response);
                HttpServletRequest httpServletRequest = (HttpServletRequest) request;
                String servletPath= httpServletRequest.getServletPath();
                
                //noinspection unchecked
                subject.execute(new Callable() {
                    public Object call() throws Exception {
                    	if(!StringUtilsAG.checkWhiteList(servletPath,WHITELIST)){
                    		updateSessionLastAccessTime(request, response);
                    	}
                        executeChain(request, response, chain);
                        return null;
                    }
                });
            } catch (ExecutionException ex) {
                t = ex.getCause();
            } catch (Throwable throwable) {
                t = throwable;
            }

            if (t != null) {
                if (t instanceof ServletException) {
                    throw (ServletException) t;
                }
                if (t instanceof IOException) {
                    throw (IOException) t;
                }
                //otherwise it's not one of the two exceptions expected by the filter method signature - wrap it in one:
                String msg = "Filtered request failed.";
                throw new ServletException(msg, t);
            }
        }
    }
}

这里定义了一个自己的内部类,继承AbstractShiroFilter,重写了doFilterInternal,为updateSessionLastAccessTime(request, response)加上自己的逻辑代码,比如我这里就是加上了一套白名单列表机制的逻辑,寻求开放原则,需求不仅仅只是case by case,虽然这次只有一个需要排除,面对未来口子还是要留的。

ShiroConfiguration.java配置如下,将白名单配置入我们定义的PersonShiroFilterFactoryBean

/**
	 * Shiro的Web过滤器
	 *
	 * @param securityManager 项目
	 * @return
	 */
	@Bean
	public ShiroCUEFilterFactoryBean shiroFilter(SecurityManager securityManager) {
		PersonShiroFilterFactoryBeanfactory = new PersonShiroFilterFactoryBean();

		Map<String, Filter> filters = new HashMap<>();
		filters.put("authc", new ShiroPermissionsFilter());
		factory.setFilters(filters);
		factory.setSecurityManager(securityManager);
		factory.setLoginUrl(ShiroUrl.UnauthURL.getUrl());
		List<String> whiteList = new ArrayList<String>();
		whiteList.add("/api/getTodoNums");
		Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
		//过滤链定义,从上向下顺序执行,一般将/**放在最为下边
		filterChainDefinitionMap.put("/api/loginCheck", "anon");
		filterChainDefinitionMap.put("/**", "authc");
		factory.setFilterChainDefinitionMap(filterChainDefinitionMap);
		factory.setWHITELIST(whiteList);
		return factory;
	}

测试结果

将session过期时间调整为5分钟,启动之后,登陆系统,持续轮询请求,不再操作系统,5分钟后,接口返回401无效认证,返回登陆页。测试通过。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值