How to configure Spring Security + OAuth2
<p>I'm building a REST Application using Spring Security + OAuth2. </p>

<p>If i use </p>

<pre><code>curl -u clientapp:123456 -X POST http://localhost:8080/oauth/token -H "Accept:application/json" -d "username=admin&amp;password=123456&amp;grant_type=password"
</code></pre>

<p>I do not get the response</p>

<p>But if i add the application contextpath i am able to.</p>

<pre><code>curl -u clientapp:123456 -X POST http://localhost:8080/demoproject/oauth/token -H "Accept:application/json" -d "username=admin&amp;password=123456&amp;grant_type=password"
</code></pre>

<p>Also getting success response</p>

<pre><code>{"access_token":"dc86814f-94a5-43b7-9e8d-73b143b28c64","token_type":"bearer","re
fresh_token":"09c7e31e-b8e7-4bf2-a839-9e8d4702b822","expires_in":2837,"scope":"r
ead write"}
</code></pre>

<p>But when use the access token to request a secured API, I'm getting login page as response because of Spring Security Configuration.</p>

<p>Here is my Configration:</p>

<p>WebMvcInitializer.java</p>

<pre><code>import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class&lt;?&gt;[] getRootConfigClasses() {
        return new Class[] { 
                WebConfig.class, 
                WebSecurityConfiguration.class, 
                Oauth2ServerConfiguration.AuthConfig.class };
    }

    @Override
    protected Class&lt;?&gt;[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}
</code></pre>

<p>WebSecurityConfiguration .java</p>

<pre><code>  @Configuration
    @EnableWebSecurity
    @EnableWebMvcSecurity
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

         @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("admin").password("123456").roles("USER", "ADMIN");
        }

        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

        @Bean
        public PasswordEncoder passwordEncoder() {
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            return encoder;
        }

        @Override
         protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().hasRole("USER"); 
            //super.configure(http);
        }
    }
</code></pre>

<p>WebConfig.java</p>

<pre><code> @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = "edu.demo.springoauth")  
    public class WebConfig extends WebMvcConfigurerAdapter {

        @Bean
        public ViewResolver viewResolver() {
            InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
            viewResolver.setViewClass(JstlView.class);
            viewResolver.setPrefix("/WEB-INF/views/");
            viewResolver.setSuffix(".jsp");

            return viewResolver;
        }


        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**").addResourceLocations("/static/");
        } 
    }
</code></pre>

<p>SecurityInitializer.java</p>

<pre><code> import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;  
            public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {

            }
</code></pre>

<p>Oauth2ServerConfiguration.java </p>

<pre><code>  @Configuration
    public class Oauth2ServerConfiguration {

        private static final String SERVER_RESOURCE_ID = "oauthdemo";

        private static InMemoryTokenStore tokenStore = new InMemoryTokenStore();

        @Configuration
        @EnableResourceServer
        protected static class ResourceServer extends ResourceServerConfigurerAdapter {

            @Override
            public void configure(ResourceServerSecurityConfigurer resources) throws Exception { 
                resources.resourceId(SERVER_RESOURCE_ID);
            }

            @Override
            @Order(Ordered.HIGHEST_PRECEDENCE)
            public void configure(HttpSecurity http) throws Exception {


                http.requestMatchers().antMatchers("/oauth/**" , "/noauth/**" , "/api/r/**")
                .and()
                .authorizeRequests().antMatchers("/api/w/**").hasAuthority("ROLE_USER"); 


}
        }



        @Configuration
        @EnableAuthorizationServer
        protected static class AuthConfig extends AuthorizationServerConfigurerAdapter {

            @Autowired
            @Qualifier("authenticationManagerBean")
            private AuthenticationManager authenticationManager;

            @Override
            public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
                oauthServer.allowFormAuthenticationForClients();
            }

            @Override
            public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
                endpoints.authenticationManager(authenticationManager);
            }

            @Override
            public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
                clients.inMemory().withClient("clientapp").authorizedGrantTypes("password","client_credentials", "authorization_code", "refresh_token", "implicit")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT", "ROLE_USER")
                        .scopes("read", "write").resourceIds(SERVER_RESOURCE_ID).secret("123456").accessTokenValiditySeconds(3600);
            }

            @Bean
            @Primary
            public DefaultTokenServices tokenServices() {
                DefaultTokenServices tokenServices = new DefaultTokenServices();
                tokenServices.setSupportRefreshToken(true);
                tokenServices.setTokenStore(tokenStore);
                return tokenServices;
            }
        }
    }
</code></pre>

<p><strong>Pom.xml</strong></p>

