[英]Spring Boot Microservice JUnit Test - How to write a test method with adding the option of @PreAuthorize
我只想在訂單controller的方法中添加@PreAuthorize("hasAuthority('ROLE_ADMIN')")
和@PreAuthorize("hasAuthority('ROLE_USER')")
並且我在定義登錄后還修改了controller測試方法就用戶和管理員角色而言,身份驗證服務中的方法。
我在controller的placeOrder方法中添加@PreAuthorize("hasAuthority('ROLE_USER')")
之后,修改了它的測試方法。
下面是controller的訂購方法
@PreAuthorize("hasAuthority('ROLE_USER')")
@PostMapping("/placeorder")
public ResponseEntity<Long> placeOrder(@RequestBody OrderRequest orderRequest) {
log.info("OrderController | placeOrder is called");
log.info("OrderController | placeOrder | orderRequest: {}", orderRequest.toString());
long orderId = orderService.placeOrder(orderRequest);
log.info("Order Id: {}", orderId);
return new ResponseEntity<>(orderId, HttpStatus.OK);
}
這是訂單服務中ordercontrollertest中的示例測試方法。
@Test
@DisplayName("Place Order -- Success Scenario")
void test_When_placeOrder_DoPayment_Success() throws Exception {
OrderRequest orderRequest = getMockOrderRequest();
String jwt = getJWTTokenForRoleUser();
MvcResult mvcResult
= mockMvc.perform(MockMvcRequestBuilders.post("/order/placeorder")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.header("Authorization", "Bearer " + jwt)
.content(objectMapper.writeValueAsString(orderRequest)))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
String orderId = mvcResult.getResponse().getContentAsString();
Optional<Order> order = orderRepository.findById(Long.valueOf(orderId));
assertTrue(order.isPresent());
Order o = order.get();
assertEquals(Long.parseLong(orderId), o.getId());
assertEquals("PLACED", o.getOrderStatus());
assertEquals(orderRequest.getTotalAmount(), o.getAmount());
assertEquals(orderRequest.getQuantity(), o.getQuantity());
}
下面是關於它的訂單服務的依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
如何在此測試方法中定義 ROLE。 我嘗試使用@WithMockUser(roles="USER")
和@WithMockUser(roles="ADMIN")
但它對我沒有幫助。 (我收到 403 Forbidden 錯誤。)
編輯(我也嘗試在服務中使用 WebSecurityConfig,但它沒有幫助我解決問題。這就是我從服務中刪除它的原因。)
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {
@Bean
public SecurityFilterChain securityWebFilterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(
authorizeRequest -> authorizeRequest
.anyRequest()
.authenticated());
return http.build();
}
}
這是示例鏈接:鏈接
這是測試 controller: 鏈接
要運行該應用程序,1)運行服務注冊(Eureka 服務器)
2)運行配置服務器
3 ) 通過下面顯示的這些命令運行 zipkin 和 redis docker docker run -d -p 9411:9411 openzipkin/zipkin docker run -d --name redis -p 63788:62376 63788:62376
4)運行api網關
5)運行其他服務
我可能看起來很粗魯,但我已經厭倦了給你解決問題的方法(這已經是第三次了,如果你第一次嘗試的話,我們都會節省很多時間)
它會教你如何(你顯然不知道如何正確地做):
@WithMockUser
使用不適用於 OAuth2 資源服務器的UsernamePasswordAuthenticationToken
填充測試安全上下文。
只需遵循前 3 個教程(真正的:編寫代碼並運行測試),然后參考與您的特定用例最匹配的示例。 它應該花費你不到一個小時。
使用 MockMvc 時,停止嘗試構建 JWT 以將其設置為請求 header。 使用來自spring-security-test
org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt
或來自spring-addons-oauth2-test
@WithMockJwtAuth
。
添加此配置以測試 class:
@EnableGlobalMethodSecurity(prePostEnabled = true)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.