title: Handling error: InvalidGrantException, Bad credentials
body: <p>package com.phynart.cloud.config;</p>
  
  <pre><code>    import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.security.authentication.AuthenticationManager;
      import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
      import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
      import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
      import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
      import org.springframework.security.oauth2.provider.token.TokenStore;
      import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
      import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
  
      @Configuration
      @EnableAuthorizationServer
      public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  
          private static final Logger logger = LoggerFactory.getLogger(AuthorizationServerConfig.class);
  
          static final String CLIEN_ID = "devglan-client";
          static final String CLIENT_SECRET = "devglan-secret";   
          static final String GRANT_TYPE_PASSWORD = "password";
          static final String AUTHORIZATION_CODE = "authorization_code";
          static final String REFRESH_TOKEN = "refresh_token";
          static final String IMPLICIT = "implicit";
          static final String SCOPE_READ = "read";
          static final String SCOPE_WRITE = "write";
          static final String TRUST = "trust";
          static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60*60;
          static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6*60*60;
  
          @Autowired
          private AuthenticationManager authenticationManager;
  
          @Bean
          public JwtAccessTokenConverter accessTokenConverter() {
              logger.debug("in access token converter");
              JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
              converter.setSigningKey("as466gf");
              return converter;
          }
  
          @Bean
          public TokenStore tokenStore() {
              logger.debug("tokenStore");
              return new JwtTokenStore(accessTokenConverter());
          }
  
          @Override
          public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
              logger.debug("ClientDetailsServiceConfigurer");
              configurer
                      .inMemory()
                      .withClient(CLIEN_ID)
                      .secret(CLIENT_SECRET)
                      .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
                      .scopes(SCOPE_READ, SCOPE_WRITE, TRUST)                     
                      .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
                      .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
          }
  
          @Override
          public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
              logger.debug("AuthorizationServerEndpointsConfigurer");
              endpoints.tokenStore(tokenStore())
                      .authenticationManager(authenticationManager)
                      .accessTokenConverter(accessTokenConverter());
          }
      }
  
  package com.phynart.cloud.config;
  
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.security.authentication.AuthenticationManager;
  import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
  import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
  
  @Configuration
  @EnableResourceServer
  public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  
      private static final Logger logger = LoggerFactory.getLogger(ResourceServerConfig.class);
  
      private static final String RESOURCE_ID = "resource_id";
  
      @Override
      public void configure(ResourceServerSecurityConfigurer resources) {
          logger.debug("ResourceServerSecurityConfigurer");
          resources.resourceId(RESOURCE_ID).stateless(false);
      }
  
      @Override
      public void configure(HttpSecurity http) throws Exception {
          logger.debug("HttpSecurity resource");
          http.
                  anonymous().disable()
                  .authorizeRequests()
                  .antMatchers("/users/**").access("hasRole('ADMIN')")
                  .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
      }    
  
  }
  
  
  package com.phynart.cloud.config;
  
  import javax.annotation.Resource;
  
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.boot.web.servlet.FilterRegistrationBean;
  import org.springframework.context.annotation.Bean;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.http.HttpMethod;
  import org.springframework.security.authentication.AuthenticationManager;
  import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  import org.springframework.security.core.userdetails.UserDetailsService;
  import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  import org.springframework.web.cors.CorsConfiguration;
  import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  import org.springframework.web.filter.CorsFilter;
  
  
  @Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);
  
      @Resource(name = "UserService")
      private UserDetailsService userDetailsService;
  
      @Override
      @Bean
      public AuthenticationManager authenticationManagerBean() throws Exception {
          logger.debug("inside authentication manager");
          return super.authenticationManagerBean();
      }
  
      @Autowired
      public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
          logger.debug("password encoder");
          auth.userDetailsService(userDetailsService)
                  .passwordEncoder(encoder());    
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
  
          logger.debug("HttpSecurity");
          http
                  .csrf().disable()
                  .anonymous().disable()
                  .authorizeRequests()
                  .antMatchers("/api-docs/**").permitAll();
      }
  
      @Bean
      public BCryptPasswordEncoder encoder(){
          logger.debug("inside password encoder");
          // return new BCryptPasswordEncoder();
          BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
          logger.debug("bCryptPasswordEncoder -" + bCryptPasswordEncoder);
          return bCryptPasswordEncoder;
      }    
  
  
      @Bean
      public FilterRegistrationBean corsFilter() {
          logger.debug("corsFilter");
          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          CorsConfiguration config = new CorsConfiguration();
          config.setAllowCredentials(true);
          config.addAllowedOrigin("*");
          config.addAllowedHeader("*");
          config.addAllowedMethod("*");
          source.registerCorsConfiguration("/**", config);
          FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
          bean.setOrder(0);
          return bean;
      }
  }
  
  
  package com.phynart.cloud.controller;
  
  import java.util.List;
  
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.core.annotation.Order;
  import org.springframework.web.bind.annotation.GetMapping;
  import org.springframework.web.bind.annotation.PathVariable;
  import org.springframework.web.bind.annotation.RequestBody;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RequestMethod;
  import org.springframework.web.bind.annotation.RestController;
  
  import com.phynart.cloud.model.User;
  import com.phynart.cloud.service.UserService;
  import java.security.Principal;
  
  @RestController
  @RequestMapping("/users")
  public class UserController {
  
      private static final Logger logger = LoggerFactory.getLogger(UserController.class);
  
      @Autowired    
      private UserService userService;
  
      @RequestMapping(value="/user", method = RequestMethod.GET)
      public Iterable&lt;User&gt; listUser(){
          logger.debug("inside controller");
          return userService.findAll();
      }
  
      @RequestMapping(value = "/user", method = RequestMethod.POST)
      public User create(@RequestBody User user){
          return userService.save(user);
      }
  
      @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
      public String delete(@PathVariable(value = "id") Long id){
          userService.delete(id);
          return "success";
      }
  
  }
  
  
  package com.phynart.cloud.service;
  
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.List;
  
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.security.core.authority.SimpleGrantedAuthority;
  import org.springframework.security.core.userdetails.UserDetails;
  import org.springframework.security.core.userdetails.UserDetailsService;
  import org.springframework.security.core.userdetails.UsernameNotFoundException;
  import org.springframework.stereotype.Service;
  
  import com.phynart.cloud.dao.UserDao;
  import com.phynart.cloud.model.User;
  
  @Service(value = "UserService")
  public class UserServiceImpl implements UserDetailsService {
  
      private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
  
      @Autowired
      private UserDao userDao;
  
      public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
          logger.debug("loadUserByUsername");
          User user = userDao.findByUsername(userId);
          if(user == null){
              throw new UsernameNotFoundException("Invalid username or password.");
          }
          logger.debug("before returning user");
          logger.debug("username -" + user.getUsername());
          logger.debug("password -" + user.getPassword());        
          return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthority());
  
      }
  
      private List getAuthority() {
          return Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
      }
  
      public List findAll() {
          logger.debug("findAll");
          List list = new ArrayList&lt;&gt;();
          userDao.findAll().iterator().forEachRemaining(list::add);
          return list;
      }
  }
  
  package com.phynart.cloud.service;
  
  import java.util.List;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.core.annotation.Order;
  import org.springframework.stereotype.Service;
  
  import com.phynart.cloud.dao.UserDao;
  import com.phynart.cloud.model.User;
  
  @Service
  public class UserService {
  
      @Autowired
      UserDao userDao;
  
      public Iterable&lt;User&gt; findAll() {
  
          return userDao.findAll();
      }
  
      public User save(User user) {
  
          return userDao.save(user);
      }
  
      public void delete(Long id) {
          // TODO Auto-generated method stub
  
      }
  
  }
  </code></pre>
  
  <p>I am getting bad credentials "Handling error: InvalidGrantException, Bad credentials", even If i comment the BCryptPasswordEncoder portion and use plain password in database still am facing issue, could anyone please help me out? i am not finding any solution and I am new to oauth implementation, 
   i have added the AuthorizartionServerConfig, ResourceServerConfig, SecurityConfig, UserServiceImpl, UserController - I have pulled the code from site - <a href="https://www.devglan.com/spring-security/spring-boot-oauth2-jwt-example" rel="nofollow noreferrer">https://www.devglan.com/spring-security/spring-boot-oauth2-jwt-example</a></p>
  
  <p><a href="https://i.stack.imgur.com/hD9kK.png" rel="nofollow noreferrer">basic auth from postman</a></p>
  
  <p><a href="https://i.stack.imgur.com/DbQJm.png" rel="nofollow noreferrer">Body in postman for user credetial</a></p>
  
  <p><a href="https://i.stack.imgur.com/i1k1q.png" rel="nofollow noreferrer">database credential of the user</a></p>
  
  <p><a href="https://i.stack.imgur.com/p3CI3.png" rel="nofollow noreferrer">data entered from the site i coded - https://www.devglan.com/spring-security/spring-boot-oauth2-jwt-example</a></p>