如何将Spring SecurityContext传递给RestAssured

时间:2018-05-10 00:54:08

标签: java spring-boot testing spring-security rest-assured

我尝试使用方法级安全控制器为Spring-Boot应用程序设置RestAssured测试。

例如,我有这个使用方法级安全性的最小控制器


@RestController
public class DummyController {
    @GetMapping("/")
    @PreAuthorize("hasRole('TEST')") // removing this should make the test green
    public String test() {
        return "hello";
    }
}

和允许的安全配置


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll();
    }
}

然后使用RestAssured进行的这个简单测试失败了:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class DummyControllerITest {
    private static final Logger logger = LoggerFactory.getLogger(DummyControllerITest.class);

    @LocalServerPort
    private int port;

    @Test
    @WithMockUser(roles = "TEST")
    public void name() throws Exception {
        RestAssured.given()
                .port(port)
            .when()
                .get("/")
            .then()
                .statusCode(HttpStatus.OK.value());
    }
}

为什么此测试失败,即使模拟用户配置了正确的角色?

我已经调试了这个,似乎正确设置了运行测试的线程中的SecurityContext,而未填充处理RestAssured请求的线程中的SecurityContext。但是......为什么?

0 个答案:

没有答案