title: My SparkJava resource server gets 403 errors when trying to validate access tokens
body: <p>I want to set up a very basic REST API using Spark-java, which just checks an access token obtained from my own authorisation server. It creates a GET request to the authorisation server's <code>/oauth/authorize</code> endpoint followed by <code>?token=$ACCESS_TOKEN</code>.</p>
  <p>Whenever I try this, I get diverted to the <code>/error</code> endpoint and a 403 error.</p>
  <p>Here's my API class:</p>
  <pre><code>import org.apache.http.client.methods.HttpGet;
  import org.apache.http.entity.ContentType;
  import org.apache.http.impl.client.CloseableHttpClient;
  import org.apache.http.impl.client.HttpClients;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import spark.utils.StringUtils;
  
  import java.io.IOException;
  
  import static spark.Spark.*;
  
  public class SampleAPI {
    private static final Logger logger = LoggerFactory.getLogger(&quot;SampleAPI&quot;);
  
    public static void main(String[] args) {
      // Run on port 9782
      port(9782);
      // Just returns &quot;Hello there&quot; to the client's console
      before((preRequest, preResponse) -&gt; {
  
        System.out.println(&quot;Getting token from request&quot;);
        final String authHeader = preRequest.headers(&quot;Authorization&quot;);
        //todo validate token, don't just accept it because it's not null/empty
        if(StringUtils.isEmpty(authHeader) || !isAuthenticated(authHeader)){
          halt(401, &quot;Access not authorised&quot;);
        } else {
          System.out.println(&quot;Token = &quot; + authHeader);
        }
      });
      get(&quot;/&quot;, (res, req) -&gt; &quot;Hello there&quot;);
    }
  
    private static boolean isAuthenticated(final String authHeader) {
      String url = &quot;http://localhost:9780/oauth/authorize&quot;;
      //&quot;Bearer &quot; is before the actual token in authHeader, so we need to extract the token itself as a substring
      String token = authHeader.substring(7);
      HttpGet getAuthRequest = new HttpGet(url + &quot;?token=&quot; + token);
      getAuthRequest.setHeader(&quot;Content-Type&quot;, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
      CloseableHttpClient httpClient = HttpClients.createMinimal();
      try {
        CloseableHttpResponse response = httpClient.execute(getAuthRequest);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(&quot;Status code &quot; + statusCode + &quot; returned for access token &quot; + authHeader);
        return statusCode == 200;
      } catch (IOException ioException) {
        System.out.println(&quot;Exception when trying to validate access token &quot; + ioException);
      }
      return false;
    }
  }
  </code></pre>
  <p>The <code>System.out.println</code> statements are just for debugging.</p>
  <p>Here's my authorisation server's WebSecurityConfigurerAdapter class:</p>
  <pre><code>    package main.config;
      
      import main.service.ClientAppDetailsService;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Qualifier;
      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.builders.WebSecurity;
      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.factory.PasswordEncoderFactories;
      import org.springframework.security.crypto.password.PasswordEncoder;
      
      @Configuration
      @EnableWebSecurity(debug = true)
      public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
      
        @Autowired
        private UserDetailsService userDetailsService;
      
        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
          //returns AuthenticationManager from the superclass for authenticating users
          return super.authenticationManagerBean();
        }
      
        @Bean
        public PasswordEncoder getPasswordEncoder() {
          return PasswordEncoderFactories.createDelegatingPasswordEncoder();
        }
      
        @Override
        public void configure(WebSecurity web) throws Exception {
          //Allow for DB access without any credentials
          web.ignoring().antMatchers(&quot;/h2-console/**&quot;);
        }
      
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          //configures user details, and uses the custom UserDetailsService to check user credentials
          auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
        }
      
        @Override
        protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests().anyRequest().authenticated();
      
          //disable CORS and CSRF protection for Postman testing
          http.cors().disable().anonymous().disable();
          http.headers().frameOptions().disable();
          http.csrf().disable();
        }
      }
  </code></pre>
  <p>And here's my authorisation server's <code>application.properties</code>:</p>
  <pre><code>server.port=9780
  
  #in-memory database, will get populated using data.sql
  spring.datasource.url=jdbc:h2:mem:testdb
  spring.datasource.driverClassName=org.h2.Driver
  spring.datasource.username=admin
  spring.datasource.password=syst3m
  spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
  
  spring.jpa.properties.hibernate.format_sql=true
  #adds to existing DB instead of tearing it down and re-populating it every time the app is started
  spring.jpa.hibernate.ddl-auto=update
  
  spring.h2.console.enabled=true
  spring.h2.console.path=/h2-console
  spring.h2.console.settings.trace=false
  spring.h2.console.settings.web-allow-others=false
  
  </code></pre>
  <p>What have I done wrong? Do I need to specify my API as a resource server using Spring Security? Do I need to add it to the authorisation server's <code>application.properties</code>?</p>