Тест интеграции Spring Boot для контроллера сервера ресурсов с защитой oauth - PullRequest
2 голосов
/ 14 февраля 2020

У нас есть следующий защищенный контроллер:

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {

    @GetMapping
    @PreAuthorize("#oauth2.hasScope('edit') OR hasRole('ADMIN')")
    public String getForAdmin(@AuthenticationPrincipal Principal principal) {
        return employeeService.getForAdmin(principal)
    }
}

Безопасность работает, как и ожидалось. Я получил токен доступа jwt с сервера авторизации, и с запросом с заголовком «Авторизационный носитель xxxx.yyyy.zzzz» я могу вызвать этот контроллер.

Сервер ресурсов настроил довольно базовую c аутентификацию

@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests(httpSecurity -> httpSecurity
            .anyRequest().authenticated()
        );
}

Далее я попытался написать интеграционный тест для контроллера сотрудника, чтобы убедиться, что система безопасности работает нормально:

// configure mock mvc with security
    mockMvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity())
            .build();

    // call secured endpoint and with specific authentication
    mockMvc.perform(get("/api/employee")
            .with(jwt())
            .accept(MediaType.APPLICATION_JSON))
            .andDo(print())
            .andExpect(status().isOk());

Я обнаружил, что существует JwtRequestPostProcessor, как я назначил в образце, но понятия не имею как сказать это высмеянная jwt сфера и роль. Я пробовал хотя бы следующую роль: jwt().authorities(new SimpleGrantedAuthority("ROLE_ADMIN")), но она не работала, и я всегда получаю ошибку 401.

РЕДАКТИРОВАТЬ: это журналы, которые я обнаружил после включения уровня отладки для безопасности:

2020-02-14 11:42:18.167 DEBUG 2094 --- [           main] o.s.security.web.FilterChainProxy        : /api/employee at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
2020-02-14 11:42:18.167 DEBUG 2094 --- [           main] o.s.s.o.p.a.BearerTokenExtractor         : Token not found in headers. Trying request parameters.
2020-02-14 11:42:18.167 DEBUG 2094 --- [           main] o.s.s.o.p.a.BearerTokenExtractor         : Token not found in request parameters.  Not an OAuth2 request.
2020-02-14 11:42:18.167 DEBUG 2094 --- [           main] p.a.OAuth2AuthenticationProcessingFilter : Clearing security context.
2020-02-14 11:42:18.167 DEBUG 2094 --- [           main] p.a.OAuth2AuthenticationProcessingFilter : No token in request, will continue chain.
2020-02-14 11:42:18.167 DEBUG 2094 --- [           main] o.s.security.web.FilterChainProxy        : /api/employee at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2020-02-14 11:42:18.167 DEBUG 2094 --- [           main] o.s.security.web.FilterChainProxy        : /api/employee at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2020-02-14 11:42:18.168 DEBUG 2094 --- [           main] o.s.security.web.FilterChainProxy        : /api/employee at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2020-02-14 11:42:18.168 DEBUG 2094 --- [           main] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@94907bf0: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2020-02-14 11:42:18.168 DEBUG 2094 --- [           main] o.s.security.web.FilterChainProxy        : /api/employee at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2020-02-14 11:42:18.169 DEBUG 2094 --- [           main] o.s.security.web.FilterChainProxy        : /api/employee at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2020-02-14 11:42:18.169 DEBUG 2094 --- [           main] o.s.security.web.FilterChainProxy        : /api/employee at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2020-02-14 11:42:18.169 DEBUG 2094 --- [           main] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /api/employee; Attributes: [#oauth2.throwOnError(authenticated)]
2020-02-14 11:42:18.169 DEBUG 2094 --- [           main] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@94907bf0: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2020-02-14 11:42:18.173 DEBUG 2094 --- [           main] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@2f6e92ca, returned: -1
2020-02-14 11:42:18.176 DEBUG 2094 --- [           main] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied

зависимости:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        <version>2.2.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        <version>2.2.2.RELEASE</version>
    </dependency>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...