【发布时间】:2020-03-20 18:09:29
【问题描述】:
我的SecurityConfiguration配置如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.authorizeRequests()
.antMatchers("/api/auth", "/api/auth/**", "/api/oauth2/**").permitAll()
.anyRequest().authenticated().and()
.oauth2Login()
//
}
我正在测试我的自定义身份验证 POST 端点 /api/auth/login 和 /api/auth/register。该应用程序运行良好,我目前正在为它们追溯编写单元测试。在我的控制器单元测试中,我有以下内容:
@WebMvcTest(AuthenticationController.class)
@ContextConfiguration(classes = {AuthenticationController.class})
class AuthenticationControllerTest {
@Test
void register() throws Exception {
mockMvc.perform(post(BASE_PATH + "/register")
.content(...) // POST body
.with(csrf()))
.andExpect(status().isOk());
}
这会返回 HTTP 401 (Unauthorized) 而不是预期的 HTTP 200。但是如果我将 @WithMockUser(不带任何参数)添加到测试方法中,那么它确实会返回 200。为什么需要模拟用户,因为我不需要在 /api/auth 端点上进行身份验证? 可以肯定的是,我尝试在 SecurityConfiguration 中设置 /api/auth/**,但同样的问题仍然存在。我还没有实现任何与授权相关的东西,所以角色不是问题。
编辑:值得注意的是,我也尝试设置.anyRequest().permitAll(),本质上是说我的所有端点都不需要身份验证,但会出现同样的问题。
EDIT2:更新了测试 sn-p,我使用了以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
【问题讨论】:
-
您能否添加您的整个测试以查看您在测试执行期间如何引导以及引导哪些部分?如果您使用 Spring Boot Starter for Security 或仅 Spring Security,还请添加您的
pom.xml或提供更多信息 -
@rieckpil 我已将您要求的信息添加到我的问题中
标签: java spring spring-boot spring-mvc spring-security