2012-11-13 4 views
1

저는 UserDetailsService를 구현하여 스프링 기반 인증을 사용하고 있습니다. 내 스프링 설정사용자 생성 스레드에서 스프링 인증을 사용할 수 없음

<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가 포함 된 부모에 의해 생성 된 경우에만 작동합니다. 스레드 풀을 사용하는 경우 (최선의 방법이 될 수 있음) 그럴 필요가 없습니다. –

관련 문제