title: Spring Boot Oauth2 UserDetailsService from database - access denied
body: <p>I've been trying to implement Oauth2 authorisation and resource servers. Up until now I've just been using a hard coded user:</p>
  
  <pre><code>@EnableWebSecurity
  public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
  
      @Bean
      @Override
      public UserDetailsService userDetailsService() {
  
          UserDetails user=User.builder()
              .username("user")
              .password( passwordEncoder().encode("secret") )
              .roles("USER")
              .build();
  
          return new InMemoryUserDetailsManager(user);
      }
  </code></pre>
  
  <p>This has worked out well. But I have multiple users in my database that I want to use as users login instead.</p>
  
  <p>So, I've removed the above @Bean method from that class and implemented UserDetailsService as a class of its own:</p>
  
  <pre><code>@Service
  public class MyUserDetailsService implements UserDetailsService {
  
      @Autowired
      private UserRepository userRepository;
  
      @Override
      public UserDetails loadUserByUsername(String username) {
          User user = userRepository.findByUsername(username);
          System.out.println("loadUserByUsername: "+user);
          if (user == null) {
              throw new UsernameNotFoundException(username);
          }
          return new MyUserPrincipal(user);
      }
  }
  </code></pre>
  
  <p>And my UserDetails implementation:</p>
  
  <pre><code>public class MyUserPrincipal implements UserDetails {
  
      private static final long serialVersionUID = -1480402973442569981L;
      private User user;
  
      public MyUserPrincipal(User user) {
          this.user = user;
      }
  
      @Override
      public String getUsername() {
          System.out.println("Getting username: "+user.getUsername());
          return user.getUsername();
      }
  
      @Override
      public String getPassword() {
          System.out.println("Getting password: "+user.getPassword());
          return user.getPassword();
      }
  
      @Override
      public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {
          final List&lt;GrantedAuthority&gt; authorities = Collections.singletonList(new SimpleGrantedAuthority("USER"));
          return authorities;
      }
  
      @Override
      public boolean isAccountNonExpired() {
          return true;
      }
  
      @Override
      public boolean isAccountNonLocked() {
          return true;
      }
  
      @Override
      public boolean isCredentialsNonExpired() {
          return true;
      }
  
      @Override
      public boolean isEnabled() {
          return true;
      }
  
      public User getUser() {
          return user;
      }
  
  }
  </code></pre>
  
  <p>I've the following in my user table:</p>
  
  <pre><code>mysql&gt; select * from user;
  +----+--------------------------------------------------------------+----------+
  | id | password                                                     | username |
  +----+--------------------------------------------------------------+----------+
  |  1 | $2a$10$7tYTQ/dMXASLZG2OptweV.JdVH9RoDsG2ighxq5im3A/srnOo9OYC | user     |
  +----+--------------------------------------------------------------+----------+
  1 row in set (0.00 sec)
  </code></pre>
  
  <p>With this new setup, I am able to retrieve my access token as before:</p>
  
  <p>POST /oauth/token</p>
  
  <pre><code>{
      "access_token": "8cf0a509-2a56-4adc-ace7-38f39beee8a1",
      "token_type": "bearer",
      "refresh_token": "742a109f-6768-48b5-9818-76397dc658fb",
      "expires_in": 42705,
      "scope": "read write"
  }
  </code></pre>
  
  <p>However, when I try to access the resource as before it now gives me the following response:</p>
  
  <p>GET /funds</p>
  
  <pre><code>{
      "error": "access_denied",
      "error_description": "Access is denied"
  }
  </code></pre>
  
  <p>I'm not seeing any errors or exceptions thrown. I suspected it was something to do with the roles and this user just not being authorized. Here is my ClientDetailsServiceConfigurer setup:</p>
  
  <pre><code>@Configuration
  @EnableAuthorizationServer
  public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
  
      //...
  
      @Override
      public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  
          clients.inMemory()
              .withClient("cliente")
              .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
              .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT", "USER")
              .scopes("read", "write")
              .autoApprove(true)
              .secret(passwordEncoder().encode("password"));
  
      }
  </code></pre>
  
  <p>UPDATE </p>
  
  <p>Here's my ResourceServerConfigurerAdapter implementation:</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableResourceServer
  public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
  {
      @Override
      public void configure(HttpSecurity http) throws Exception {
  
          http.anonymous().disable()
              .requestMatchers()
                  .antMatchers("/funds/**")
              .and().authorizeRequests()
                  .antMatchers("/funds/**")
                  .access("hasRole('USER')")
              .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
      }   
  
  }
  </code></pre>