我正在使用@WebMvcTest测试我的AccountContoller。 GET和Update请求工作正常,但DELETE抛出403状态。
所有请求都使用@AutenticationPrincipal- 我能够使用以下命令测试“获取和更新”请求集 mvc.preform(...)。with(authntication(appAuth))。andExpect(...)但 DELETE请求返回403。
我试图包含@ContextConfiguration(classes = SecurityConfig.class) 但是到了@webMvcTest要求完整配置的地步,但仍然遇到了很多问题,都与我的WebSecurityConfigurerAdapter有关。如果相关,我将发布我的SecurityConfiguration。
测试:
@RunWith(SpringRunner.class)
@WebMvcTest(AccountController.class)
@ContextConfiguration(classes = {SecurityConfiguration.class})
public class AccountControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private AccountService service;
@Test
public void updateAccountName() throws Exception {
String usrNm = "admin";
AppUser appUser = new AppUser(usrNm, "pass");
mvc.perform(get(Path.getAccoutUrl())
.with(authentication(new AppAuth(appUser, true)))
)
.andExpect(status().isOk());
verify(service, times(1))
.findByUsername(usrNm);
}
@Test
public void deleteAccount() throws Exception {
String usrNm = "admin";
AppUser appUser = new AppUser(usrNm, "pass");
appUser.setAuthority(Authority.ADMIN);
appUser.setState(State.ACTIVE);
mvc.perform(delete(Path.getAccoutUrl())
.with(authentication(new AppAuth(appUser, true)))
)
.andExpect(status().isOk());
verify(service, times(1))
.deleteByUsername(usrNm);
}
@Test
public void getAccountName() throws Exception {
String usrNm = "admin";
AppUser appUser = new AppUser(usrNm, "pass");
mvc.perform(get(Path.USERNAME)
.with(authentication(new AppAuth(appUser, true))))
.andExpect(status().isOk())
.andExpect(content().string(usrNm));
}
}
控制器:
@RestController(Path.ACCOUNT)
public class AccountController {
@Autowired
private AccountService service;
@GetMapping(Path.ACCOUNT)
public Account getAccount(@AuthenticationPrincipal AppAuth user) {
return service.findByUsername(user.getName());
}
@PutMapping(Path.ACCOUNT)
public void updateAccountName( @AuthenticationPrincipal AppAuth user,
@RequestBody String newName) {
Account account = service.findByUsername(user.getName());
account.setUsername(newName);
service.save(account);
}
@DeleteMapping(Path.ACCOUNT)
public void deleteAccount(@AuthenticationPrincipal AppAuth user) {
service.deleteByUsername(user.getName());
}
@RequestMapping(method = RequestMethod.GET, value = Path.USERNAME)
public String getAccountName(@AuthenticationPrincipal AppAuth user) {
return user.getName();
}
@RequestMapping(method = RequestMethod.GET, value = Path.LASTCHANGE)
public Date getLastChange(@AuthenticationPrincipal AppAuth user) {
return service.findByUsername(user.getName()).getLastChange();
}
}
如何避免403? (最好不使用WebSecurityConfigurerAdapter)