如何使用放心从集成测试中的 SecurityContextHolder 身份验证中获取正确的用户?

问题描述

我无法使用放心在集成测试中成功获得正确的用户名。我不明白为什么 SecurityContextHolder 的身份验证返回“anonymousUser”而不是“myuser”。我的配置有什么问题?

响应正文与预期不符。预期:是“身份验证 用户 myuser 成功” 实际:身份验证成功 用户匿名用户

控制器:

@RestController
@RequestMapping(value = "/api/ping",produces = TEXT_PLAIN_VALUE)
public class PingController {

    @GetMapping
    public @ResponseBody String ping() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return "Authentication successful for user " + authentication.getName();
    }
}

安全配置:

http.authorizeRequests()
                .antMatchers("/api/ping").permitAll()

                .antMatchers("/api/**").hasRole(ROLE_API)
                 
                //...another roles...

                .anyRequest().permitAll()

                .and()
                .httpBasic()
                .authenticationEntryPoint(basicRestAuthenticationEntryPoint)

                .and()
                .headers().frameOptions().disable()

                .and().cors()

                .and()
                .csrf().disable();

测试:

@Test
    void test() {
        
        given()
            .contentType(TEXT)
            .auth().basic("myuser","password").
        when()
            .get("/api/ping").
        then()
            .statusCode(200)
            .body(is("Authentication successful for user: myuser"));
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)