title: OAuth2-SpringBoot - Refresh token
body: <p>I have configured my spring boot application to to provide oauth2 authorization.</p>
  
  <pre><code>@Configuration
  public class OAuth2Configuration {
  
      @Configuration
      @EnableResourceServer
      protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
  
         @Autowired
         private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
  
         @Autowired
         private CustomLogoutSuccessHandler customLogoutSuccessHandler;
  
         @Override
         public void configure(HttpSecurity http) throws Exception {
             http.exceptionHandling()
                 .authenticationEntryPoint(customAuthenticationEntryPoint)
                          .and()
                          .logout()
                          .logoutUrl("/oauth/logout")
                          .logoutSuccessHandler(customLogoutSuccessHandler)
                          .and()
                          .csrf()
                          .disable()
                          .headers()
                          .frameOptions().disable()
                          .exceptionHandling().and()
                          .sessionManagement()
                          .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                          .and()
                          .authorizeRequests()
                          .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                          .antMatchers("/api/v1/login/**").permitAll()
                          .antMatchers("/api/v1/admin/**").permitAll()
                          .antMatchers("/api/v1/test/**").permitAll()
                          .antMatchers("/oauth/token").permitAll()
                          .antMatchers("/api/**").authenticated();
              }
          }
  
      @Configuration
      @EnableAuthorizationServer
      protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {
  
          private static final String ENV_OAUTH = "authentication.oauth.";
          private static final String PROP_CLIENTID = "clientid";
          private static final String PROP_SECRET = "secret";
          private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";
          private RelaxedPropertyResolver propertyResolver;
  
          @Autowired
          private DataSource dataSource;
  
          @Bean
          public TokenStore tokenStore() {
              return new JdbcTokenStore(dataSource);
          }
  
          @Autowired
          @Qualifier("authenticationManagerBean")
          private AuthenticationManager authenticationManager;
  
          @Override
          public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
              endpoints.tokenStore(tokenStore())
                       .authenticationManager(authenticationManager);
          }
  
          @Override
          public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
              clients.inMemory()
                     .withClient(propertyResolver.getProperty(PROP_CLIENTID))
                     .scopes("read", "write")
                     .authorities(Authorities.ROLE_USER.name())
                     .authorizedGrantTypes("password", "refresh_token", "authorization_code", "implicit")
                     .secret(propertyResolver.getProperty(PROP_SECRET))
                     .accessTokenValiditySeconds(
                      propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800))
                     .refreshTokenValiditySeconds(100000);
              }
  
          @Override
          public void setEnvironment(Environment environment) {
              this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
          }
      }
  }
  
  @Configuration
  @EnableWebSecurity
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
      @Autowired
      private UserDetailsService userDetailsService;
  
      @Bean
      public CustomPasswordEncoder passwordEncoder() {
          return new CustomPasswordEncoder();
      }
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(userDetailsService)
              .passwordEncoder(passwordEncoder());
      }
  
      @Override
      public void configure(WebSecurity web) throws Exception {
          web.ignoring()
             .antMatchers(HttpMethod.OPTIONS, "/**").antMatchers("/api/login/**");
      }
  
      @Override
      public void configure(HttpSecurity http) throws Exception {      
          http.httpBasic().realmName("WebServices").and().sessionManagement()
              .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
              .requestMatchers().antMatchers("/oauth/authorize").and()
              .authorizeRequests().antMatchers("/oauth/authorize")
              .authenticated();
      }
  
      @Override
      @Bean
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
      @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
      private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
          @Override
          protected MethodSecurityExpressionHandler createExpressionHandler() {
              return new OAuth2MethodSecurityExpressionHandler();
          }
      }
  }
  
  public class UserDetailsServiceImpl implements UserDetailsService {
      @Inject
      private AccountDao accountDao;
  
      @Override
      @Transactional
      public UserDetails loadUserByUsername(final String login) {
          Account userFromDatabase = null;
          String lowercaseLogin = login.toLowerCase();
          if (lowercaseLogin.contains("@")) {
              userFromDatabase = accountDao.getByEmailId(lowercaseLogin);
          } else {
              userFromDatabase = accountDao.getByPhoneNumber(lowercaseLogin);
          }
  
          if (userFromDatabase != null) {
              if (!userFromDatabase.getActivated()) {
                  throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
              }
              List&lt;GrantedAuthority&gt; grantedAuthorities = userFromDatabase.getRoles().stream()
                      .map(authority -&gt; new SimpleGrantedAuthority(authority.getRoleName())).collect(Collectors.toList());
              return new org.springframework.security.core.userdetails.User(userFromDatabase.getAccountName(),
                      userFromDatabase.getAccountPassword(), grantedAuthorities);
          } else {
              throw new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + "database");
          }
      }
  }
  </code></pre>
  
  <p>Now whenever I try to get the refresh token after the access token expires, I always get </p>
  
  <blockquote>
    <p>2017-07-10 00:57:40.797  INFO 68115 --- [nio-9090-exec-4]
    o.s.s.o.provider.endpoint.TokenEndpoint  : Handling error:
    NoSuchClientException, No client with requested id: 12345678</p>
  </blockquote>
  
  <p>Though there is a row in the db with the column phone number 12345678 and account name as 12345678.</p>
  
  <p><a href="https://myTestWebServices/oauth/token?grant_type=refresh_token&amp;refresh_token=f4cc8213-3f2b-4a30-965b-6feca898479e" rel="nofollow noreferrer">https://myTestWebServices/oauth/token?grant_type=refresh_token&amp;refresh_token=f4cc8213-3f2b-4a30-965b-6feca898479e</a></p>
  
  <p>I have the header set to <code>Authorization: Basic xxx</code> 
  <code>xxx</code> is the same that I use to get the <code>access_token</code> so I am assuming it works fine.</p>
  
  <p>But the output is always this </p>
  
  <blockquote>
    <p>{ "error": "unauthorized", "error_description": "User 12345678 was
    not found in the database" }</p>
  </blockquote>