title: how to solve "Handling error: InvalidGrantException, Bad credentials"
body: <p>I want to work with OAuth2. but I have problem. I can't access token.
  this is my code</p>
  
  <p>model.entity.user:</p>
  
  <pre><code>package com.example.oauth2.model.entity;
  
  import javax.persistence.*;
  import java.util.List;
  
  @Entity(name = "users")
  @Table(name = "USERS")
  public class User {
  
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private int id;
      @Column(columnDefinition = "varchar2(20)")
      private String username;
  
      @Column(columnDefinition = "varchar2(20)")
      private String password;
  
      @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
      @JoinColumn(name = "fk")
      private List&lt;Role&gt; roles;
  
      public User(String username, String password, List&lt;Role&gt; roles) {
          this.username = username;
          this.password = password;
          this.roles = roles;
      }
  
      public User() {
      }
  
  
      public int getId() {
          return id;
      }
  
      public void setId(int id) {
          this.id = id;
      }
  
      public String getUsername() {
          return username;
      }
  
      public void setUsername(String username) {
          this.username = username;
      }
  
      public String getPassword() {
          return password;
      }
  
      public void setPassword(String password) {
          this.password = password;
      }
  
      public List&lt;Role&gt; getRoles() {
          return roles;
      }
  
      public void setRoles(List&lt;Role&gt; roles) {
          this.roles = roles;
      }
  }
  </code></pre>
  
  <p>model.entity.Role:</p>
  
  <pre><code>package com.example.oauth2.model.entity;
  
  import javax.persistence.*;
  
  @Entity(name = "roles")
  @Table(name = "ROLES")
  public class Role {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private int id;
      private String name;
  
      public Role() {
      }
  
      public Role(String name) {
          this.name = name;
      }
  
      public int getId() {
          return id;
      }
  
      public void setId(int id) {
          this.id = id;
      }
  
      public String getName() {
          return name;
      }
  
      public void setName(String name) {
          this.name = name;
      }
  }
  
  </code></pre>
  
  <p>model.repository.UserDA:</p>
  
  <pre><code>
  
  import com.example.oauth2.model.entity.User;
  import org.springframework.stereotype.Repository;
  
  import javax.persistence.EntityManager;
  import javax.persistence.PersistenceContext;
  import javax.persistence.Query;
  import javax.transaction.Transactional;
  import java.util.List;
  
  @Repository
  @Transactional
  public class UserDA {
      @PersistenceContext
      private EntityManager entityManager;
  
  
      public void save(User user) {
          entityManager.persist(user);
      }
  
  
      public User findById(int id) {
          return entityManager.find(User.class, id);
      }
  
  
      public User findByUsername(String username) {
          Query query = entityManager.createQuery("select entity from users entity");
          //query.setParameter("n",username);
          List&lt;User&gt; users = query.getResultList();
          User u=null;
          for (User user : users) {
              if (user.getUsername().equals(username)) {
                 u = user;
                 break;
              }
          }
          return u;
      }
  
  }
  </code></pre>
  
  <p>model.service.UserDetailImpl:</p>
  
  <pre><code>package com.example.oauth2.model.service;
  
  import com.example.oauth2.model.entity.Role;
  import com.example.oauth2.model.entity.User;
  import org.springframework.security.core.GrantedAuthority;
  import org.springframework.security.core.authority.SimpleGrantedAuthority;
  import org.springframework.security.core.userdetails.UserDetails;
  import org.springframework.stereotype.Service;
  
  import java.util.ArrayList;
  import java.util.Collection;
  import java.util.List;
  
  
  public class UserDetailImpl implements UserDetails {
  
  
      private String password;
      private String username;
      private Collection&lt;? extends GrantedAuthority&gt; authorities;
  
      public UserDetailImpl(User user) {
          this.username = user.getUsername();
          this.password = user.getPassword();
          this.authorities = translate(user.getRoles());
      }
  
  
      private Collection&lt;? extends GrantedAuthority&gt; translate(List&lt;Role&gt; roles) {
          List&lt;GrantedAuthority&gt; authorities = new ArrayList&lt;&gt;();
          for (Role role : roles) {
              String roleName = role.getName().toUpperCase();
              authorities.add(new SimpleGrantedAuthority(roleName));
          }
  
          return authorities;
      }
  
  
      @Override
      public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {
          return authorities;
      }
  
      @Override
      public String getPassword() {
          return password;
      }
  
      @Override
      public String getUsername() {
          return username;
      }
  
      @Override
      public boolean isAccountNonExpired() {
          return true;
      }
  
      @Override
      public boolean isAccountNonLocked() {
          return true;
      }
  
      @Override
      public boolean isCredentialsNonExpired() {
          return true;
      }
  
      @Override
      public boolean isEnabled() {
          return true;
      }
  }
  </code></pre>
  
  <p>controller.HomeController:</p>
  
  <pre><code>package com.example.oauth2.controller;
  
  
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RestController;
  
  @RestController
  public class HomeController {
  
      @RequestMapping("/")
      public String home(){
          return "Home";
      }
  
  
      @RequestMapping("/private")
      public String privatem() {
          return "private";
      }
  
  }
  </code></pre>
  
  <p>config.AuthorizationServerConfig:</p>
  
  <pre><code>package com.example.oauth2.config;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.security.authentication.AuthenticationManager;
  import org.springframework.security.crypto.password.PasswordEncoder;
  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.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
  
  
  @Configuration
  @EnableAuthorizationServer
  public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  
  
      @Autowired
      private AuthenticationManager authenticationManager;
  
      @Autowired
      private PasswordEncoder passwordEncoder;
  
  
      @Override
      public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
          security.checkTokenAccess("isAuthenticated()");
      }
  
      @Override
      public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
          clients
                  .inMemory()
                  .withClient("my-trusted-client")
                  .authorizedGrantTypes("password")
                  .authorities("ROLE_CLIENT","ROLE_TRUSTED_CLIENT","USER")
                  .scopes("read","write","trust")
                  .resourceIds("oauth2-resource")
                  .accessTokenValiditySeconds(1000)
                  .secret(passwordEncoder.encode("secret"));
      }
  
  
     @Override
      public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
          endpoints
                  .authenticationManager(authenticationManager);
      }
  
  }
  </code></pre>
  
  <p>config.ResourseServerConfig:</p>
  
  <pre><code>package com.example.oauth2.config;
  
  import org.springframework.context.annotation.Configuration;
  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;
  
  
  @Configuration
  @EnableResourceServer
  public class ResourseServerConfig extends ResourceServerConfigurerAdapter {
  
  
  
  
      @Override
      public void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests()
                  .antMatchers("/").permitAll()
                  .antMatchers("/private").authenticated();
      }
  }
  </code></pre>
  
  <p>config.WebSecurityConfig:</p>
  
  <pre><code>package com.example.oauth2.config;
  
  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.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  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.password.PasswordEncoder;
  
  @Configuration
  @EnableWebSecurity
  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      private UserDetailsService customUserDetailsService;
  
      @Autowired
      private PasswordEncoder passwordEncoder;
  
      @Autowired
      public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
          System.out.println("2222222222222222222");
          auth
                  .userDetailsService(customUserDetailsService)
                  .passwordEncoder(passwordEncoder);
      }
  
      @Override
      public void configure(HttpSecurity http) throws Exception {
          http
                  .authorizeRequests()
                  .antMatchers("/oauth/token").permitAll()
                  .anyRequest().authenticated()
                  .and()
                  .httpBasic()
                  .and()
                  .csrf().disable();
      }
  
  
      @Bean
      @Override
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
  }
  </code></pre>
  
  <p>this is my request:</p>
  
  <pre><code>http://localhost:8080/oauth/token?grant_type=password&amp;username=user&amp;password=user
  </code></pre>
  
  <p>and Authorization :
  <code>
  username: my-trusted-client
  password: secret
  </code></p>
  
  <p>and this is my warning:
  <code>
  2019-11-14 18:32:17.229  WARN 14920 --- [nio-8080-exec-4] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Encoded password does not look like BCrypt
  2019-11-14 18:32:17.231  WARN 14920 --- [nio-8080-exec-4] o.s.s.o.provider.endpoint.TokenEndpoint  : Handling error: InvalidGrantException, Bad credentials
  </code></p>
  
  <p>can you help me please;
  I think very much about this but I can't solve it;</p>