2012-11-13 42 views
1

我通过实现UserDetailsS​​ervice来使用基于Spring的认证。以下是我的Spring配置在用户创建的线程中不提供弹簧认证

<authentication-manager> 
    <authentication-provider user-service-ref="authenticationService"> 
     <password-encoder ref="passwordEncoder"> 
      <salt-source ref="authenticationService"/> 
     </password-encoder> 
    </authentication-provider> 
</authentication-manager> 

我的身份验证服务是这样的:

public class AuthenticationServiceImpl implements AuthenticationService, UserDetailsService, SaltSource { 
    .... 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { 
     .... 
     return new org.springframework.security.core.userdetails.User(username, user.getPassword(), true, true, true, true, authorities); 
    } 
} 

现在的问题是,当我从我的春天控制器之一创建一个新的线程。我如何在该线程中验证我的用户?

回答

1
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(loadUserByUsername), password)); 
1

我发现了一个更好的解决方案,将其设置在配置本身。使用以下代码:

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

工程就像一个魅力。

+0

N.B.这只有在线程由包含SecurityContext的父代创建时才有效。如果你使用线程池(这将是最佳实践),情况并非如此。 –