title: Got access_denied as error status while accessing protected resource using authenticated token in Spring Security OAuth 2.0 using Jdbc datastore
body: <p>The token can be generated but while the same token (which is not expired) is used to access protected resource then got <strong><em>access_denied</em></strong> as error message.</p>
  
  <hr/>
  
  <blockquote>
    <p>Below is the <strong>spring-security.xml</strong> file.</p>
  </blockquote>
  
  <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"  
  xmlns:sec="http://www.springframework.org/schema/security"     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.xsd"&gt;
  &lt;http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager"      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;!-- include this only if you need to authenticate clients via request parameters --&gt;  
  &lt;custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER"/&gt;  
  &lt;access-denied-handler ref="oauthAccessDeniedHandler"/&gt;      &lt;/http&gt;      &lt;!-- The OAuth2 protected resources are separated out into their own block so we can deal with authorization and error handling  
  separately. This isn't mandatory, but it makes it easier to control the behaviour. --&gt;      &lt;http pattern="/test/*" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint"
  access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security"&gt;  
  &lt;anonymous enabled="false"/&gt;  
  &lt;intercept-url pattern="/test/**" access="ROLE_USER"/&gt;  
  &lt;custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER"/&gt;  
  &lt;access-denied-handler ref="oauthAccessDeniedHandler"/&gt;
  &lt;/http&gt;&lt;bean id="oauthAuthenticationEntryPoint"  
  class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"&gt;&lt;property name="realmName" value="test"/&gt;&lt;/bean&gt;      &lt;bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"&gt; &lt;property name="realmName" value="test/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;bean id="clientCredentialsTokenEndpointFilter"  
        class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"&gt;
  
       &lt;property name="authenticationManager" ref="clientAuthenticationManager"/&gt;      &lt;/bean&gt;      &lt;bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"  
        xmlns="http://www.springframework.org/schema/beans"&gt;  
       &lt;constructor-arg&gt;  
         &lt;list&gt;  
           &lt;bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter"/&gt;
  
           &lt;bean class="org.springframework.security.access.vote.RoleVoter"/&gt;  
           &lt;bean class="org.springframework.security.access.vote.AuthenticatedVoter"/&gt; 
  
         &lt;/list&gt;  
       &lt;/constructor-arg&gt;      &lt;/bean&gt;      &lt;authentication-manager id="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security"&gt;  
       &lt;authentication-provider user-service-ref="clientDetailsUserService"/&gt;      &lt;/authentication-manager&gt;      &lt;bean id="passwordEncoder"  
        class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"&gt;
  
       &lt;constructor-arg name="strength" value="11"/&gt;      &lt;/bean&gt;      &lt;authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security"&gt;  
       &lt;authentication-provider user-service-ref="userService"&gt;  
         &lt;password-encoder ref="passwordEncoder"/&gt;  
       &lt;/authentication-provider&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;!-- Used for the persistenceof tokens (currently an in memory implementation) --&gt;      &lt;bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore"&gt;
  
       &lt;constructor-arg ref="dataSource"/&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="clientDetailsService" ref="clientDetails"/&gt;      &lt;/bean&gt;      &lt;bean id="oAuth2RequestFactory"  
        class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory"&gt;
  
       &lt;constructor-arg ref="clientDetails"/&gt;      &lt;/bean&gt;      &lt;bean id="userApprovalHandler"  
        class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler"&gt;
  
       &lt;property name="tokenStore" ref="tokenStore"/&gt;  
       &lt;property name="requestFactory" ref="oAuth2RequestFactory"/&gt;      &lt;/bean&gt;      &lt;!-- authorization-server aka AuthorizationServerTokenServices is an interface that defines everything necessary for token management --&gt;      &lt;oauth:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenServices"  
                   user-approval-handler-ref="userApprovalHandler"&gt;  
       &lt;oauth:authorization-code/&gt;  
       &lt;oauth:implicit/&gt;  
       &lt;oauth:refresh-token/&gt;  
       &lt;oauth:client-credentials/&gt;  
       &lt;oauth:password/&gt;      &lt;/oauth:authorization-server&gt;      &lt;oauth:resource-server id="resourceServerFilter" resource-id="test" token-services-ref="tokenServices"/&gt;      &lt;bean id="clientDetails"  
        class="org.ateam.common.service.ClientService"&gt;      &lt;/bean&gt;      &lt;sec:global-method-security pre-post-annotations="enabled" proxy-target-class="true"&gt;  
       &lt;!--you could also wire in the expression handler up at the layer of the http filters. See https://jira.springsource.org/browse/SEC-1452
  --&gt;  
       &lt;sec:expression-handler ref="oauthExpressionHandler"/&gt;      &lt;/sec:global-method-security&gt;      &lt;oauth:expression-handler id="oauthExpressionHandler"/&gt;      &lt;oauth:web-expression-handler id="oauthWebExpressionHandler"/&gt;    &lt;/beans&gt;
  </code></pre>
  
  <hr/>
  
  <blockquote>
    <p>Below is the <strong>db-configuration.xml</strong></p>
  </blockquote>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
          xmlns:tx="http://www.springframework.org/schema/tx"
          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"&gt;
  
      &lt;bean
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;
          &lt;property name="location"&gt;
              &lt;value&gt;classpath:database.properties&lt;/value&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
  
      &lt;bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"&gt;
          &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt;
          &lt;property name="url" value="${jdbc.url}" /&gt;
          &lt;property name="username" value="${jdbc.username}" /&gt;
          &lt;property name="password" value="${jdbc.password}" /&gt;
      &lt;/bean&gt;
  
      &lt;bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;
          &lt;property name="dataSource" ref="dataSource" /&gt;
          &lt;property name="hibernateProperties"&gt;
              &lt;props&gt;
                  &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt;
                  &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt;
                  &lt;!-- &lt;prop key="hibernate.hbm2ddl.auto"&gt;update&lt;/prop&gt; --&gt;
                  &lt;prop key="hibernate.hbm2ddl.auto"&gt;create&lt;/prop&gt;
                  &lt;prop key="hibernate.hbm2ddl.import_files_sql_extractor"&gt;org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor
                  &lt;/prop&gt;
              &lt;/props&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
  
      &lt;bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt;
          &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
      &lt;/bean&gt;
  
      &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt;
  
      &lt;bean id="transactionInterceptor"
          class="org.springframework.transaction.interceptor.TransactionInterceptor"&gt;
          &lt;property name="transactionManager" ref="transactionManager" /&gt;
          &lt;property name="transactionAttributeSource"&gt;
              &lt;value&gt;
              &lt;/value&gt;
          &lt;/property&gt;
      &lt;/bean&gt;
  
      &lt;bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"&gt;
          &lt;property name="dataSource" ref="dataSource"/&gt;
      &lt;/bean&gt;
  
  &lt;/beans&gt;
  </code></pre>
  
  <hr/>
  
  <blockquote>
    <p>Below is the <strong>ClientService.class</strong> file.</p>
  </blockquote>
  
  <pre><code>@Component
  public class ClientService implements ClientDetailsService {
  
      @Autowired
      private OauthRepository oauthRepository;
  
      @Override
      public ClientDetails loadClientByClientId(String s) throws ClientRegistrationException {
          BaseClientDetails clientDetails = oauthRepository.getByClientId(s);
          return clientDetails;
      }
  }
  </code></pre>
  
  <hr/>
  
  <blockquote>
    <p>Below is the <strong>UserService.class</strong> file.</p>
  </blockquote>
  
  <pre><code>@Component
  public class UserService implements UserDetailsService {
  
      @Autowired
      private OauthRepository oauthRepository;
  
      @Override
      public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
          User user = oauthRepository.getByUsername(s);
          return user;
      }
  }
  </code></pre>
  
  <hr/>
  
  <blockquote>
    <p>Below is the <strong>OauthRepository.class</strong> file.</p>
  </blockquote>
  
  <pre><code>@Repository
  public class OauthRepository {
  
      @Autowired
      private JdbcTemplate jdbcTemplate;
  
      private final static String FETCH_BY_USERNAME = "select username,password from auth_details where username=?";
  
      private final static String FETCH_BY_CLIENT_ID = "select client_id, client_secret, resource_ids, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove from oauth_client_details where client_id = ?";
  
      public User getByUsername(String username) {
          return jdbcTemplate.queryForObject(FETCH_BY_USERNAME, new Object[]{username}, new RowMapper&lt;User&gt;() {
              @Override
              public User mapRow(ResultSet resultSet, int i) throws SQLException {
                  User user = new User(resultSet.getString("username"), resultSet.getString("password"), Collections.&lt;GrantedAuthority&gt;emptyList());
                  return user;
              }
          });
      }
  
      public BaseClientDetails getByClientId(String clientId) {
          return jdbcTemplate.queryForObject(FETCH_BY_CLIENT_ID, new Object[]{clientId}, new RowMapper&lt;BaseClientDetails&gt;() {
              @Override
              public BaseClientDetails mapRow(ResultSet rs, int i) throws SQLException {
                  BaseClientDetails details = new BaseClientDetails(rs.getString(1), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(7), rs.getString(6));
                  details.setClientSecret(rs.getString(2));
                  if (rs.getObject(8) != null) {
                      details.setAccessTokenValiditySeconds(Integer.valueOf(rs.getInt(8)));
                  }
  
                  if (rs.getObject(9) != null) {
                      details.setRefreshTokenValiditySeconds(Integer.valueOf(rs.getInt(9)));
                  }
  
                  String scopes1 = rs.getString(11);
                  if (scopes1 != null) {
                      details.setAutoApproveScopes(StringUtils.commaDelimitedListToSet(scopes1));
                  }
                  return details;
              }
          });
      }
  }
  </code></pre>
  
  <hr/>
  
  <blockquote>
    <p>Get <strong>access token</strong> using user credential.</p>
  </blockquote>
  
  <pre><code>URI : http://localhost:8080/oauth2/oauth/token
  Method : POST
  x-www-form-urlencoded : 
       grant_type : password
       client_id : client-id
       client_secret : 123456
       username : someusername
       password : somepassword
  </code></pre>
  
  <blockquote>
    <p>Response:</p>
  </blockquote>
  
  <pre><code>{
    "access_token": "732a8e9b-4f9b-4dd8-b8e7-1f3e5ff831b4",
    "token_type": "bearer",
    "refresh_token": "6c1bac4f-994c-4037-8a26-650e2cda3w4f",
    "expires_in": 86399,
    "scope": "read trust write"
  }
  </code></pre>
  
  <hr/>
  
  <blockquote>
    <p>Accessing protected resource using above token.</p>
  </blockquote>
  
  <pre><code>URI : http://localhost:8080/oauth2/test/
  Method : GET
  Headers : 
        Authorization : bearer 732a8e9b-4f9b-4dd8-b8e7-1f3e5ff831b4
  </code></pre>
  
  <blockquote>
    <p>Response:</p>
  </blockquote>
  
  <pre><code>{
    "error": "access_denied",
    "error_description": "Access is denied"
  }
  </code></pre>
  
  <p><hr/>
  <strong>Any solution for this problem ?</strong></p>
  
  <p><em>Thank you !</em></p>