Shiro 自己实现登录后重新生成sessionid

Shiro Security是非常不错的Security框架,我们系统在使用过程中发现Shiro在登录之后不会生成新的Jessionid。这显然会出现Session_Fixation。Shiro自己说会在下一个版本1.3 fix这个问题,在这之前只能学Spring Security来实现重新生成Session。其实简单就是在登陆之后把session数据复制一份到新的session。

Shiro中要做到这一点可以通过实现可以通过继承org.apache.shiro.web.filter.authc.AuthenticatingFilter (一般是继承AuthenticatingFilter的子类FormAuthenticationFilter),重写executeLogin方法就可以了。

 protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        AuthenticationToken token = createToken(request, response);
        if (token == null) {
            String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
                    "must be created in order to execute a login attempt.";
            throw new IllegalStateException(msg);
        }
        try {
            Subject subject = getSubject(request, response);
            //获取session数据
            Session session = subject.getSession();
            final LinkedHashMap<Object, Object> attributes = new LinkedHashMap<Object, Object>();
            final Collection<Object> keys = session.getAttributeKeys();
            for (Object key : keys) {
                final Object value = session.getAttribute(key);
                if (value != null)
                { attributes.put(key, value); }
            }
            session.stop();
            subject.login(token);
            // 登录成功后复制session数据 
            session = subject.getSession();
            for (final Object key : attributes.keySet())
               { session.setAttribute(key, attributes.get(key)); }
            return onLoginSuccess(token, subject, request, response);
        } catch (AuthenticationException e) {
            return onLoginFailure(token, e, request, response);
        }
    }

你可能感兴趣的:(jsesion,shiro,Java,Java,Web)