title: Spring OAuth2 - Can't get client token
body: <p>I'm not 100% sure I'm performing the correct request but I can't seem to get a token for a client. I've based my solution off of this tutorial <a href="https://techannotation.wordpress.com/2014/04/29/5-minutes-with-spring-oauth-2-0/" rel="nofollow">5 minutes with spring oauth 2.0</a>.</p>
  
  <p>I'm performing this request from postman: </p>
  
  <blockquote>
    <p>/oauth/token?grant_type=client_credentials&amp;client_id=mysupplycompany&amp;client_secret=mycompanyk</p>
  </blockquote>
  
  <p>That request responds with an exception: </p>
  
  <blockquote>
    <p>org.springframework.security.authentication.InsufficientAuthenticationException:
    There is no client authentication. Try adding an appropriate
    authentication filter.
      org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(TokenEndpoint.java:91)</p>
  </blockquote>
  
  <p>Below are some files/classes you may need to help me figure out any issues.</p>
  
  <p><strong>WebInitializer</strong></p>
  
  <pre><code>package com.squirrels.config;
  
  import javax.servlet.ServletContext;
  import javax.servlet.ServletException;
  import javax.servlet.ServletRegistration.Dynamic;
  
  import org.springframework.web.WebApplicationInitializer;
  import org.springframework.web.context.ContextLoaderListener;
  import org.springframework.web.context.WebApplicationContext;
  import org.springframework.web.context.request.RequestContextListener;
  import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
  import org.springframework.web.filter.DelegatingFilterProxy;
  import org.springframework.web.servlet.DispatcherServlet;
  
  public class WebInitializer implements WebApplicationInitializer {
  
      public void onStartup(ServletContext servletContext) throws ServletException {          
          WebApplicationContext context = getContext();
          servletContext.addListener(new ContextLoaderListener(context));
          servletContext.addListener(new RequestContextListener());    
  
          Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));  
          servlet.addMapping("/");  
          servlet.setLoadOnStartup(1);  
  
          DelegatingFilterProxy filter = new DelegatingFilterProxy("springSecurityFilterChain");
          filter.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
          servletContext.addFilter("springSecurityFilterChain", filter).addMappingForUrlPatterns(null, false, "/*");
      }  
  
      private AnnotationConfigWebApplicationContext getContext() {
          AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
          context.setConfigLocation("com.squirrels.config");
          return context;
      }
  
  }
  </code></pre>
  
  <p><strong>PersistenceJPAConfig</strong></p>
  
  <pre><code>package com.squirrels.config;
  
  import java.util.Properties;
  
  import javax.persistence.EntityManagerFactory;
  import javax.sql.DataSource;
  
  import liquibase.integration.spring.SpringLiquibase;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.context.annotation.Bean;
  import org.springframework.context.annotation.ComponentScan;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.context.annotation.ImportResource;
  import org.springframework.context.annotation.PropertySource;
  import org.springframework.core.env.Environment;
  import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
  import org.springframework.jdbc.datasource.DriverManagerDataSource;
  import org.springframework.orm.jpa.JpaTransactionManager;
  import org.springframework.orm.jpa.JpaVendorAdapter;
  import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
  import org.springframework.transaction.PlatformTransactionManager;
  import org.springframework.transaction.annotation.EnableTransactionManagement;
  
  @Configuration
  @EnableTransactionManagement
  @ComponentScan({ "com.squirrels.controller", "com.squirrels.services", "com.squirrels.persistence.dao", "com.squirrels.auth" })
  @PropertySource(value = { "classpath:squirrel.properties" })
  @ImportResource("classpath:spring-security.xml")
  public class PersistenceJPAConfig {
  
      @Autowired
      private Environment environment;
  
      @Bean
      public SpringLiquibase liquibase() {
          SpringLiquibase liquibase = new SpringLiquibase();
          liquibase.setDataSource(dataSource());
          liquibase.setDefaultSchema(environment.getRequiredProperty("db_schema"));
          liquibase.setChangeLog("classpath:/db/changelog/db.changelog-master.xml");
  
          return liquibase;
      }
  
      @Bean
      public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
          LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
          em.setDataSource(dataSource());
          em.setPersistenceUnitName("SquirrelAuth");
          em.setPackagesToScan(new String[] { "com.squirrels.persistence.model" });
  
          JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
          em.setJpaVendorAdapter(vendorAdapter);
          em.setJpaProperties(additionalProperties());
  
          return em;
      }
  
      @Bean
      public DataSource dataSource() {
          DriverManagerDataSource dataSource = new DriverManagerDataSource();
          dataSource.setDriverClassName(environment.getRequiredProperty("db_driverClass"));
          dataSource.setUrl(environment.getRequiredProperty("db_jdbcUrl"));
          dataSource.setUsername(environment.getRequiredProperty("db_user"));
          dataSource.setPassword(environment.getRequiredProperty("db_password"));
          return dataSource;
      }
  
      @Bean
      public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
          JpaTransactionManager transactionManager = new JpaTransactionManager();
          transactionManager.setEntityManagerFactory(emf);
  
          return transactionManager;
      }
  
      @Bean
      public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
          return new PersistenceExceptionTranslationPostProcessor();
      }
  
      Properties additionalProperties() {
          Properties properties = new Properties();
          properties.setProperty("hibernate.dialect", environment.getRequiredProperty("db_hibernateDialect"));
          return properties;
      }
  
  
  }
  </code></pre>
  
  <p><strong>security-spring.xml</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
      xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
      xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
          http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
          http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"&gt;
  
  
      &lt;sec:http pattern="/oauth/token" create-session="stateless"
          authentication-manager-ref="authenticationManager"&gt;
          &lt;sec:intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" /&gt;
          &lt;sec:anonymous enabled="false" /&gt;
          &lt;sec:http-basic entry-point-ref="clientAuthenticationEntryPoint" /&gt;
          &lt;sec:custom-filter ref="clientCredentialsTokenEndpointFilter"
              before="BASIC_AUTH_FILTER" /&gt;
          &lt;sec:access-denied-handler ref="oauthAccessDeniedHandler" /&gt;
      &lt;/sec:http&gt;
  
      &lt;sec:http pattern="/api/**" create-session="never"
          entry-point-ref="oauthAuthenticationEntryPoint"&gt;
          &lt;sec:anonymous enabled="false" /&gt;
          &lt;sec:intercept-url pattern="/api/**" method="GET"
              access="IS_AUTHENTICATED_FULLY" /&gt;
          &lt;sec:custom-filter ref="resourceServerFilter"
              before="PRE_AUTH_FILTER" /&gt;
          &lt;sec:access-denied-handler ref="oauthAccessDeniedHandler" /&gt;
      &lt;/sec:http&gt;
  
      &lt;bean id="oauthAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"&gt;
      &lt;/bean&gt;
  
      &lt;bean id="clientAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"&gt;
          &lt;property name="realmName" value="springsec/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&gt;
  
      &lt;bean id="clientCredentialsTokenEndpointFilter"
          class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"&gt;
          &lt;property name="authenticationManager" ref="authenticationManager" /&gt;
      &lt;/bean&gt;
  
      &lt;sec:authentication-manager alias="authenticationManager"&gt;
          &lt;sec:authentication-provider
              user-service-ref="clientDetailsUserService" /&gt;
      &lt;/sec: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="clientDetails" class="com.squirrels.auth.OAuthClientDetailsImpl"&gt;
          &lt;property name="id" value="mysupplycompany" /&gt;
          &lt;property name="secretKey" value="mycompanykey" /&gt;
      &lt;/bean&gt;
  
      &lt;sec:authentication-manager id="userAuthenticationManager"&gt;
          &lt;sec:authentication-provider ref="customUserAuthenticationProvider" /&gt;
      &lt;/sec:authentication-manager&gt;
  
      &lt;bean id="customUserAuthenticationProvider" class="com.squirrels.auth.OAuthAuthenticationProvider"&gt;
      &lt;/bean&gt;
  
      &lt;oauth:authorization-server
          client-details-service-ref="clientDetails" token-services-ref="tokenServices"&gt;
          &lt;oauth:authorization-code /&gt;
          &lt;oauth:implicit /&gt;
          &lt;oauth:refresh-token /&gt;
          &lt;oauth:client-credentials /&gt;
          &lt;oauth:password authentication-manager-ref="userAuthenticationManager" /&gt;
      &lt;/oauth:authorization-server&gt;
  
      &lt;oauth:resource-server id="resourceServerFilter"
          resource-id="springsec" token-services-ref="tokenServices" /&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="supportRefreshToken" value="true" /&gt;
          &lt;property name="accessTokenValiditySeconds" value="120"&gt;&lt;/property&gt;
          &lt;property name="clientDetailsService" ref="clientDetails" /&gt;
      &lt;/bean&gt;
  
      &lt;mvc:annotation-driven /&gt;
  &lt;/beans&gt;
  </code></pre>
  
  <p><strong>OAuthAuthenticationProvider</strong></p>
  
  <pre><code>package com.squirrels.auth;
  
  import java.util.ArrayList;
  import java.util.List;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.security.authentication.AuthenticationProvider;
  import org.springframework.security.authentication.BadCredentialsException;
  import org.springframework.security.core.Authentication;
  import org.springframework.security.core.AuthenticationException;
  import org.springframework.security.core.GrantedAuthority;
  
  public class OAuthAuthenticationProvider implements AuthenticationProvider {
  
      @Autowired
      private OAuthProxy proxy;
  
      @Override
      public Authentication authenticate(Authentication authentication) throws AuthenticationException {
          boolean result = proxy.isValidUser("1", authentication.getPrincipal().toString(), authentication.getCredentials().toString());
  
          if (result) {
              List&lt;GrantedAuthority&gt; grantedAuthorities =
  
              new ArrayList&lt;GrantedAuthority&gt;();
              OAuthAuthenticationToken auth = new OAuthAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);
  
              return auth;
          } else {
              throw new BadCredentialsException("Bad User Credentials.");
          }
      }
  
      @Override
      public boolean supports(Class&lt;?&gt; arg0) {
          return true;
      }
  
  }
  </code></pre>
  
  <p><strong>WebMvcConfig</strong></p>
  
  <pre><code>package com.squirrels.config;
  
  import java.util.ArrayList;
  import java.util.List;
  
  import org.springframework.context.annotation.Bean;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.web.accept.ContentNegotiationManager;
  import org.springframework.web.servlet.ViewResolver;
  import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
  import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
  
  @Configuration
  @EnableWebMvc
  public class WebMvcConfig extends WebMvcConfigurerAdapter {
  
  
      @Override
      public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
          configurer.enable();
      };
  
      /*
       * Configure ContentNegotiatingViewResolver
       */
      @Bean
      public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
          ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
          resolver.setContentNegotiationManager(manager);
  
          // Define all possible view resolvers
          List&lt;ViewResolver&gt; resolvers = new ArrayList&lt;ViewResolver&gt;();
          resolvers.add(jsonViewResolver());         
          resolver.setViewResolvers(resolvers);
          return resolver;
      }
  
      /*
       * Configure View resolver to provide JSON output using JACKSON library to
       * convert object in JSON format.
       */
      @Bean
      public ViewResolver jsonViewResolver() {
          return new JsonViewResolver();
      }
  
  }
  </code></pre>
  
  <p><strong>OAuthenticationToken</strong></p>
  
  <pre><code>package com.squirrels.auth;
  
  import java.util.Collection;
  
  import org.springframework.security.authentication.AbstractAuthenticationToken;
  import org.springframework.security.core.GrantedAuthority;
  
  public class OAuthAuthenticationToken extends AbstractAuthenticationToken {
  
      private static final long serialVersionUID = -1092219614309982278L;
      private final Object principal;
      private Object credentials;
  
      public OAuthAuthenticationToken(Object principal, Object credentials,
              Collection&lt;? extends GrantedAuthority&gt; authorities) {
          super(authorities);
          this.principal = principal;
          this.credentials = credentials;
          super.setAuthenticated(true);
      }
  
      @Override
      public Object getCredentials() {
          return credentials;
      }
  
      @Override
      public Object getPrincipal() {
          return principal;
      }
  
  }
  </code></pre>
  
  <p><strong>OAuthClientDetailsImpl</strong></p>
  
  <pre><code>package com.squirrels.auth;
  
  import java.util.ArrayList;
  import java.util.List;
  
  import org.springframework.security.oauth2.provider.ClientDetails;
  import org.springframework.security.oauth2.provider.ClientDetailsService;
  import org.springframework.security.oauth2.provider.ClientRegistrationException;
  import org.springframework.security.oauth2.provider.NoSuchClientException;
  import org.springframework.security.oauth2.provider.client.BaseClientDetails;
  
  public class OAuthClientDetailsImpl implements ClientDetailsService {
  
      private String id;
      private String secretKey;
  
      @Override
      public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
          if (clientId.equals(id))
          {
              List&lt;String&gt; authorizedGrantTypes = new ArrayList&lt;String&gt;();
              authorizedGrantTypes.add("password");
              authorizedGrantTypes.add("refresh_token");
              authorizedGrantTypes.add("client_credentials");
  
              BaseClientDetails clientDetails = new BaseClientDetails();
              clientDetails.setClientId(id);
              clientDetails.setClientSecret(secretKey);
              clientDetails.setAuthorizedGrantTypes(authorizedGrantTypes);
  
              return clientDetails;
          }
          else {
              throw new NoSuchClientException("No client recognized with id: " + clientId);
          }
      }
  
      public String getId() {
          return id;
      }
  
      public void setId(String id) {
          this.id = id;
      }
  
      public String getSecretKey() {
          return secretKey;
      }
  
      public void setSecretKey(String secretKey) {
          this.secretKey = secretKey;
      }
  
  }
  </code></pre>
  
  <p><strong>OAuthProxy</strong></p>
  
  <pre><code>package com.squirrels.auth;
  
  import org.apache.logging.log4j.LogManager;
  import org.apache.logging.log4j.Logger;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Service;
  import org.springframework.transaction.annotation.Transactional;
  
  import com.squirrels.dto.UserDTO;
  import com.squirrels.persistence.dao.UserDao;
  import com.squirrels.persistence.model.UserModel;
  import com.squirrels.services.UserUtil;
  
  
  @Service
  public class OAuthProxy {
  
      protected static final Logger logger = LogManager.getLogger(OAuthProxy.class);
  
      @Autowired
      private UserDao userDaoImpl;
  
      @Autowired
      private UserUtil userUtil;  
  
      @Transactional
      public boolean isValidUser(String organizationId, String username, String password) {
  
          try{
              UserModel user = userDaoImpl.findByOrganizationAndUserName(organizationId, username);
              UserDTO userDto = userUtil.getDTO(user);
  
              //TODO validate password (or other means of auth)
  
              return true;            
          }catch(Exception e){
              logger.error("No user: " + username + " found in organization: " + organizationId, e);
          }
  
          return false;
      }
  
  }
  </code></pre>