Spring线程中没有Spring安全会话

时间:2017-01-12 09:21:43

标签: java spring multithreading spring-mvc spring-security

我正在开发一个Spring-MVC应用程序,我们使用Spring-security进行身份验证和授权。有些任务我们想要使用Thread,但每当我们使用Java线程时,都会尝试获取有关经过身份验证的用户的详细信息。

我也尝试了@Async注释,但我们所看到的不仅仅是我们在线程中需要的代码的特定部分。

有没有办法在Java线程中注入spring-session?如果没有,则在单独的线程中运行部分代码的任何替代方法。谢谢。

示例代码:

  public void sendNotification(Notification notification, int memberId) {
            Thread thread = new Thread(() -> {
            Person onlinePerson = this.personService.getCurrentlyAuthenticatedUser();
            GroupMembers groupMembers = this.groupMembersService.getMemberById(memberId);
}
thread.start();
}

现在,在上面的代码中,如果我尝试获取有关onlinePerson的任何信息,例如id with onlinePerson.getId();,我会得到一个NPE。查看错误日志:

Exception in thread "Thread-9" java.lang.NullPointerException
    at com.project.spring.chat.ChatServiceImpl.lambda$sendNotification$3(ChatServiceImpl.java:532)
    at java.lang.Thread.run(Thread.java:745)

知道如何解决这个问题。谢谢。

Security-applicationContext.xml:

 <security:http pattern="/resources/**" security="none"/>
    <security:http create-session="ifRequired" use-expressions="true" auto-config="false" disable-url-rewriting="true">
        <security:form-login login-page="/login" username-parameter="j_username" password-parameter="j_password"
                             login-processing-url="/j_spring_security_check" default-target-url="/canvaslisting"
                             always-use-default-target="true" authentication-failure-url="/denied"/>
        <security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService"
                              token-validity-seconds="1209600" data-source-ref="dataSource"/>
        <security:logout delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>
       <!--<security:intercept-url pattern="/**" requires-channel="https"/>-->
        <security:port-mappings>
            <security:port-mapping http="80" https="443"/>
        </security:port-mappings>
        <security:logout logout-url="/logout" logout-success-url="/" success-handler-ref="myLogoutHandler"/>

        <security:session-management session-fixation-protection="newSession">
            <security:concurrency-control session-registry-ref="sessionReg" max-sessions="5" expired-url="/login"/>
        </security:session-management>
    </security:http>

    <beans:bean id="sessionReg" class="org.springframework.security.core.session.SessionRegistryImpl"/>

    <beans:bean id="rememberMeAuthenticationProvider"
                class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
        <beans:constructor-arg index="0" value="_spring_security_remember_me"/>
        <beans:constructor-arg index="1" ref="userDetailsService"/>
        <beans:constructor-arg index="2" ref="jdbcTokenRepository"/>
        <property name="alwaysRemember" value="true"/>
    </beans:bean>

    <beans:bean id="jdbcTokenRepository"
                class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
        <beans:property name="createTableOnStartup" value="false"/>
        <beans:property name="dataSource" ref="dataSource"/>
    </beans:bean>

    <!-- Remember me ends here -->
    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider user-service-ref="LoginServiceImpl">
            <security:password-encoder ref="encoder"/>
        </security:authentication-provider>
    </security:authentication-manager>

    <beans:bean id="encoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="11"/>
    </beans:bean>

    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
        <beans:property name="passwordEncoder" ref="encoder"/>
    </beans:bean>
</beans>

4 个答案:

答案 0 :(得分:3)

这是因为会话信息存储在ThreadLocal中,针对处理HTTP请求的线程。默认情况下,新线程无法使用它(无论是手动创建还是通过@Async创建)。

幸运的是,这很容易配置:

SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL) //in a context loader listener for example

或者使用环境变量:

spring.security.strategy=MODE_INHERITABLETHREADLOCAL

答案 1 :(得分:1)

您的线程类不受spring管理,因为在您的代码示例中,您通过调用其构造函数手动创建类实例。您需要获取spring管理的线程实例,并使用spring ApplicationContext从bean中检索它。我想你想要同时运行多个线程实例?如果是这样,您可能需要为每个线程执行一个新的线程实例(bean)。以下是如何实现此目标的示例:

@Component
@Scope("prototype") // the scope “prototype" will return a new instance each time when the bean will be retrieved.
public class YourThreadClass implements Runnable {
   private String anyString;

   @Autowired
   AnyOtherBean anyOtherBean; // since YourThreadClass is now managed by spring, you can also inject services / components into YourThreadClass 
}

@Component
public class YourClassThatStartsTheThread{
   @Autowired
   ApplicationContext ctx;

   public void sendNotification(Notification notification, int memberId){
        // ... your code ....
        yourThreadClass aNewInstanceOfYourThreadClass = (YourThreadClass) ctx.getBean(yourThreadClass);
        // ... your code ...
   }
}

答案 2 :(得分:0)

Runnable

run()通常用于提供线程应该dikt = {'bloomberg': Timestamp('2009-01-26 10:00:00'), 'investingcom': Timestamp('2009-01-01 09:00:00')} 的代码,但MI= MultiIndex(levels=[['Existing Home Sales MoM'], ['investingcom', 'bloomberg']], labels=[[0, 0], [0, 1]], names=['indicator', 'source']) 本身与线程无关。它只是一个df = pd.DataFrame(index = MI, columns=["datetime"],data =np.full((2,1),np.NaN)) 方法的对象。

答案 3 :(得分:0)

public void sendNotification(Notification notification, int memberId) {
        Thread thread = new Thread(new Runnable(){
            public void run()
            {
                Person onlinePerson = this.personService.getCurrentlyAuthenticatedUser();
                GroupMembers groupMembers = this.groupMembersService.getMemberById(memberId);
            }
        }
        thread.start();
    }