title: Upgrading Spring Security OAuth2
body: <p>I am trying to upgrade Spring security OAuth2 configuration from 2.0.0.RC1 to 2.0.3.RELEASE. At the time I copied the configuration from sprklr sample and made it work. So it's based on a working example of xml based Spring Security OAuth2 configuration.</p>
  
  <p>Now, I've upgraded to Spring Security latest release (2.0.3 at the time of this writing) and also trying to convert this to java config. I am posting the xml config and the java config below.</p>
  
  <pre><code> &lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:security="http://www.springframework.org/schema/security"
  xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
  http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd"&gt;
  
  &lt;!-- Authentication manager. --&gt;
  &lt;security:authentication-manager alias="authenticationManager"&gt;
      &lt;security:authentication-provider&gt;
          &lt;security:jdbc-user-service data-source-ref="dataSource"
             users-by-username-query="select a.username, a.password, a.enabled, a.email from account a where a.username = ?" 
             authorities-by-username-query="select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?" /&gt;
          &lt;security:password-encoder ref="passwordEncoder"/&gt;
      &lt;/security:authentication-provider&gt;
  &lt;/security:authentication-manager&gt;
  
  &lt;security:global-method-security secured-annotations="enabled" jsr250-annotations="enabled" pre-post-annotations="enabled" /&gt;
  
  
  &lt;security:http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager"&gt;
      &lt;security:intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" /&gt;
      &lt;security:anonymous enabled="false" /&gt;
      &lt;security:http-basic entry-point-ref="clientAuthenticationEntryPoint" /&gt;
      &lt;!-- include this only if you need to authenticate clients via request parameters --&gt;
      &lt;security:custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" /&gt;
      &lt;security:access-denied-handler ref="oauthAccessDeniedHandler" /&gt;
  &lt;/security:http&gt;
  
  &lt;security:http pattern="/api/.*/accounts" request-matcher="regex" create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint" use-expressions="true"&gt;
      &lt;security:intercept-url pattern="/api/.*/accounts" method="POST" requires-channel="https" access="#oauth2.clientHasRole('ROLE_CLIENT') or hasRole('ROLE_ANONYMOUS')"/&gt;
      &lt;security:intercept-url pattern="/.*" access="denyAll()" /&gt;
      &lt;security:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /&gt;
      &lt;security:access-denied-handler ref="oauthAccessDeniedHandler" /&gt;
      &lt;security:expression-handler ref="oauthWebExpressionHandler" /&gt;
  &lt;/security:http&gt;
  
  &lt;security:http pattern="/api/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager"&gt;
      &lt;security:anonymous enabled="false" /&gt;
      &lt;security:intercept-url pattern="/api/**" access="ROLE_USER,SCOPE_TRUST,SCOPE_PLAY"/&gt;
      &lt;security:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /&gt;
      &lt;security:access-denied-handler ref="oauthAccessDeniedHandler" /&gt;
  &lt;/security:http&gt;
  
  &lt;bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"&gt;
      &lt;property name="realmName" value="*****" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"&gt;
      &lt;property name="realmName" value="*****/client" /&gt;
      &lt;property name="typeName" value="Basic" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" /&gt;
  
  &lt;bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"&gt;
      &lt;property name="authenticationManager" ref="clientAuthenticationManager" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"&gt;
      &lt;constructor-arg&gt;
          &lt;list&gt;
              &lt;bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" /&gt;
              &lt;bean class="org.springframework.security.access.vote.RoleVoter" /&gt;
              &lt;bean class="org.springframework.security.access.vote.AuthenticatedVoter" /&gt;
          &lt;/list&gt;
      &lt;/constructor-arg&gt;
  &lt;/bean&gt;
  
  &lt;security:authentication-manager id="clientAuthenticationManager"&gt;
      &lt;security:authentication-provider user-service-ref="clientDetailsUserService" /&gt;
  &lt;/security:authentication-manager&gt;
  
  &lt;bean id="clientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService"&gt;
      &lt;constructor-arg ref="clientDetails" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore" /&gt;
  
  &lt;bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices"&gt;
      &lt;property name="tokenStore" ref="tokenStore" /&gt;
      &lt;property name="tokenEnhancer" ref="tokenEnhancer" /&gt;
      &lt;property name="supportRefreshToken" value="true" /&gt;
      &lt;property name="clientDetailsService" ref="clientDetails" /&gt;
      &lt;property name="accessTokenValiditySeconds" value="6000" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="tokenEnhancer" class="com.****.*****.config.*****TokenEnhancer" /&gt;
  
  &lt;bean id="requestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory"&gt;
      &lt;constructor-arg name="clientDetailsService" ref="clientDetails" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="userApprovalHandler" class="com.****.*****.config.*****UserApprovalHandler"&gt;
      &lt;property name="approvalStore" ref="approvalStore" /&gt;
      &lt;property name="clientDetailsService" ref="clientDetails" /&gt;
      &lt;property name="requestFactory" ref="requestFactory" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id="approvalStore" class="org.springframework.security.oauth2.provider.approval.TokenApprovalStore"&gt;
      &lt;property name="tokenStore" ref="tokenStore" /&gt;
  &lt;/bean&gt;
  
  &lt;oauth:authorization-server
      client-details-service-ref="clientDetails" token-services-ref="tokenServices"
      user-approval-handler-ref="userApprovalHandler"&gt;
      &lt;oauth:authorization-code /&gt;
      &lt;oauth:implicit /&gt;
      &lt;oauth:refresh-token /&gt;
      &lt;oauth:client-credentials /&gt;
      &lt;oauth:password /&gt;
  &lt;/oauth:authorization-server&gt;
  
  &lt;oauth:resource-server id="resourceServerFilter" resource-id="*****" token-services-ref="tokenServices" /&gt;
  
  &lt;oauth:client-details-service id="clientDetails"&gt;
     &lt;oauth:client client-id="*****-php-demo" secret="??????????"
          authorized-grant-types="password,authorization_code,refresh_token,client_credentials"
          authorities="ROLE_USER, ROLE_CLIENT"
          scope="play,trust"
          access-token-validity="6000"/&gt;
  
  
     &lt;oauth:client client-id="*****-swagger-ui"
          authorized-grant-types="implicit"
          authorities="ROLE_USER, ROLE_CLIENT, ROLE_TRUSTED_CLIENT"
          scope="play,trust"
          redirect-uri="${baseUrl}/o2c.html"
          autoapprove="true"
          access-token-validity="6000"/&gt;
  
     &lt;oauth:client client-id="*****-runscope" 
          secret="???????????????????????????????"
          authorized-grant-types="password,authorization_code,refresh_token"
          authorities="ROLE_USER, ROLE_CLIENT, ROLE_TRUSTED_CLIENT"
          scope="play,trust"
          redirect-uri="https://www.runscope.com/oauth_tool/callback"
          autoapprove="true"
          access-token-validity="6000"/&gt;     
  
  &lt;/oauth:client-details-service&gt;  
  
  &lt;oauth:expression-handler id="oauthExpressionHandler" /&gt;
  
  &lt;oauth:web-expression-handler id="oauthWebExpressionHandler" /&gt; 
  </code></pre>
  
  <p></p>
  
  <p>and the java config (so far..)</p>
  
  <pre><code>@Configuration
  public class SecurityConfig {
  
  @Autowired
  private DataSource dataSource;
  
  @Value("${baseUrl}") private String baseUrl;
  
  @Bean
  public ClientDetailsService clientDetailsService() throws Exception {
      ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
  
      serviceConfig.clientDetailsServiceConfigurer().inMemory()
          .withClient("*****-????????")
          .secret("????????????????????")
          .authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
          .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
          .scopes("play", "trust")
      .and()
          .withClient("*****-????????")
          .authorizedGrantTypes("implicit")
          .authorities("ROLE_USER", "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
          .scopes("play", "trust")
          .redirectUris(baseUrl + "/o2c.html")
          .autoApprove(true)
      .and()
          .withClient("*****-???????")
          .secret("????????????????????")
          .authorizedGrantTypes("password", "authorization_code", "refresh_token")
          .authorities("ROLE_USER", "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
          .scopes("play", "trust")
          .redirectUris("https://www.runscope.com/oauth_tool/callback")
          .autoApprove(true);
  
      return serviceConfig.clientDetailsService();
  }
  
  @Bean
  public TokenStore tokenStore() {
      return new InMemoryTokenStore();
  }
  
  @Bean
  public DefaultTokenServices tokenServices() throws Exception {
      DefaultTokenServices tokenServices = new DefaultTokenServices();
      tokenServices.setAccessTokenValiditySeconds(6000);
      tokenServices.setClientDetailsService(clientDetailsService());
      tokenServices.setTokenEnhancer(new *****TokenEnhancer());
      tokenServices.setSupportRefreshToken(true);
      tokenServices.setTokenStore(tokenStore());
      return tokenServices;
  }
  
  @Bean
  public UserApprovalHandler userApprovalHandler() throws Exception {
      *****UserApprovalHandler handler = new *****UserApprovalHandler();
      handler.setApprovalStore(approvalStore());
      handler.setClientDetailsService(clientDetailsService());
      handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService()));
      return handler;
  }
  
  @Bean
  public ApprovalStore approvalStore() {
      TokenApprovalStore store = new TokenApprovalStore();
      store.setTokenStore(tokenStore());
      return store;
  }
  
  @Bean
  public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
      return new OAuth2AccessDeniedHandler();
  }
  
  
  @Configuration
  @Order(Ordered.HIGHEST_PRECEDENCE)
  @EnableWebSecurity
  protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      private DataSource dataSource;
  
      @Resource
      private PasswordEncoder passwordEncoder;
  
      @Autowired
      private ClientDetailsService clientDetailsService;
  
      @Autowired
      private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
  
      @Bean
      protected UserDetailsService clientDetailsUserService() {
          return new ClientDetailsUserDetailsService(clientDetailsService);
      }
  
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  
          auth.userDetailsService(clientDetailsUserService());
  
          JdbcUserDetailsManagerConfigurer&lt;AuthenticationManagerBuilder&gt; jdbcUserDetail = new JdbcUserDetailsManagerConfigurer&lt;AuthenticationManagerBuilder&gt;();
          jdbcUserDetail.dataSource(dataSource);
          jdbcUserDetail.passwordEncoder(passwordEncoder);
          jdbcUserDetail.authoritiesByUsernameQuery("select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
          jdbcUserDetail.usersByUsernameQuery("select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
  
          auth.apply(jdbcUserDetail);
      }
  
      @Bean(name="authenticationManager")
      @Override
      public AuthenticationManager authenticationManagerBean() throws Exception {
          return super.authenticationManagerBean();
      }
  
      @Bean
      protected AuthenticationEntryPoint authenticationEntryPoint() {
          OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
          entryPoint.setTypeName("Basic");
          entryPoint.setRealmName("oauth2/client");
          return entryPoint;
      }
  
      @Override
      public void configure(WebSecurity webSecurity) throws Exception {
          webSecurity
              .ignoring()
              .antMatchers("/index.html", "/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
          .and()
              .debug(true);
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          // @formatter:off
          http.anonymous().disable()
              .antMatcher("/oauth/token")
              .authorizeRequests().anyRequest().authenticated()
          .and()
              .httpBasic().authenticationEntryPoint(authenticationEntryPoint())
          .and()
              .csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/token")).disable()
              .exceptionHandling().accessDeniedHandler(oAuth2AccessDeniedHandler)
          .and()
              .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
          // @formatter:on
      }
  
  }
  
  @Configuration
  @EnableResourceServer
  protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  
      @Autowired
      private ResourceServerTokenServices tokenServices;
  
      @Autowired
      private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
  
      @Override
      public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
          resources.tokenServices(tokenServices);
          resources.resourceId("*****");
      }
  
  
      @Override
      public void configure(HttpSecurity http) throws Exception {
  
          // @formatter:off
          http
              .anonymous()
              .disable();
  
          // API calls
          http
              .authorizeRequests()
              .regexMatchers(HttpMethod.POST, "/api/.*/accounts")
              .access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
          .and()
          //.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
              .sessionManagement()
              .sessionCreationPolicy(SessionCreationPolicy.NEVER)
          .and()
              .exceptionHandling()
              .accessDeniedHandler(oAuth2AccessDeniedHandler);
  
          // API calls
          http
              .authorizeRequests()
              .antMatchers("/api/**")
              .access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
          .and()
          //.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
              .sessionManagement()
              .sessionCreationPolicy(SessionCreationPolicy.NEVER)
          .and()
              .exceptionHandling()
              .accessDeniedHandler(oAuth2AccessDeniedHandler);
          // @formatter:on
      }
  
  
  }
  
  @Configuration
  @EnableAuthorizationServer
  protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  
      @Autowired
      private DataSource dataSource;
  
      @Autowired
      private DefaultTokenServices tokenServices;
  
      @Autowired
      private ClientDetailsService clientDetailsService;
  
      @Autowired
      private UserApprovalHandler userApprovalHandler;
  
      @Override
      public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
          endpoints.clientDetailsService(clientDetailsService)
          .tokenServices(tokenServices)
          .userApprovalHandler(userApprovalHandler);
      }
  
  }
  }
  </code></pre>
  
  <p>Adding more info on this (per Dave Syer's question)</p>
  
  <p>Doesn't generate token, see below for more information.</p>
  
  <p>Request:</p>
  
  <pre><code>curl -k -i -H "Accept: application/json" -X POST -d "grant_type=password&amp;client_id=*****-php-demo&amp;client_secret=???????&amp;scope=play trust&amp;username=tester&amp;password=121212" https://localhost:8443/*****/oauth/token
  </code></pre>
  
  <p>Response:</p>
  
  <pre><code>HTTP/1.1 401 Unauthorized
  Server: Apache-Coyote/1.1
  X-Content-Type-Options: nosniff
  X-XSS-Protection: 1; mode=block
  Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  Pragma: no-cache
  Expires: 0
  Strict-Transport-Security: max-age=31536000 ; includeSubDomains
  X-Frame-Options: DENY
  Cache-Control: no-store
  Pragma: no-cache
  WWW-Authenticate: Basic realm="*****/client", error="unauthorized", error_description="An Authentication object was not found in the SecurityContext"
  Content-Type: application/json;charset=UTF-8
  Transfer-Encoding: chunked
  Date: Tue, 16 Sep 2014 14:05:19 GMT
  </code></pre>
  
  <p>{"error":"unauthorized","error_description":"An Authentication object was not found in the SecurityContext"}</p>
  
  <p>Server log:</p>
  
  <pre><code>Request received for POST '/oauth/token':
  
  org.apache.catalina.connector.RequestFacade@344dad0c
  
  servletPath:
  pathInfo:/oauth/token
  headers: 
  user-agent: curl/7.30.0
  host: localhost:8443
  accept: application/json
  content-length: 145
  content-type: application/x-www-form-urlencoded
  
  
  Security filter chain: [
    WebAsyncManagerIntegrationFilter
    SecurityContextPersistenceFilter
    HeaderWriterFilter
    LogoutFilter
    BasicAuthenticationFilter
    RequestCacheAwareFilter
    SecurityContextHolderAwareRequestFilter
    SessionManagementFilter
    ExceptionTranslationFilter
    FilterSecurityInterceptor
  ]
  </code></pre>
  
  <p>(Update Oct 14)</p>
  
  <p>Java security configuration;</p>
  
  <pre><code>    @Configuration
  public class SecurityConfig {
  
      @Autowired
      private DataSource dataSource;
  
      @Value("${baseUrl}") private String baseUrl;
  
      @Bean
      public ClientDetailsService clientDetailsService() throws Exception {
          ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
  
          serviceConfig.clientDetailsServiceConfigurer().inMemory()
              .withClient("abc")
              .secret("?????")
              .authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
              .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
              .scopes("play", "trust")
          .and()
              .withClient("xyz")
              .authorizedGrantTypes("implicit")
              .authorities("ROLE_USER", "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
              .scopes("play", "trust")
              .redirectUris(baseUrl + "/o2c.html")
              .autoApprove(true)
          .and()
              .withClient("zzz")
              .secret("?????????????????")
              .authorizedGrantTypes("password", "authorization_code", "refresh_token")
              .authorities("ROLE_USER", "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
              .scopes("play", "trust")
              .redirectUris("https://www.runscope.com/oauth_tool/callback")
              .autoApprove(true);
  
          return serviceConfig.clientDetailsService();
      }
  
      @Bean
      public TokenStore tokenStore() {
          return new InMemoryTokenStore();
      }
  
      @Bean
      public DefaultTokenServices tokenServices() throws Exception {
          DefaultTokenServices tokenServices = new DefaultTokenServices();
          tokenServices.setAccessTokenValiditySeconds(6000);
          tokenServices.setClientDetailsService(clientDetailsService());
          tokenServices.setTokenEnhancer(new MyTokenEnhancer());
          tokenServices.setSupportRefreshToken(true);
          tokenServices.setTokenStore(tokenStore());
          return tokenServices;
      }
  
      @Bean
      public UserApprovalHandler userApprovalHandler() throws Exception {
          MyUserApprovalHandler handler = new MyUserApprovalHandler();
          handler.setApprovalStore(approvalStore());
          handler.setClientDetailsService(clientDetailsService());
          handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService()));
          return handler;
      }
  
      @Bean
      public ApprovalStore approvalStore() {
          TokenApprovalStore store = new TokenApprovalStore();
          store.setTokenStore(tokenStore());
          return store;
      }
  
      @Bean
      public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
          return new OAuth2AccessDeniedHandler();
      }
  
      @Configuration
      @Order(Ordered.HIGHEST_PRECEDENCE)
      @EnableWebSecurity
      protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  
          @Autowired
          private DataSource dataSource;
  
          @Resource
          private PasswordEncoder passwordEncoder;
  
          @Autowired
          private ClientDetailsService clientDetailsService;
  
          @Autowired
          private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
  
          @Bean
          protected UserDetailsService clientDetailsUserService() {
              return new ClientDetailsUserDetailsService(clientDetailsService);
          }
  
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  
              JdbcUserDetailsManagerConfigurer&lt;AuthenticationManagerBuilder&gt; jdbcUserDetail = new JdbcUserDetailsManagerConfigurer&lt;AuthenticationManagerBuilder&gt;();
              jdbcUserDetail.dataSource(dataSource);
              jdbcUserDetail.passwordEncoder(passwordEncoder);
              jdbcUserDetail.authoritiesByUsernameQuery("select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
              jdbcUserDetail.usersByUsernameQuery("select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
  
              auth.apply(jdbcUserDetail);
          }
  
          @Bean(name="authenticationManager")
          @Override
          public AuthenticationManager authenticationManagerBean() throws Exception {
              AuthenticationManager am = super.authenticationManagerBean();
              return am; 
          }
  
          @Bean
          protected AuthenticationEntryPoint authenticationEntryPoint() {
              OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
              entryPoint.setTypeName("Basic");
              entryPoint.setRealmName("redrum/client");
              return entryPoint;
          }
  
          @Override
          public void configure(WebSecurity webSecurity) throws Exception {
              webSecurity
                  .ignoring()
                  .antMatchers("/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
              .and()
                  .debug(true);
          }
  
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              // @formatter:off
              http.anonymous().disable()
                  .antMatcher("/oauth/token")
                  .authorizeRequests().anyRequest().authenticated()
              .and()
                  .httpBasic().authenticationEntryPoint(authenticationEntryPoint())
              .and()
                  .csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/token")).disable()
                  .exceptionHandling().accessDeniedHandler(oAuth2AccessDeniedHandler)
              .and()
                  .addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
                  .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
              // @formatter:on
          }
  
          @Bean
          public ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() throws Exception {
              ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
              filter.setAuthenticationEntryPoint(authenticationEntryPoint());
              filter.setAuthenticationManager(authenticationManagerBean());
              return filter;
          }
  
      }
  
      @Configuration
      @EnableResourceServer
      protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  
          @Autowired
          private ResourceServerTokenServices tokenServices;
  
          @Autowired
          private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
  
          @Autowired
          private AuthenticationManager authenticationManager;
  
          @Override
          public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
              resources.tokenServices(tokenServices);
              resources.resourceId("xyz");
          }
  
          @Override
          public void configure(HttpSecurity http) throws Exception {
  
              // @formatter:off
              http
                  .anonymous()
                  .disable();
  
              // API calls
              http
                  .authorizeRequests()
                  .regexMatchers(HttpMethod.POST, "/api/.*/accounts")
                  .access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
              .and()
                  //.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
                  .sessionManagement()
                  .sessionCreationPolicy(SessionCreationPolicy.NEVER)
              .and()
                  .exceptionHandling()
                  .accessDeniedHandler(oAuth2AccessDeniedHandler);
  
              // API calls
              http
                  .authorizeRequests()
                  .antMatchers("/api/**")
                  .access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
              .and()
                  //.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
                  .sessionManagement()
                  .sessionCreationPolicy(SessionCreationPolicy.NEVER)
              .and()
                  .exceptionHandling()
                  .accessDeniedHandler(oAuth2AccessDeniedHandler);
              // @formatter:on
          }
  
  
      }
  
      @Configuration
      @EnableAuthorizationServer
      protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  
          @Autowired
          private DataSource dataSource;
  
          @Autowired
          private DefaultTokenServices tokenServices;
  
          @Autowired
          private ClientDetailsService clientDetailsService;
  
          @Autowired
          private UserApprovalHandler userApprovalHandler;
  
          @Override
          public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
              endpoints.clientDetailsService(clientDetailsService)
              .tokenServices(tokenServices)
              .userApprovalHandler(userApprovalHandler);
          }
  
      }
  }
  </code></pre>