title: Spring : Mvc Rest api error=“invalid_grant”, error_description=“Bad credentials” in Spring oauth2 jdbc
body: <p>I would like to implement security for spring rest api using OAth2 and I'm very new to these concepts. I have implemented this concept using InMemoryAuthentication and it works fine, but I'm trying to do with jdbc authentication. After searching so many tutorials on google I have implemented jdbc authentication but it gives error and I don't know how to do it, My code is looks like below.I'm not sure whether my flow is correct or not, please correct me.</p>
  
  <h1>AuthorizationServerConfig class</h1>
  
  <pre><code>@Configuration
  @EnableAuthorizationServer
  public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  
  @Autowired
  private TokenStore tokenStore;
  
  @Autowired
  private UserApprovalHandler userApprovalHandler;
  
  @Autowired
  @Qualifier("authenticationManagerBean")
  private AuthenticationManager authenticationManager;
  
  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws 
  Exception {
      clients.inMemory()
      .withClient("crmClient1")
          .secret("crmSuperSecret")
          .authorizedGrantTypes("password", "refresh_token")
          .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
          .scopes("read", "write", "trust")
          //.accessTokenValiditySeconds(ONE_DAY)
          .accessTokenValiditySeconds(300)
          .refreshTokenValiditySeconds(THIRTY_DAYS);
  }
  
  @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(REALM);
  }
  }
  </code></pre>
  
  <h1>ResourceServerConfig class</h1>
  
  <pre><code>@Configuration
  @EnableResourceServer
  public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  
  @Override
  public void configure(HttpSecurity http) throws Exception {
      //-- define URL patterns to enable OAuth2 security
      http.
      anonymous().disable()
      .requestMatchers().antMatchers("/api/**")
      .and().authorizeRequests()
      .antMatchers("/api/**").access("hasRole('ADMIN') or hasRole('USER')")
      .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
  }
  
  }
  </code></pre>
  
  <h1>SecurityConfig class</h1>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
  @Autowired
  private ClientDetailsService clientDetailsService;
  
  @Autowired
  private DataSource dataSource;
  
  @Autowired
  public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
      System.out.println("data source : " + dataSource.getConnection().isClosed());
      auth.jdbcAuthentication().dataSource(dataSource)
              .usersByUsernameQuery("select username,password from users where username=?");
      /*auth.jdbcAuthentication().dataSource(dataSource)
              .authoritiesByUsernameQuery("select username, role from user_roles where username =?");*/
  
  }
  
  
   /* @Autowired 
    public void globalUserDetails(AuthenticationManagerBuilder
    auth) throws Exception {
    //System.out.println("Auth : "+auth.inMemoryAuthentication().toString());
    auth.inMemoryAuthentication()
   .withUser("crmadmin").password("crmpass").roles("ADMIN","USER").and()
   .withUser("crmuser").password("pass123").roles("USER");
    }*/
  
  
  @Override
  @Order(Ordered.HIGHEST_PRECEDENCE)
  protected void configure(HttpSecurity http) throws Exception {
      http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable()
              .authorizeRequests().antMatchers("/about").permitAll().antMatchers("/signup").permitAll()
              .antMatchers("/oauth/token").permitAll()
              // .antMatchers("/api/**").authenticated()
              // .antMatchers("/api/**").hasRole("USER")
              .anyRequest().authenticated().and().httpBasic().realmName("CRM_REALM");
  }
  
  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
      return super.authenticationManagerBean();
  }
  
  @Bean
  public TokenStore tokenStore() {
      return new  JdbcTokenStore(dataSource);
  }
  
  @Bean
  @Autowired
  public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
      TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
      handler.setTokenStore(tokenStore);
      handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
      handler.setClientDetailsService(clientDetailsService);
      return handler;
  }
  
  @Bean
  @Autowired
  public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
      TokenApprovalStore store = new TokenApprovalStore();
      store.setTokenStore(tokenStore);
      return store;
  }
  </code></pre>
  
  <p>}</p>
  
  <h1>POSTMAN RESULTS</h1>
  
  <p><a href="https://i.stack.imgur.com/6AA3c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6AA3c.png" alt="enter image description here"></a>
  <a href="https://i.stack.imgur.com/SaEJY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SaEJY.png" alt="enter image description here"></a></p>