title: Spring OAuth2 "Full authentication is required to access this resource"
body: <p>I'm trying to use Spring OAuth2 for my rest app. 
  But looks like I made a mistake and I can find where I did it. 
  The flow should be:
  1. get token from /oauth/token with username and password
  2. make request to /security with provided token</p>
  
  <p>MethodSecurityConfig:</p>
  
  <pre><code>@Configuration
  @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
  public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
  
      @Autowired
      private SecurityConfiguration securityConfig;
  
      @Override
      protected MethodSecurityExpressionHandler createExpressionHandler() {
          return new OAuth2MethodSecurityExpressionHandler();
      }
  }
  </code></pre>
  
  <p>OAuth2ServerConfig:</p>
  
  <pre><code>@Configuration
  public class OAuth2ServerConfig {
  
      private static final String RESOURCE_ID = "nessnity";
  
      @Configuration
      @Order(10)
      protected static class UiResourceConfiguration extends WebSecurityConfigurerAdapter {
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              http
                      .requestMatchers().antMatchers("/security")
                      .and()
                      .authorizeRequests()
                      .antMatchers("/security").access("hasRole('USER')");
          }
      }
  
      @Configuration
      @EnableResourceServer
      protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
  
          @Override
          public void configure(ResourceServerSecurityConfigurer resources) {
              resources.resourceId(RESOURCE_ID);
          }
  
          @Override
          public void configure(HttpSecurity http) throws Exception {
              http
                      .requestMatchers().antMatchers("/security/")
                      .and()
                      .authorizeRequests()
                      .antMatchers("/security").access("#oauth2.hasScope('read')");
        }
  
      }
  
      @Configuration
      @EnableAuthorizationServer
      protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
  
          @Autowired
          private TokenStore tokenStore;
  
          @Autowired
          private UserApprovalHandler userApprovalHandler;
  
          @Autowired
          private AuthenticationManager authenticationManager;
  
          @Override
          public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
              clients.inMemory()
                      .withClient("my-client")
                      .resourceIds(RESOURCE_ID)
                      .authorizedGrantTypes("client_credentials")
                      .authorities("ROLE_CLIENT")
                      .scopes("read")
                      .secret("password")
                      .accessTokenValiditySeconds(60);
          }
  
          @Bean
          public TokenStore tokenStore() {
              return new InMemoryTokenStore();
          }
  
          @Override
          public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
              endpoints
                      .tokenStore(tokenStore)
                      .userApprovalHandler(userApprovalHandler)
                      .authenticationManager(authenticationManager);
          }
  
          @Override
          public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
              oauthServer.realm("sparklr2/client");
          }
  
      }
  
      protected static class Stuff {
  
          @Autowired
          private ClientDetailsService clientDetailsService;
  
          @Autowired
          private TokenStore tokenStore;
  
          @Bean
          public ApprovalStore approvalStore() throws Exception {
              TokenApprovalStore store = new TokenApprovalStore();
              store.setTokenStore(tokenStore);
              return store;
          }
  
          @Bean
          @Lazy
          @Scope(proxyMode=ScopedProxyMode.TARGET_CLASS)
          public SparklrUserApprovalHandler userApprovalHandler() throws Exception {
              SparklrUserApprovalHandler handler = new SparklrUserApprovalHandler();
              handler.setApprovalStore(approvalStore());
              handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
              handler.setClientDetailsService(clientDetailsService);
              handler.setUseApprovalStore(true);
              return handler;
          }
      }
  
  }
  </code></pre>
  
  <p>SecurityConfiguration:</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.inMemoryAuthentication()
                  .withUser("root")
                  .password("password")
                  .roles("USER");
      }
  
      @Override
      public void configure(WebSecurity web) throws Exception {
          web.ignoring().antMatchers("/oauth/uncache_approvals", "/oauth/cache_approvals");
      }
  
      @Override
      @Bean
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
                  .authorizeRequests()
                  .anyRequest().hasRole("USER");
      }
  }
  </code></pre>
  
  <p>Problem: when I tried to get token </p>
  
  <pre><code>curl --user root:password --data "grant_type=client_credentials" http://localhost:8080/oauth/token
  </code></pre>
  
  <p>I got message:</p>
  
  <blockquote>
    <p>{"error":"invalid_client","error_description":"Bad client
    credentials"}</p>
  </blockquote>
  
  <p>The second question is how to pass username/password in the url params like /oauth/token?username=root&amp;password=password ?</p>
  
  <p>Thanks.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I decided to start from scratch and use xml configuration. </p>
  
  <p>The following configuration works perfect:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
         xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
  
          http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"&gt;
  
  
      &lt;http pattern="/oauth/token" create-session="stateless"
            authentication-manager-ref="authenticationManager"
            xmlns="http://www.springframework.org/schema/security"&gt;
          &lt;intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY"/&gt;
          &lt;anonymous enabled="false"/&gt;
          &lt;http-basic entry-point-ref="clientAuthenticationEntryPoint"/&gt;
          &lt;custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER"/&gt;
          &lt;access-denied-handler ref="oauthAccessDeniedHandler"/&gt;
      &lt;/http&gt;
  
      &lt;bean id="clientCredentialsTokenEndpointFilter"
            class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"&gt;
          &lt;property name="authenticationManager" ref="authenticationManager"/&gt;
      &lt;/bean&gt;
  
      &lt;authentication-manager alias="authenticationManager"
                              xmlns="http://www.springframework.org/schema/security"&gt;
          &lt;authentication-provider user-service-ref="clientDetailsUserService"/&gt;
      &lt;/authentication-manager&gt;
  
      &lt;bean id="clientDetailsUserService"
            class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService"&gt;
          &lt;constructor-arg ref="clientDetails"/&gt;
      &lt;/bean&gt;
  
      &lt;bean id="clientDetails" class="com.nessnity.api.security.OAuthClienDetailsService"&gt;
          &lt;property name="id" value="testuser"/&gt;
          &lt;property name="secretKey" value="secret" /&gt;
      &lt;/bean&gt;
  
      &lt;bean id="clientAuthenticationEntryPoint"
            class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"&gt;
          &lt;property name="realmName" value="springsec/client"/&gt;
          &lt;property name="typeName" value="Basic"/&gt;
      &lt;/bean&gt;
  
      &lt;bean id="oauthAccessDeniedHandler"
            class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"/&gt;
  
      &lt;oauth:authorization-server
              client-details-service-ref="clientDetails"
              token-services-ref="tokenServices"&gt;
          &lt;oauth:authorization-code/&gt;
          &lt;oauth:implicit/&gt;
          &lt;oauth:refresh-token/&gt;
          &lt;oauth:client-credentials/&gt;
          &lt;oauth:password authentication-manager-ref="userAuthenticationManager"/&gt;
      &lt;/oauth:authorization-server&gt;
  
      &lt;authentication-manager id="userAuthenticationManager"
                              xmlns="http://www.springframework.org/schema/security"&gt;
          &lt;authentication-provider ref="customUserAuthenticationProvider"&gt;
          &lt;/authentication-provider&gt;
      &lt;/authentication-manager&gt;
  
      &lt;bean id="customUserAuthenticationProvider"
            class="com.nessnity.api.security.OAuthUserAuthenticationProvider"&gt;
      &lt;/bean&gt;
  
      &lt;bean id="tokenServices"
            class="org.springframework.security.oauth2.provider.token.DefaultTokenServices"&gt;
          &lt;property name="tokenStore" ref="tokenStore"/&gt;
          &lt;property name="supportRefreshToken" value="true"/&gt;
          &lt;property name="accessTokenValiditySeconds" value="900000000"/&gt;
          &lt;property name="clientDetailsService" ref="clientDetails"/&gt;
      &lt;/bean&gt;
  
      &lt;bean id="tokenStore"
            class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore"/&gt;
  
      &lt;bean id="oauthAuthenticationEntryPoint"
            class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"&gt;
      &lt;/bean&gt;
  
      &lt;http pattern="/resources/**" create-session="never"
            entry-point-ref="oauthAuthenticationEntryPoint"
            xmlns="http://www.springframework.org/schema/security"&gt;
          &lt;anonymous enabled="false"/&gt;
          &lt;intercept-url pattern="/resources/**" method="GET"/&gt;
          &lt;custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER"/&gt;
          &lt;access-denied-handler ref="oauthAccessDeniedHandler"/&gt;
      &lt;/http&gt;
  
      &lt;oauth:resource-server id="resourceServerFilter"
                             resource-id="springsec" token-services-ref="tokenServices"/&gt;
  
  &lt;/beans&gt;
  </code></pre>