Shiro complaining “There is no session with id xxx” with DefaultSecurityManager

安稳与你 提交于 2019-12-05 00:15:32

I was getting this error and found that completely destroying any existing session before calling subject.login(credentials) fixed it.

// Login the user
private Subject loginUser()
{
  ensureUserIsLoggedOut();
  Subject subject = SecurityUtils.getSubject();
  subject.login(credentials);
}

And the supporting routines are:

// Logout the user fully before continuing.
private void ensureUserIsLoggedOut()
{
    try
    {
        // Get the user if one is logged in.
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser == null)
            return;

        // Log the user out and kill their session if possible.
        currentUser.logout();
        Session session = currentUser.getSession(false);
        if (session == null)
            return;

        session.stop();
    }
    catch (Exception e)
    {
        // Ignore all errors, as we're trying to silently 
        // log the user out.
    }
}

Shiro is validating credentials against SecuritySubject, which is stored in Session. So, it's very likely your session expired after some time of inactivity. You can change expiration time in web.xml or you can use Shiro rememberMe function, but your client have to support cookies. After rememberMe function SecuritySubject will obtain different session and will return false against isAuthenticated, but isRemembered will return true.

The session will never expired This will produce another problem, when your session will never expire. It will most likely get you out of memory, because your web container is most likely using memory session manager.

<session-config>
    <session-timeout>-1</session-timeout>
</session-config>

Shiro rememberMe http://shiro.apache.org/java-authentication-guide.html

//Example using most common scenario:
//String username and password.  Acquire in
//system-specific manner (HTTP request, GUI, etc)

UsernamePasswordToken token =
 new UsernamePasswordToken( username, password );

//”Remember Me” built-in, just do this:
token.setRememberMe(true);

We can disable the session storage in shiro.

The org.apache.shiro.mgt.DefaultSessionStorageEvaluator class contains a flag called sessionStorageEnabled. We can make it false.

I use the following in my spring application context for not using session storage.

<bean id="defaultSessionStorageEvaluator" class="org.apache.shiro.mgt.DefaultSessionStorageEvaluator">
        <property name="sessionStorageEnabled" value="false" />

<bean id="defaultSubjectDAO" class="org.apache.shiro.mgt.DefaultSubjectDAO">
        <property name="sessionStorageEvaluator" ref="defaultSessionStorageEvaluator" />
    </bean>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!