<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;groupId&gt;edu.demo&lt;/groupId&gt;
    &lt;artifactId&gt;springoauth&lt;/artifactId&gt;
    &lt;name&gt;springoauth&lt;/name&gt;
    &lt;packaging&gt;war&lt;/packaging&gt;
    &lt;version&gt;1.0.0-BUILD-SNAPSHOT&lt;/version&gt;
    &lt;properties&gt;
        &lt;build.profile.id&gt;dev&lt;/build.profile.id&gt;
        &lt;java-version&gt;1.8&lt;/java-version&gt;

        &lt;spring.security.oauth2.version&gt;2.0.1.RELEASE&lt;/spring.security.oauth2.version&gt;
        &lt;spring-security.version&gt;3.2.4.RELEASE&lt;/spring-security.version&gt;
        &lt;spring.version&gt;4.0.5.RELEASE&lt;/spring.version&gt;


    &lt;/properties&gt;
    &lt;dependencyManagement&gt;
        &lt;dependencies&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.springframework&lt;/groupId&gt;
                &lt;artifactId&gt;spring-framework-bom&lt;/artifactId&gt;
                &lt;version&gt;${spring.version}&lt;/version&gt;
                &lt;type&gt;pom&lt;/type&gt;
                &lt;scope&gt;import&lt;/scope&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;
    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;junit&lt;/groupId&gt;
            &lt;artifactId&gt;junit&lt;/artifactId&gt;
            &lt;version&gt;3.8.1&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
            &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
            &lt;version&gt;1.7.7&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
            &lt;artifactId&gt;spring-security-web&lt;/artifactId&gt;
            &lt;version&gt;${spring-security.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
            &lt;artifactId&gt;spring-security-core&lt;/artifactId&gt;
            &lt;version&gt;${spring-security.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
            &lt;artifactId&gt;spring-security-config&lt;/artifactId&gt;
            &lt;version&gt;${spring-security.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.security.oauth&lt;/groupId&gt;
            &lt;artifactId&gt;spring-security-oauth2&lt;/artifactId&gt;
            &lt;version&gt;${spring.security.oauth2.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt;
            &lt;artifactId&gt;jackson-mapper-asl&lt;/artifactId&gt;
            &lt;version&gt;1.9.13&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-tx&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-orm&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt;
            &lt;artifactId&gt;tomcat-dbcp&lt;/artifactId&gt;
            &lt;version&gt;7.0.47&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-orm&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
            &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
            &lt;version&gt;4.1.8.Final&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;mysql&lt;/groupId&gt;
            &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
            &lt;version&gt;5.1.22&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
    &lt;profiles&gt;
        &lt;profile&gt;
            &lt;id&gt;dev&lt;/id&gt;
            &lt;properties&gt;
                &lt;build.profile.id&gt;dev&lt;/build.profile.id&gt;
            &lt;/properties&gt;
        &lt;/profile&gt;
    &lt;/profiles&gt;
    &lt;build&gt;
        &lt;finalName&gt;springoauth&lt;/finalName&gt;
        &lt;filters&gt;
            &lt;filter&gt;profiles/${build.profile.id}/config.properties&lt;/filter&gt;
        &lt;/filters&gt;
        &lt;resources&gt;
            &lt;resource&gt;
                &lt;filtering&gt;true&lt;/filtering&gt;
                &lt;directory&gt;src/main/resources&lt;/directory&gt;
                &lt;excludes&gt;
                    &lt;exclude&gt;**/messages*.properties&lt;/exclude&gt;
                &lt;/excludes&gt;
            &lt;/resource&gt;
            &lt;resource&gt;
                &lt;filtering&gt;false&lt;/filtering&gt;
                &lt;directory&gt;src/main/resources&lt;/directory&gt;
                &lt;includes&gt;
                    &lt;include&gt;**/messages*.properties&lt;/include&gt;
                &lt;/includes&gt;
            &lt;/resource&gt;
        &lt;/resources&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;artifactId&gt;maven-eclipse-plugin&lt;/artifactId&gt;
                &lt;version&gt;2.9&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;additionalProjectnatures&gt;
                        &lt;projectnature&gt;org.springframework.ide.eclipse.core.springnature&lt;/projectnature&gt;
                    &lt;/additionalProjectnatures&gt;
                    &lt;additionalBuildcommands&gt;
                        &lt;buildcommand&gt;org.springframework.ide.eclipse.core.springbuilder&lt;/buildcommand&gt;
                    &lt;/additionalBuildcommands&gt;
                    &lt;downloadSources&gt;true&lt;/downloadSources&gt;
                    &lt;downloadJavadocs&gt;true&lt;/downloadJavadocs&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
                &lt;version&gt;2.5.1&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;source&gt;${java-version}&lt;/source&gt;
                    &lt;target&gt;${java-version}&lt;/target&gt;
                    &lt;compilerArgument&gt;-Xlint:all&lt;/compilerArgument&gt;
                    &lt;showWarnings&gt;true&lt;/showWarnings&gt;
                    &lt;showDeprecation&gt;true&lt;/showDeprecation&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
                &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;1.2.1&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;mainClass&gt;org.test.int1.Main&lt;/mainClass&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;
                &lt;configuration&gt;
                    &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;
&lt;/project&gt;
</code></pre>

<p>Is there something in spring configuration that I'm doing wrong?</p>