2

Hey

I have found some code that allow to use spring events in async way by overriding the code ApplicationEventMulticaster, so each listener will run its in own thread. example code here

My question is:

Does the security context will be the same as the publisher thread? or i have to to pass user logged id to each publisher

Thanks,

Oak

Edit:

Going through the docs:

i have found

Some applications aren't entirely suitable for using a ThreadLocal, because of the specific way they work with threads. For example, a Swing client might want all threads in a Java Virtual Machine to use the same security context. SecurityContextHolder can be configured with a strategy on startup to specify how you would like the context to be stored. For a standalone application you would use the SecurityContextHolder.MODE_GLOBAL strategy. Other applications might want to have threads spawned by the secure thread also assume the same security identity. This is achieved by using SecurityContextHolder.MODE_INHERITABLETHREADLOCAL. You can change the mode from the default SecurityContextHolder.MODE_THREADLOCAL in two ways. The first is to set a system property, the second is to call a static method on SecurityContextHolder. Most applications won't need to change from the default, but if you do, take a look at the JavaDocs for SecurityContextHolder to learn more.

So it seems that if one set up SecurityContextHolder.MODE_INHERITABLETHREADLOCAL is should work

My question is: does anyone have experience with this kind of configuration?

Community
  • 1
  • 1
oak
  • 2,898
  • 2
  • 32
  • 65
  • new `securityContext` will be created for new asych thread If you need to keep the same `SecurityContext` you are responsible for passing present `SecurityContext` to `SecurityContextHolder` in new thread that will assign it to `ThreadLoacal` in this situation – mariubog Jan 28 '15 at 16:33
  • also you should clear `SecurityContextHolder` after thread is done – mariubog Jan 28 '15 at 16:38
  • @user1289300, the thanks for answering did you try it? i have updated my question. – oak Jan 29 '15 at 14:20

1 Answers1

0

Solution:

combining the doc from the question and @viator remark at https://stackoverflow.com/a/3468965/1211174

Setup the rule to inherit security context from the thread

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"        p:targetClass="org.springframework.security.core.context.SecurityContextHolder"
    p:targetMethod="setStrategyName" p:arguments="MODE_INHERITABLETHREADLOCAL" />

Make sure spring event will be asynced

<bean id="applicationEventMulticaster"
    class="org.springframework.context.event.SimpleApplicationEventMulticaster">
    <property name="taskExecutor">
        <bean class="org.springframework.core.task.SimpleAsyncTaskExecutor">
        </bean>
    </property>
</bean>
Community
  • 1
  • 1
oak
  • 2,898
  • 2
  • 32
  • 65