Shiro 设置session超时时间

Shiro 是一个轻量的安全框架,使用和配置都很方便,是小型web项目很好的选择。


Shiro的Session可以设置超时时间,默认是30min

By default, Shiro's SessionManager implementations 
default to a 30 minute session timeout. That is, if any Session created remains 
idle (unused, where its lastAccessedTime isn't updated)for 30 minutes or more,
 the Session is considered expired and will not be allowed to be used anymore.

意思是,登录30分钟后,会话超时,需要重新登录。


这个超时时间是可以自定义的,有两种方式:


  1. 通过配置文件
    Setting the Default Session Timeout in shiro.ini
    [main]
    ...
    # 3,600,000 milliseconds = 1 hour
    securityManager.sessionManager.globalSessionTimeout = 3600000

  2. 通过api:Shiro的Session接口有一个setTimeout()方法
    //登录后,可以用如下方式取得session
    SecurityUtils.getSubject().getSession().setTimeout(30000);
    
    查看Shiro的api文档,

setTimeout

void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionExceptionSets the time in milliseconds that the session may remain idle before expiring.A negative value means the session will never expire.A non-negative value (0 or greater) means the session expiration will occur if idle for that length of time.*Note: if you are used to the HttpSession's getMaxInactiveInterval() method, the scale on this method is different: Shiro Sessions use millisecond values for timeout whereas HttpSession.getMaxInactiveInterval uses seconds. Always use millisecond values with Shiro sessions.Parameters:maxIdleTimeInMillis - the time in milliseconds that the session may remain idle before expiring.Throws:InvalidSessionException - if the session has been stopped or expired prior to calling this method.Since:0.2


设置的最大时间,正负都可以,为负数时表示永不超时。开发过程中,设置负数时,遇到点儿问题:


SecurityUtils.getSubject().getSession().setTimeout(-1l);


    这样调用后,总是抛出session已经过时的异常,一直找不到原因,后来调试源码才发现,这里设置的时间单位是:ms,但是Shiro会把这个时间转成:s,而且是会舍掉小数部分,这样我设置的是-1ms,转成s后就是0s,马上就过期了,所以后面再对这个会话进行操作时,总会抛异常,正确的设置永不超时的方式应该是:

                    // timeout:-1000ms 永不超时
                    SecurityUtils.getSubject().getSession().setTimeout(-1000l);

    这个应该是api文档不够详细造成的吧。

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值