我通过实现UserDetailsService使用基于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);
}
}
现在问题是当我从一个弹簧控制器创建一个新线程时。如何在该线程中验证我的用户?
答案 0 :(得分:1)
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(loadUserByUsername), password));
答案 1 :(得分: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>
像魅力一样工作。