OAuth2 com aplicativo REST Spring Boot - não é possível acessar o recurso com token

Quero usar o OAuth2 no meu projeto de inicialização de primavera REST. Usando alguns exemplos, criei a configuração para o OAuth2:

@Configuration
public class OAuth2Configuration {

    private static final String RESOURCE_ID = "restservice";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends
          ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            // @formatter:off
            resources
                    .resourceId(RESOURCE_ID);
            // @formatter:on
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http
                    .anonymous().disable()
                    .authorizeRequests().anyRequest().authenticated();
            // @formatter:on
        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends
             AuthorizationServerConfigurerAdapter {

        private TokenStore tokenStore = new InMemoryTokenStore();

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Autowired
        private UserDetailsServiceImpl userDetailsService;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
          // @formatter:off
          endpoints
                  .tokenStore(this.tokenStore)
                  .authenticationManager(this.authenticationManager)
                  .userDetailsService(userDetailsService);
          // @formatter:on
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // @formatter:off
            clients
                  .inMemory()
                  .withClient("clientapp")
                  .authorizedGrantTypes("password", "refresh_token", "trust")
                  .authorities("USER")
                  .scopes("read", "write")
                  .resourceIds(RESOURCE_ID)
                  .secret("clientsecret")
                  .accessTokenValiditySeconds(1200)
                  .refreshTokenValiditySeconds(3600);
            // @formatter:on
        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(this.tokenStore);
            return tokenServices;
        }
    }
}

Esta é minha classe SecurityConfiguration:

@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http
                .authorizeRequests().antMatchers("/api/register").permitAll()
                .and()
                .authorizeRequests().antMatchers("/api/free").permitAll()
                .and()
                .authorizeRequests().antMatchers("/oauth/token").permitAll()
                .and()
                .authorizeRequests().antMatchers("/api/secured").hasRole("USER")
                .and()
                .authorizeRequests().anyRequest().authenticated();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

Tentei verificar meu aplicativo com 2 solicitações simples:

@RequestMapping(value = "/api/secured", method = RequestMethod.GET)
public String checkSecured(){
    return "Authorization is ok";
}

@RequestMapping(value = "/api/free", method = RequestMethod.GET)
public String checkFree(){
    return "Free from authorization";
}

Primeiramente, verifiquei dois pedidos:

/ api / grátis retornou o código 200 e a sequência "Livre de autorização"

/ api / protegido retornou {"timestamp": 1487451065106, "status": 403, "error": "Proibido", "mensagem": "Acesso negado", "caminho": "/ api / secure"}

E parece que eles funcionam bem.

Então recebi access_token (usando credenciais do banco de dados de meus usuários)

/ oauth / token? grant_type = senha e nome de usuário = emaila & senha = emailo

Resposta:

{"access_token": "3344669f-c66c-4161-9516-d7e2f31a32e8", "token_type": "portador", "refresh_token": "c71c17e4-45ba-458c-9d98-574de33d1859", "expires_in": 1199, "scope" :"ler escrever"}

Em seguida, tentei enviar uma solicitação (com o token que obtive) para o recurso que requer autenticação:

/ api / secure? access_token = 3344669f-c66c-4161-9516-d7e2f31a32e8

Aqui está a resposta:

{"timestamp": 1487451630224, "status": 403, "error": "Proibido", "mensagem": "Acesso negado", "caminho": "/ api / secure"}

Não consigo entender por que o acesso foi negado. Não tenho certeza nas configurações e parece que elas estão incorretas. Também ainda não entendo claramente as relações de métodosconfigurar (http HttpSecurity) na aula que se estendeWebSecurityConfigurerAdapter e em outro que se estendeResourceServerConfigurerAdapter. Obrigado por qualquer ajuda!

questionAnswers(1)

yourAnswerToTheQuestion