Я покрыл контроллеры правами, таким образом:
@RestController
@RequestMapping("/api/role")
@PreAuthorize("hasAnyAuthority('ALL')")
public class RoleController {
На методах преавторизации нет. При запуске приложения всё отлично работает. Я скопировал в тестовый пакет SecurityConfig:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public SecurityConfig() {
}
@Configuration
protected static class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("123").authorities("ALL");
}
}
}
Тест:
@Test
@WithMockUser(username = "admin", authorities = {"ALL"})
public void save() throws Exception {
result = mockMvc.perform(post(URL)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(asJson(roleDto)))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").exists())
.andReturn();
assertEquals(MediaType.APPLICATION_JSON_UTF8_VALUE, result.getResponse().getContentType());
}
Пишет:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /api/role
Parameters = {}
Headers = {Content-Type=[application/json;charset=UTF-8]}
Body = {"accountId":null,"roleType":null,"authorities":null,"clientAccounts":null,"clientClusters":null,"id":null}
Session Attrs = {}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 401
Error message = null
Headers = {Pragma=[no-cache], WWW-Authenticate=[Bearer realm="oauth2-resource", error="unauthorized", error_description="Full authentication is required to access this resource"], Cache-Control=[no-store], Content-Type=[application/json;charset=UTF-8], X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], X-Frame-Options=[DENY]}
Content type = application/json;charset=UTF-8
Body = {"error":"unauthorized","error_description":"Full authentication is required to access this resource"}
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :401
Подскажите, что я делаю не так?
Продвижение своими сайтами как стратегия роста и независимости