環境內: 我有由多個基礎設施服務和資源服務(包含業務邏輯)彈簧啓動基於微服務架構的應用程序。授權和身份驗證由管理用戶實體併爲客戶端創建JWT令牌的oAuth2服務處理。使用@WithMockUser(與@SpringBootTest)OAuth2用戶資源服務器應用
爲了測試其整體的單一微服務的應用程序,我試圖用TestNG的,spring.boot.test,org.springframework.security.test建立測試...
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, properties = {"spring.cloud.discovery.enabled=false", "spring.cloud.config.enabled=false", "spring.profiles.active=test"})
@AutoConfigureMockMvc
@Test
public class ArtistControllerTest extends AbstractTestNGSpringContextTests {
@Autowired
private MockMvc mvc;
@BeforeClass
@Transactional
public void setUp() {
// nothing to do
}
@AfterClass
@Transactional
public void tearDown() {
// nothing to do here
}
@Test
@WithMockUser(authorities = {"READ", "WRITE"})
public void getAllTest() throws Exception {
// EXPECT HTTP STATUS 200
// BUT GET 401
this.mvc.perform(get("/")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
}
}
其中安全(資源服務器)配置如下
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
// get the configured token store
@Autowired
TokenStore tokenStore;
// get the configured token converter
@Autowired
JwtAccessTokenConverter tokenConverter;
/**
* !!! configuration of springs http security !!!
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").authenticated();
}
/**
* configuration of springs resource server security
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
// set the configured tokenStore to this resourceServer
resources.resourceId("artist").tokenStore(tokenStore);
}
}
以及基於以下方法的安全檢查註釋IDE控制器類
@PreAuthorize("hasAuthority('READ')")
@RequestMapping(value = "/", method = RequestMethod.GET)
public List<Foo> getAll(Principal user) {
List<Foo> foos = fooRepository.findAll();
return foos;
}
我認爲這會工作,但運行測試時,我只能得到一個斷言錯誤
java.lang.AssertionError: Status
Expected :200
Actual :401
問題: 有一些完全明顯,我在做什麼錯誤?或者@WithMockUser不會在oAuth2環境中使用@SpringBootTest和@AutoConfigureMockMvc?如果是這種情況......作爲像這樣的(集成)測試的一部分,測試基於路由和方法的安全配置的最佳方法是什麼?
附錄: 我也嘗試了不同的方法,如類似下面的...但它導致了同樣的結果:(
this.mvc.perform(get("/")
.with(user("admin").roles("READ","WRITE").authorities(() -> "READ",() -> "WRITE"))
.accept(MediaType.APPLICATION_JSON))
看到:
spring security testing
spring boot 1.4 testing
將此類添加到我的(maven項目)src/test/java對Spring Boot 1.5.4和1.5.9有幫助。我現在可以按照我的預期使用@WithMockUser。 – DaShaun
將此類添加到我的項目允許我繞過安全性,但它似乎不像用戶重要。無論我給測試用戶的範圍如何,它總是通過安全。這是意圖嗎? – Rig