【问题标题】:Authentication of background tasks using Spring Boot and Spring Security使用 Spring Boot 和 Spring Security 对后台任务进行身份验证
【发布时间】:2015-03-18 02:05:05
【问题描述】:

我有一个后台任务(与 Project Reactor 一起运行,但我认为它不相关),我需要与经过身份验证的用户一起运行以通过一些 @PreAuthorize 注释方法。

我正在做这样的事情:

Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(login, password));
SecurityContextHolder.getContext().setAuthentication(authentication);

但是当我追踪到 authenticationManager 调用时,我发现它使用的是 Spring-Boot 的默认 InMemoryUserDetailsS​​ervice,而不是我的自定义身份验证配置。无论我是在 Web 请求线程还是在后台线程中运行身份验证,都会发生这种情况。

我不知道它是否相关,但我正在集成测试中运行此代码,并带有这些注释(以及其他):

@SpringApplicationConfiguration(classes=MyAppConfiguration.class)
@WebAppConfiguration
@IntegrationTest({"server.port:0"})

除了这个问题,我的测试向我的服务器发出了一个经过身份验证的 Web 请求,并且验证得很好。所以我至少知道我系统的 Web 部分正在使用正确的身份验证配置。

这是我的身份验证配置:

@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(jsr250Enabled=true, prePostEnabled=true)
public abstract class BaseSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public LocalUserDetailsService localUserDetailsService;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(localUserDetailsService);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers( "/admin/**" ).hasRole( "ADMIN" )
}

【问题讨论】:

    标签: spring spring-mvc spring-security spring-boot project-reactor


    【解决方案1】:

    没有你的测试实现很难说,但重要的是你在集成测试中运行它 也许你忘记在你的 mockMvc 中添加 `FilterChainProxy

    喜欢这个mvc = MockMvcBuilders.webAppContextSetup(context) .addFilter(springSecurityFilterChain).build();

    filterChainPrioxy 的实例可以@Autowired 到您的测试类中,当然这个答案可能没有意义,取决于您的测试类的实现

    ---在您发表评论后

    这一行:

    SecurityContextHolder.getContext().setAuthentication(authentication);
    

    为当前线程分配安全约束并且不影响后台运行的线程,除非您的策略是全局的并且不是默认的

    【讨论】:

    • 您好,感谢您的回复。这没有帮助有两个原因:1)我没有使用MockMvc,我正在运行实际的服务器并使用Spring的HttpEntity API进行真正的Http调用。 2)实际的http请求工作正常并正确验证。是后台线程获取了错误的身份验证配置,或者可能是整个错误的 Spring 上下文?
    • 我认为您在这里处理的不是spring上下文本身,而是SecurityContext,它将安全约束分配给当前线程,如果后台有另一个线程它有自己的securityContext,因此在不同的集合上运行约束
    • 因此您必须在该线程中访问 SecurityContextHolder 并尝试进行修改,或者使用 GlobalSecurityContextHolderStrategy 来全局分配安全策略(如果它仅用于测试)
    猜你喜欢
    • 2015-11-22
    • 2014-07-03
    • 2020-05-12
    • 1970-01-01
    • 2018-11-07
    • 2012-11-27
    • 2011-10-17
    • 2017-08-14
    相关资源
    最近更新 更多