欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Shiro权限管理框架(四):深入分析Shiro中的Session管理

程序员文章站 2023-11-08 18:04:16
其实关于Shiro的一些学习笔记很早就该写了,因为懒癌和拖延症晚期一直没有落实,直到今天公司的一个项目碰到了在集群环境的单点登录频繁掉线的问题,为了解决这个问题,Shiro相关的文档和教程没少翻。最后问题解决了,但我觉得我也是时候来做一波Shiro学习笔记了。 本篇是Shiro系列第四篇,Shiro ......

其实关于shiro的一些学习笔记很早就该写了,因为懒癌和拖延症晚期一直没有落实,直到今天公司的一个项目碰到了在集群环境的单点登录频繁掉线的问题,为了解决这个问题,shiro相关的文档和教程没少翻。最后问题解决了,但我觉得我也是时候来做一波shiro学习笔记了。

本篇是shiro系列第四篇,shiro中的过滤器初始化流程和实现原理。shiro基于url的权限控制是通过filter实现的,本篇从我们注入的shirofilterfactorybean开始入手,翻看源码追寻shiro中的过滤器的实现原理。

首发地址:

session

Shiro权限管理框架(四):深入分析Shiro中的Session管理

sessionmanager

Shiro权限管理框架(四):深入分析Shiro中的Session管理

我们在配置shiro时配置了一个defaultwebsecuritymanager,先来看下

Shiro权限管理框架(四):深入分析Shiro中的Session管理

defaultwebsecuritymanager

    public defaultwebsecuritymanager() {
        super();
        ((defaultsubjectdao) this.subjectdao).setsessionstorageevaluator(new defaultwebsessionstorageevaluator());
        this.sessionmode = http_session_mode;
        setsubjectfactory(new defaultwebsubjectfactory());
        setremembermemanager(new cookieremembermemanager());
        setsessionmanager(new servletcontainersessionmanager());
    }

在它的构造方法中注入了一个servletcontainersessionmanager

public class servletcontainersessionmanager implements websessionmanager {
    public session getsession(sessionkey key) throws sessionexception {
        if (!webutils.ishttp(key)) {
            string msg = "sessionkey must be an http compatible implementation.";
            throw new illegalargumentexception(msg);
        }
        httpservletrequest request = webutils.gethttprequest(key);
        session session = null;
        httpsession httpsession = request.getsession(false);
        if (httpsession != null) {
            session = createsession(httpsession, request.getremotehost());
        }
        return session;
    }
    
    private string gethost(sessioncontext context) {
        string host = context.gethost();
        if (host == null) {
            servletrequest request = webutils.getrequest(context);
            if (request != null) {
                host = request.getremotehost();
            }
        }
        return host;
    }

    protected session createsession(sessioncontext sessioncontext) throws authorizationexception {
        if (!webutils.ishttp(sessioncontext)) {
            string msg = "sessioncontext must be an http compatible implementation.";
            throw new illegalargumentexception(msg);
        }
        httpservletrequest request = webutils.gethttprequest(sessioncontext);
        httpsession httpsession = request.getsession();
        string host = gethost(sessioncontext);
        return createsession(httpsession, host);
    }
    
    protected session createsession(httpsession httpsession, string host) {
        return new httpservletsession(httpsession, host);
    }
}

servletcontainersessionmanager本身并不管理会话,它最终操作的还是httpsession,所以只能在servlet容器中起作用,它不能支持除使用http协议的之外的任何会话。

所以一般我们配置shiro都会配置一个defaultwebsessionmanager,它继承了defaultsessionmanager,看看defaultsessionmanager的构造方法:

public defaultsessionmanager() {
    this.deleteinvalidsessions = true;
    this.sessionfactory = new simplesessionfactory();
    this.sessiondao = new memorysessiondao();
}

这里的sessiondao初始化了一个memorysessiondao,它其实就是一个map,在内存中通过键值对管理session。

public memorysessiondao() {
    this.sessions = new concurrenthashmap<serializable, session>();
}

httpservletsession

public class httpservletsession implements session {
    public httpservletsession(httpsession httpsession, string host) {
        if (httpsession == null) {
            string msg = "httpsession constructor argument cannot be null.";
            throw new illegalargumentexception(msg);
        }
        if (httpsession instanceof shirohttpsession) {
            string msg = "httpsession constructor argument cannot be an instance of shirohttpsession.  this " +
                    "is enforced to prevent circular dependencies and infinite loops.";
            throw new illegalargumentexception(msg);
        }
        this.httpsession = httpsession;
        if (stringutils.hastext(host)) {
            sethost(host);
        }
    }
    protected void sethost(string host) {
        setattribute(host_session_key, host);
    }
    public void setattribute(object key, object value) throws invalidsessionexception {
        try {
            httpsession.setattribute(assertstring(key), value);
        } catch (exception e) {
            throw new invalidsessionexception(e);
        }
    }
}

