Spring Security: не проходит тестирование

178
09 января 2020, 01:30

Я покрыл контроллеры правами, таким образом:

@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

Подскажите, что я делаю не так?

READ ALSO
Присваивание и логические операторы java

Присваивание и логические операторы java

Во время написания одной программы возник интересный вопрос: "Можно ли как-то присвоить нескольким переменным одинаковое значение с помощью...

171
Android. Где хранить изменяемые строковые ресурсы?

Android. Где хранить изменяемые строковые ресурсы?

Есть готовое приложение учета зарплатыВ нем есть 5 категорий - зарплата, аванс, больничные, отпускные, иное

173
Cannot infer arguments - Java

Cannot infer arguments - Java

Вот создаю ArrayList для массивов, чтобы потом удалить в них значения, но у третьей строчки выскакивает ошибка у <> - Cannot infer argumentsЧто за непонятная...

185