【问题标题】:Spring-security session not available in java threadjava线程中没有Spring-security会话
【发布时间】:2017-01-12 09:21:42
【问题描述】:

我正在开发一个 Spring-MVC 应用程序,我们在其中使用 Spring-security 进行身份验证和授权。有些任务我们想使用线程,但每当我们使用 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 的任何信息,例如带有 onlinePerson.getId(); 的 id,我会得到一个 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>

【问题讨论】:

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


【解决方案1】:

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

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

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

或者用环境变量:

spring.security.strategy=MODE_INHERITABLETHREADLOCAL

【讨论】:

  • 谢谢。我已经用 Security-applicationContext.xml 更新了我的问题。你知道上面的配置在哪里吗?
  • 我不认为它可以进去。您要么需要 ContextLoaderListener 作为第一种以编程方式设置它的方法,要么在启动时作为 JVM 选项:-Dspring.security.strategy=MODE_INHERITABLETHREADLOCAL
  • 这很好用。如您所见,我也在与另一个用户讨论这个问题。我有点困惑 Runnable 通常用于提供线程应该运行的代码,但 Runnable 本身与线程无关。它只是一个带有 run() 方法的对象。这是否意味着我正在创建的 new Thread() 不是线程。谢谢。
  • 我不得不承认,我没有仔细看你的代码。您正在通过扩展 Thread 类来创建一个新线程,虽然这很有效,但这是一种不好的做法。您应该通过实现 Runnable: Thread t = new Thread(new Runnable() { public void run() {...}).start(); 来做到这一点
  • 当我这样做时,IntelliJ 建议我创建一个新的 Lambda 表达式,如下所示new Thread(()-&gt; {//Thread code} )。在 Java8 出现之前,我也是这样创建线程的。:D
【解决方案2】:

您的线程类不是由 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 ...
   }
}

【讨论】:

    【解决方案3】:
    public class HelloThread extends Thread {
    
        public void run() {
            System.out.println("Hello from a thread!");
            sendNotification(notification, memberId);
        }
    
        public static void main(String args[]) {
            (new HelloThread()).start();
        }
    
    }
    

    Runnable常用于提供线程应该run的代码,但Runnable本身与线程无关。它只是一个带有run() 方法的对象。

    【讨论】:

    • 我不明白你的意思。你能详细说明一下吗?谢谢。
    【解决方案4】:
    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();
        }
    

    【讨论】:

    • 那么,你的意思是我通过 new Thread() 创建的线程实际上不是线程?
    • 是的,您没有创建线程,并且您的请求在 new Object() 上同步并发送
    猜你喜欢
    • 2011-12-11
    • 2018-11-14
    • 1970-01-01
    • 2018-09-27
    • 2011-05-09
    • 2016-12-05
    • 2011-08-19
    • 2017-02-27
    • 2015-05-28
    相关资源
    最近更新 更多