shiro的httpservletsession只是对javax.servlet.http.httpsession进行了简单的封装,所以在web应用中对session的相关操作最终都是对javax.servlet.http.httpsession进行的,比如上面代码中的sethost()是将内容以键值对的形式保存在httpsession中。

先来看下这张图:

Shiro权限管理框架(四):深入分析Shiro中的Session管理

先了解上面这几个类的关系和作用,然后我们想管理shiro中的一些数据就非常方便了。

sessiondao是session管理的顶层接口,定义了session的增删改查相关方法。

public interface sessiondao {
    serializable create(session session);
    session readsession(serializable sessionid) throws unknownsessionexception;
    void update(session session) throws unknownsessionexception;
    void delete(session session);
    collection<session> getactivesessions();
}

abstractsessiondao是一个抽象类,在它的构造方法中定义了javauuidsessionidgenerator作为sessionidgenerator用于生成sessionid。它虽然实现了create()和readsession()两个方法,但具体的流程调用的是它的两个抽象方法docreate()和doreadsession(),需要它的子类去干活。

public abstract class abstractsessiondao implements sessiondao {
    private sessionidgenerator sessionidgenerator;
    public abstractsessiondao() {
        this.sessionidgenerator = new javauuidsessionidgenerator();
    }
    
    public serializable create(session session) {
        serializable sessionid = docreate(session);
        verifysessionid(sessionid);
        return sessionid;
    }
    protected abstract serializable docreate(session session);

    public session readsession(serializable sessionid) throws unknownsessionexception {
        session s = doreadsession(sessionid);
        if (s == null) {
            throw new unknownsessionexception("there is no session with id [" + sessionid + "]");
        }
        return s;
    }
    protected abstract session doreadsession(serializable sessionid);
}

看上面那张类图abstractsessiondao的子类有三个,查看源码发现cachingsessiondao是一个抽象类,它并没有实现这两个方法。在它的子类enterprisecachesessiondao中实现了docreate()和doreadsession(),但doreadsession()是一个空实现直接返回null。

    public enterprisecachesessiondao() {
        setcachemanager(new abstractcachemanager() {
            @override
            protected cache<serializable, session> createcache(string name) throws cacheexception {
                return new mapcache<serializable, session>(name, new concurrenthashmap<serializable, session>());
            }
        });
    }

enterprisecachesessiondao依赖于它的父级cachingsessiondao,在他的构造方法中向父类注入了一个abstractcachemanager的匿名实现,它是一个基于内存的sessiondao,它所创建的mapcache就是一个map。

我们在shiro配置类里通过 sessionmanager.setsessiondao(new enterprisecachesessiondao()); 来使用它。然后在cachingsessiondao.getcachedsession() 打个断点测试一下,可以看到cache就是一个concurrenthashmap,在内存中以key-value的形式保存着jsessionid和session的映射关系。

Shiro权限管理框架(四):深入分析Shiro中的Session管理

再来看abstractsessiondao的第三个实现memorysessiondao,它就是一个基于内存的sessiondao,简单直接,构造方法直接new了一个concurrenthashmap。

    public memorysessiondao() {
        this.sessions = new concurrenthashmap<serializable, session>();
    }

那么它和enterprisecachesessiondao有啥区别,其实enterprisecachesessiondao只是cachingsessiondao的一个默认实现,在cachingsessiondao中cachemanager是没有默认值的,在enterprisecachesessiondao的构造方法将其初始化为一个concurrenthashmap。

如果我们直接用enterprisecachesessiondao其实和memorysessiondao其实没有什么区别,都是基于map的内存型sessiondao。但是cachingsessiondao的目的是为了方便扩展的,用户可以继承cachingsessiondao并注入自己的cache实现,比如以redis缓存session的rediscache。

其实在业务上如果需要redis来管理session,那么直接继承abstractsessiondao更好,有redis支撑中间的cache就是多余的,这样还可以做分布式或集群环境的session共享(分布式或集群环境如果中间还有一层cache那么还要考虑同步问题)。

回到开篇提到的我们公司项目集群环境下单点登录频繁掉线的问题,其实就是中间那层cache造成的。我们的业务代码中redissessiondao是继承自enterprisecachesessiondao的,这样一来那在redis之上还有一个基于内存的cache层。此时用户的session如果发生变更,虽然redis中的session是同步的,cache层没有同步,导致的现象就是用户在一台服务器的session是有效的,另一台服务器cache中的session还是旧的,然后用户就*下线了。