Syro in a multi-threaded environment

The main way that I understand Shiro SecurityUtils.getSubject() to work is that it returns the object associated with the current executable thread. However, this simply contradicts a servlet container such as Tomcat, which uses a thread pool to serve requests.

If Tomcat uses ThreadA to process requests, any calls to SecurityUtils.getSubject() should work fine. But, once ThreadB is selected, the user is lost, getSubject returns null, and isAuthenticated is now false. This is even though the user is still registered.

I confirmed this in my application. I use Shiro Core 1.2 and notice that my user is miraculously not authenticated when I view my application. If I look at the logs, the problem occurs as soon as another thread is used to service the request.

So, did I get Syro wrong? It seems that the "current user" should be tied to something longer than the current thread. I expect it to be session based. I know that Shiro has session control, but in all the examples I found, he says to get the current user by calling getSubject , which looks at ThreadContext. Did I miss something?

+6
source share
1 answer

So it turns out that I just didn't configure Shiro correctly. I have a web application, but I configured Security Manager in code. This resulted in the Security Manager being configured only for a specific thread. While the requests were being served by the same thread, it worked fine. But as soon as Tomcat chose a different thread, the user appeared inauthenticated.

Shiro has a filter for web applications that processes this script and associates the user with each incoming request. You should configure your application as follows, and not execute the security manager in code:

 <context-param> <param-name>shiroConfigLocations</param-name> <param-value>classpath:auth.ini</param-value> </context-param> <!-- Shiro Environment Listener --> <listener> <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class> </listener> <!-- Shiro Filter Configuration --> <filter> <filter-name>ShiroFilter</filter-name> <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class> </filter> <filter-mapping> <filter-name>ShiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 
+12
source

Source: https://habr.com/ru/post/911443/


All Articles