title: Facing Access Denied (403) - Forbidden error in spring security oauth2
body: <pre><code>.antMatchers("/secure2/**").authenticated();
  </code></pre>
  
  <p>I have configured one of my api as protected, when I try to access it, It gives me Access Denied error message, I do not know what could be the reason. Note that I am passing valid access token.</p>
  
  <p><strong>My scenario:</strong>
  Basically I have created logout rest api in authorization server and I want that, request with valid token is allowed to hit this api.</p>
  
  <p>Request:</p>
  
  <pre><code>GET /auth/secure2 HTTP/1.1
  Host: localhost:9191
  Authorization: Bearer 33984141-1249-4465-a3aa-0b95a053fc63
  Cache-Control: no-cache
  Postman-Token: f4661790-a8e1-90ea-f6db-79cb37958cdf
  </code></pre>
  
  <p>Response:</p>
  
  <pre><code>{
      "timestamp": 1500186837033,
      "status": 403,
      "error": "Forbidden",
      "message": "Access Denied",
      "path": "/auth/secure2"
  }
  </code></pre>
  
  <p>I found out that below method return false and due to that it raise the access denied error.</p>
  
  <pre><code>public final class ExpressionUtils {
  
      public static boolean evaluateAsBoolean(Expression expr, EvaluationContext ctx) {
          try {
              return ((Boolean) expr.getValue(ctx, Boolean.class)).booleanValue();
          }
          catch (EvaluationException e) {
              throw new IllegalArgumentException("Failed to evaluate expression '"
                      + expr.getExpressionString() + "'", e);
          }
      }
  }
  </code></pre>
  
  <p>Below are the screen shots which I captured by debugging in framework. Please also check the images mentioned in comment.</p>
  
  <p><a href="https://i.stack.imgur.com/rDP8U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rDP8U.png" alt="enter image description here"></a></p>
  
  <p>Code:</p>
  
  <p>SecurityConfiguration.java :</p>
  
  <pre><code>import org.springframework.beans.factory.annotation.Autowired;
  
  
  @Configuration
  @EnableWebSecurity
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  
      @Autowired
      private CustomUserDetailService userDetailsService;
  
      @Bean
      public PasswordEncoder passwordEncoder() {
          return new StandardPasswordEncoder();
      }
  
      @Override
      protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
          auth.authenticationProvider(authenticationProvider());
      }
  
      @Bean
      public DaoAuthenticationProvider authenticationProvider() {
          DaoAuthenticationProvider authProvider
            = new DaoAuthenticationProvider();
          authProvider.setUserDetailsService(userDetailsService);
          authProvider.setPasswordEncoder(encoder());
          return authProvider;
      }
  
      @Bean
      public ShaPasswordEncoder encoder() {
          return new ShaPasswordEncoder(256);
      }
  
      @Override
      public void configure(WebSecurity web) throws Exception {}
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
           http
           .exceptionHandling()
           .accessDeniedHandler(accessDeniedHandler())
           .and()
           .csrf()
           .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
           .disable()
           .headers()
           .frameOptions().disable().disable()
           .sessionManagement()
           .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
           .and()
           .authorizeRequests()
           .antMatchers("/hello/").permitAll()
           .antMatchers("/secure3/").permitAll()
           .antMatchers("/oauth/token/revoke/**").authenticated()
           .antMatchers("/secure2/**").authenticated();
  
      }
  
      @Bean
      public AccessDeniedHandler accessDeniedHandler(){
          return new CustomAccessDeniedHandler();
      }
  
      @Override
      @Bean
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
      @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
      private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
  
          public GlobalSecurityConfiguration() {
          }
          @Override
          protected MethodSecurityExpressionHandler createExpressionHandler() {
              return new OAuth2MethodSecurityExpressionHandler();
          }
  
      }
  
  }
  </code></pre>
  
  <p>Oauth2Configuration.java</p>
  
  <pre><code>@Configuration
  public class OAuth2Configuration {
  
  
      @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_ACCESS_TOKEN_VALIDITY_SECONDS = "accessTokenValidityInSeconds";
          private static final String PROP_REFRESH_TOKEN_VALIDITY_SECONDS = "refreshTokenValidityInSeconds";
  
          private RelaxedPropertyResolver propertyResolver;
  
          @Autowired
          private DataSource dataSource;
  
          @Autowired
          private CustomUserDetailService userDetailsService;
  
          @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())
                       .userDetailsService(userDetailsService)
                       .tokenEnhancer(tokenEnhancer())
                       .accessTokenConverter(accessTokenConverter())
                       .authenticationManager(authenticationManager);
          }
  
          @Bean
          public TokenEnhancer tokenEnhancer() {
             return new CustomTokenEnhancer();
          }
  
          @Bean
          public DefaultAccessTokenConverter accessTokenConverter() {
              return new DefaultAccessTokenConverter();
          }
  
          @Override
          public void configure(AuthorizationServerSecurityConfigurer oauthServer)
                  throws Exception {
              oauthServer
                  .tokenKeyAccess("permitAll()")
                  .checkTokenAccess("isAuthenticated()");
          }
  
  
          @Override
          public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
              clients
                      .inMemory()
  
                      .withClient("clientId")
                      .scopes("read", "write")
                      .authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name())
                      .authorizedGrantTypes("password", "refresh_token")
                      .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_ACCESS_TOKEN_VALIDITY_SECONDS, Integer.class, 80))
                      .refreshTokenValiditySeconds(propertyResolver.getProperty(PROP_REFRESH_TOKEN_VALIDITY_SECONDS, Integer.class, 180))
  
                      .and().inMemory()
                      .withClient("clientid")
                      .scopes("read", "write")
                      .authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name())
                      .authorizedGrantTypes("client_credentials")
                      .secret("secret");
  
          }
  
          @Override
          public void setEnvironment(Environment environment) {
              this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
          }
  
      }
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>@Controller
  @RequestMapping("/secure2")
  public class SecureController1 {
  
      @RequestMapping(method = RequestMethod.GET)
      @ResponseBody
      public String sayHello() {
  
          return "Secure Hello secure2!";
      }
  
  }
  </code></pre>
  
  <p>What are the scenarios in which it raises access denied error message? Please let me know if any other information in needed.</p>