【问题标题】:Why my test passes without a bearer token为什么我的测试在没有不记名令牌的情况下通过
【发布时间】:2022-01-18 19:50:45
【问题描述】:

我有一个简单的 Spring 应用程序。但我不明白为什么不需要不记名令牌就可以通过测试。

这里是控制器:

...
@GetMapping
@PreAuthorize("hasAuthority('app-user')")
public ResponseEntity<List<FooDTO>> findAll(){
    return ResponseEntity.ok(fooService.findAll());
}

安全配置:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@PropertySource("classpath:application-${env}.yml")
static class OAuth2SecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2ResourceServer()
                .jwt();
        http.cors();
        http.csrf().disable();
    }
}

为了设置我正在使用的测试的安全配置:

@TestConfiguration
@Import({OAuth2SecurityConfigurerAdapter.class})
public class DefaultTestConfiguration {
}

所以我的测试类看起来像这样:

@AutoConfigureMockMvc
@ContextConfiguration(classes = {FooController.class})
@WebMvcTest
@ActiveProfiles("test")
@Import(DefaultTestConfiguration.class)
public class FooIntegrationTest {
    
    @Test
    @WithMockUser(authorities = "app-user")
    public void findAllShouldReturnAList() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/foos")
                        .accept(MediaType.APPLICATION_JSON))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isOk())
                .andReturn();
        assertThat(result.getResponse()).isNotNull();
    }
}

如果我将测试中的权限更改为“foo-user”之类的内容,则响应变为 403,正如预期的那样,因此我认为正在应用安全配置。

如果我使用 Postman 测试应用程序,则需要不记名令牌来运行请求,但为什么在测试中不需要它?

【问题讨论】:

    标签: java spring testing spring-security mocking


    【解决方案1】:

    @WithMockUser 注解不进行身份验证。 (请注意,您甚至没有提供用户名。) 它使用用户名/密码名称和密码创建一个新的默认用户,并且该用户已经使用 UsernamePasswordAuthenticationToken 进行了身份验证。 并且您在 @WithMockUser(authorities = "app-user") 注释中将此默认用户/密码用户的权限提供为“app-user”。 https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/test/context/support/WithMockUser.html

    因此,您运行测试的用户具有身份验证和授权。

    您的安全配置未被应用。 同样,@WithMockUser 使用 SecurityContextHolder.createEmptyContext() 使用安全默认值创建新的空安全上下文。 https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/test/context/support/WithMockUser.html

    当您使用 Postman 时,当然不会发生任何事情,您的真实用户必须使用普通的不记名令牌进行身份验证。

    【讨论】:

    猜你喜欢
    • 2017-03-03
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多