本文介紹了Spring安全-OAuth2資源服務(wù)器測(cè)試的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
使用@WebMvcTest和POST HTTP方法測(cè)試OAuth2資源服務(wù)器時(shí)遇到一些問(wèn)題。
當(dāng)我不發(fā)送CSRF令牌時(shí),我總是收到403狀態(tài)代碼,即使在我使用承載令牌時(shí)不需要該令牌。
這是我要測(cè)試的POST方法。
@PostMapping("/message")
public String createMessage(@RequestBody String message) {
return String.format("Message was created. Content: %s", message);
}
這是我的安全配置:
http.authorizeRequests(authorizeRequests -> authorizeRequests
.antMatchers("/message/**")
.hasAuthority("SCOPE_message:read")
.anyRequest().authenticated()
).oauth2ResourceServer(oauth2ResourceServer ->
oauth2ResourceServer
.jwt(withDefaults())
);
我正在遵循spring-security的樣本中提供的測(cè)試。
以下測(cè)試應(yīng)該通過(guò),但失敗了,因?yàn)檎?qǐng)求中沒有發(fā)送CSRF令牌。
mockMvc.perform(post("/message").content("Hello message")
.with(jwt(jwt -> jwt.claim("scope", "message:read")))
.andExpect(status().isOk())
.andExpect(content().string(is("Message was created. Content: Hello message")));
當(dāng)我向請(qǐng)求添加CSRF令牌時(shí),測(cè)試通過(guò):
mockMvc.perform(post("/message").content("Hello message")
.with(jwt(jwt -> jwt.claim("scope", "message:read")))
.with(csrf()))
.andExpect(status().isOk())
.andExpect(content().string(is("Message was created. Content: Hello message")));
當(dāng)我運(yùn)行應(yīng)用程序時(shí),不需要在POST請(qǐng)求中發(fā)送CSRF令牌。
我已經(jīng)派生了Spring Security GitHub存儲(chǔ)庫(kù),具有此失敗測(cè)試的項(xiàng)目可以在link上找到。
有沒有辦法配置我的測(cè)試,使我不需要在POST請(qǐng)求中發(fā)送CSRF令牌?
推薦答案
為了使CSRF篩選器檢測(cè)到您正在使用JWT令牌,您需要將JWT令牌作為Authorization頭或請(qǐng)求參數(shù)包括在請(qǐng)求中。
您提到的測(cè)試有一個(gè)模擬JwtDecoder,這意味著您可以使用任何字符串作為令牌并模擬解碼值。
然后,您的測(cè)試將變?yōu)椋?/p>
Jwt jwt = Jwt.withTokenValue("token")
.header("alg", "none")
.claim("scope", "message:read")
.build();
when(jwtDecoder.decode(anyString())).thenReturn(jwt);
mockMvc.perform(post("/message")
.content("Hello message")
.header("Authorization", "Bearer " + jwt.getTokenValue()))
.andExpect(status().isOk())
.andExpect(content().string(is("Message was created. Content: Hello message")));
如果您沒有模擬JwtDecoder,則需要檢索有效的承載令牌并在Authorization頭中傳遞該令牌。
這篇關(guān)于Spring安全-OAuth2資源服務(wù)器測(cè)試的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,






