我正在尝试对控制器进行单元测试,但我无法模拟JWT身份验证——我已经尝试了多种方法来模拟它,但都不起作用。JWT令牌由外部SSO生成。不确定它是否相关,但应用程序使用Activiti库。这是我当前的代码:
控制器:
@AllArgsConstructor
@Slf4j
@RestController
@RequestMapping("/api/my-controller")
public class MyControllerController {
...
@ResponseStatus(value = HttpStatus.CREATED)
@PreAuthorize("hasAnyAuthority('admin', 'student','graduate')")
@PostMapping(value = "", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<ProcessStartedDTO> repeatingRequest(@CurrentUser UserDetails userDetails,
@RequestParam(value = "taskId", required = false) String taskId,
MyControllerRequest myControllerRequest) {
...
}
}
测试:
@WebMvcTest(MyControllerController.class)
@ActiveProfiles("test")
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@ContextConfiguration
public class ScholarshipDisabledControllerTest {
@MockBean
private SomeRequiredBean someRequiredBean;
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(roles = {"student"})
public void testCreatesNewProcessWhenNoTaskIdProvided() throws Exception {
Jwt tjwt = Jwt.withTokenValue("token")
.header("alg", "none")
.claim("sub", "user")
.claim("scope", "reuired-permision-backend-api.write")
.build();
ResultActions x = mockMvc.perform(
multipart("/api/my-controller")
.param("test", "test")
//.header("Authorization", "Bearer ")
.with(jwt().jwt(tjwt).authorities(new SimpleGrantedAuthority("student"), new SimpleGrantedAuthority("Student.Read"))))
.andDo(MockMvcResultHandlers.print());
}
}
结果:
MockHttpServletResponse:
Status = 401
Error message = null
Headers = [Cache-Control:"no-store", Pragma:"no-cache", WWW-Authenticate:"Bearer realm="oauth2-resource", error="unauthorized", error_description="Full authentication is required to access this resource"", Content-Type:"application/xml;charset=UTF-8", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", X-Frame-Options:"DENY"]
Content type = application/xml;charset=UTF-8
Body = <UnauthorizedException><error>unauthorized</error><error_description>Full authentication is required to access this resource</error_description></UnauthorizedException>
Forwarded URL = null
Redirected URL = null
Cookies = []