我有一個簡單的 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 測驗應用程式,則需要承載令牌來運行請求,但為什么在測驗中不需要它?
uj5u.com熱心網友回復:
@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 時,當然不會發生所有這些情況,并且您的真實用戶必須使用普通的不記名令牌進行身份驗證。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/415653.html
標籤:
