title: Redirecting to login page instead of returning a token
body: <p>I am implementing OAuth 2 using <code>Spring Security 3.2</code> and <code>Spring Security OAuth 1.0.5</code>. It worked with an xml-based configuration. Now I try to migrate to java-based configuration and I'm facing the problem that instead of returning a token, it redirected me to login page! Below are the configurations:</p>
  
  <p><strong>SecurityInitializer.java</strong></p>
  
  <pre class="lang-java prettyprint-override"><code>public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
  
      /**
       * This class configure spring security
       * 
       * @author tuan.dang
       * 
       */
      @Configuration
      @EnableWebMvcSecurity
      @Order
      public static class SecurityConfig extends WebSecurityConfigurerAdapter {
  
          @Autowired
          private DBAuthenticationProvider dbAuthenticationProvider;
          @Autowired
          private MyWebAuthenticationDetailsSource myWebAuthenticationDetailsSource;
  
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.authenticationProvider(dbAuthenticationProvider);
          }
  
          @Bean(name = "org.springframework.security.authenticationManager")
          @Override
          public AuthenticationManager authenticationManagerBean() throws Exception {
              return super.authenticationManagerBean();
          }
  
          @Override
          public void configure(WebSecurity web) throws Exception {
              // @formatter:off
              web.ignoring()
                  .antMatchers("/oauth/cache_approvals")
                  .antMatchers("/oauth/uncache_approvals");
              // @formatter:on
          }
  
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              // @formatter:off
              http
                  .authorizeRequests()
                      .anyRequest().authenticated()
                      .and()
                  .formLogin()
                      .loginPage("/login")
                      .loginProcessingUrl("/login-processing-url")
                      .usernameParameter("j_username")
                      .passwordParameter("j_password")
                      .authenticationDetailsSource(myWebAuthenticationDetailsSource)
                      .defaultSuccessUrl("/welcome")
                      .permitAll()
                      .and()
                  .logout()
                      .invalidateHttpSession(true)
                      .deleteCookies()
                      .logoutRequestMatcher(new AntPathRequestMatcher("/logout", RequestMethod.GET.name()))
                      .logoutSuccessUrl("/login")
                      .permitAll();
              // @formatter:on
          }
      }
  
      /**
       * 
       * @author tuan.dang
       * 
       */
      @Configuration
      @EnableWebMvcSecurity
      @Order(10)
      public static class AuthorizeServer extends WebSecurityConfigurerAdapter {
          @Autowired
          ClientDetailsService clientDetails;
  
          @Override
          protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.userDetailsService(new ClientDetailsUserDetailsService(clientDetails));
          }
  
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              // @formatter:off
              http
                  .requestMatchers()
                      .antMatchers("/oauth/token")
                      .and()
                  .sessionManagement()
                      .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                      .and()
                  .authorizeRequests()
                      .antMatchers("/oauth/token").authenticated()
                      .and()
                  .anonymous().disable()
                  .httpBasic()
                      .authenticationEntryPoint(getClientAuthenticationEntryPoint())
                      .and()
                  .addFilterAfter(getClientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
                  .addFilterBefore(new RequestContextFilter(), BasicAuthenticationFilter.class)
                  .exceptionHandling()
                      .accessDeniedHandler(new OAuth2AccessDeniedHandler());
              // @formatter:on
          }
  
          @Bean(name = "clientAuthenticationManager")
          @Override
          public AuthenticationManager authenticationManagerBean() throws Exception {
              return super.authenticationManagerBean();
          }
  
          private Filter getClientCredentialsTokenEndpointFilter() throws Exception {
              AbstractAuthenticationProcessingFilter filter = new ClientCredentialsTokenEndpointFilter();
              filter.setAuthenticationManager(authenticationManagerBean());
              return filter;
          }
  
          private AuthenticationEntryPoint getClientAuthenticationEntryPoint() {
              OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
              entryPoint.setTypeName("Basic");
              entryPoint.setRealmName("AuthorizationServer");
              return entryPoint;
          }
      }
  
  }
  </code></pre>
  
  <p><strong>WebInitializer.java</strong></p>
  
  <pre class="lang-java prettyprint-override"><code>public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  
      @Override
      protected Class&lt;?&gt;[] getRootConfigClasses() {
          return new Class[] { AppConfig.class };
      }
  
      @Override
      protected Class&lt;?&gt;[] getServletConfigClasses() {
          return new Class[] { WebAppConfig.class };
      }
  
      @Override
      protected String[] getServletMappings() {
          return new String[] { "/" };
      }
  
      /**
       * This class replaces dispatcher-servlet.xml file
       * 
       * @author tuan.dang
       * 
       */
      @Configuration
      @EnableWebMvc
      @ImportResource("classpath:oauth2/oauth2-config.xml")
      @ComponentScan(basePackages = { "net.dntuan.training.spring" })
      public static class WebAppConfig extends WebMvcConfigurerAdapter {
  
          /**
           * Configure an internalResouceViewResolver. This resolver is required to use Spring MVC with jsp view
           * 
           * @return InternalResourceViewResolver
           */
          @Bean
          public InternalResourceViewResolver configureInternalResourceViewResolver() {
              InternalResourceViewResolver resolver = new InternalResourceViewResolver();
              resolver.setPrefix("/WEB-INF/jsp/");
              resolver.setSuffix(".jsp");
              return resolver;
          }
  
          @Override
          public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
              configurer.enable();
          }
      }
  }
  </code></pre>
  
  <p>I tried to turn up logging, I got the following:</p>
  
  <pre><code>[DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/oauth/token'; against '/oauth/token' (AntPathRequestMatcher.java:145)
  [DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Secure object: FilterInvocation: URL: /oauth/token?client_id=epos-frontend&amp;grant_type=password&amp;username=user&amp;password=bypass&amp;app_id=3; Attributes: [authenticated] (AbstractSecurityInterceptor.java:194)
  [DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fea1daa6: Principal: org.springframework.security.core.userdetails.User@89854e50: Username: epos-frontend; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_APP_CLIENT; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_APP_CLIENT (AbstractSecurityInterceptor.java:310)
  [DEBUG] [org.springframework.security.access.vote.AffirmativeBased] - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@2868d4f8, returned: 1 (AffirmativeBased.java:65)
  [DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Authorization successful (AbstractSecurityInterceptor.java:215)
  [DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - RunAsManager did not change Authentication object (AbstractSecurityInterceptor.java:227)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - /oauth/token?client_id=epos-frontend&amp;grant_type=password&amp;username=user&amp;password=bypass&amp;app_id=3 reached end of additional filter chain; proceeding with original chain (FilterChainProxy.java:323)
  [DEBUG] [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'dispatcher' processing GET request for [/javabased-oauth2/oauth/token] (DispatcherServlet.java:843)
  [DEBUG] [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Looking up handler method for path /oauth/token (AbstractHandlerMethodMapping.java:222)
  [DEBUG] [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Returning handler method [public org.springframework.http.ResponseEntity&lt;org.springframework.security.oauth2.common.OAuth2AccessToken&gt; org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.getAccessToken(java.security.Principal,java.lang.String,java.util.Map&lt;java.lang.String, java.lang.String&gt;)] (AbstractHandlerMethodMapping.java:229)
  [DEBUG] [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'oauth2TokenEndpoint' (AbstractBeanFactory.java:249)
  [DEBUG] [org.springframework.web.servlet.DispatcherServlet] - Last-Modified value for [/javabased-oauth2/oauth/token] is: -1 (DispatcherServlet.java:932)
  [DEBUG] [org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter] - Getting access token for: epos-frontend (AbstractTokenGranter.java:59)
  [DEBUG] [org.springframework.security.authentication.ProviderManager] - Authentication attempt using net.dntuan.training.spring.security.DBAuthenticationProvider (ProviderManager.java:152)
  [DEBUG] [net.dntuan.training.spring.security.DBAuthenticationProvider] - entered username: user (DBAuthenticationProvider.java:40)
  [DEBUG] [net.dntuan.training.spring.security.DBAuthenticationProvider] - entered password: bypass (DBAuthenticationProvider.java:41)
  [DEBUG] [net.dntuan.training.spring.security.DBAuthenticationProvider] - appId: 3 (DBAuthenticationProvider.java:42)
  [DEBUG] [org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor] - Written [409d7529-2f54-4ec0-8439-3f2730e89e3c] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@510b6523] (AbstractMessageConverterMethodProcessor.java:150)
  [DEBUG] [org.springframework.web.servlet.DispatcherServlet] - Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling (DispatcherServlet.java:1019)
  [DEBUG] [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request (FrameworkServlet.java:961)
  [DEBUG] [org.springframework.security.web.access.ExceptionTranslationFilter] - Chain processed normally (ExceptionTranslationFilter.java:115)
  [DEBUG] [org.springframework.web.filter.RequestContextFilter] - Cleared thread-bound request context: FirewalledRequest[ org.apache.catalina.connector.RequestFacade@14738593] (RequestContextFilter.java:104)
  [DEBUG] [org.springframework.security.web.context.SecurityContextPersistenceFilter] - SecurityContextHolder now cleared, as request processing completed (SecurityContextPersistenceFilter.java:97)
  
  &lt;!-- continue with new filter chain --&gt;
  
  [DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/'; against '/oauth/cache_approvals' (AntPathRequestMatcher.java:145)
  [DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/'; against '/oauth/uncache_approvals' (AntPathRequestMatcher.java:145)
  [DEBUG] [org.springframework.security.web.util.matcher.OrRequestMatcher] - Trying to match using Ant [pattern='/oauth/token'] (OrRequestMatcher.java:65)
  [DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/'; against '/oauth/token' (AntPathRequestMatcher.java:145)
  [DEBUG] [org.springframework.security.web.util.matcher.OrRequestMatcher] - No matches found (OrRequestMatcher.java:72)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - No HttpSession currently exists (HttpSessionSecurityContextRepository.java:136)
  [DEBUG] [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - No SecurityContext was available from the HttpSession: null. A new one will be created. (HttpSessionSecurityContextRepository.java:90)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.header.writers.HstsHeaderWriter] - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@5688e4ae (HstsHeaderWriter.java:129)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/'; against '/logout' (AntPathRequestMatcher.java:145)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 6 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Request 'GET /' doesn't match 'POST /login-processing-url (AntPathRequestMatcher.java:127)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.authentication.AnonymousAuthenticationFilter] - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS' (AnonymousAuthenticationFilter.java:102)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' (FilterChainProxy.java:337)
  [DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/'; against '/logout' (AntPathRequestMatcher.java:145)
  [DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Secure object: FilterInvocation: URL: /; Attributes: [authenticated] (AbstractSecurityInterceptor.java:194)
  [DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS (AbstractSecurityInterceptor.java:310)
  [DEBUG] [org.springframework.security.access.vote.AffirmativeBased] - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@f84a51b, returned: -1 (AffirmativeBased.java:65)
  [DEBUG] [org.springframework.security.web.access.ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point (ExceptionTranslationFilter.java:165)
  org.springframework.security.access.AccessDeniedException: Access is denied
      at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)
      at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:206)
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
      at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
      at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
  </code></pre>
  
  <p>I see that the token is generated <code>Written [409d7529-2f54-4ec0-8439-3f2730e89e3c] as "application/json;charset=UTF-8"</code> but why it redirects to login page instead of returning json?</p>
  
  <p>Anyone please let me know what I'm wrong? Any help would be appreciated!<br>
  <strong>Update:</strong> the problem seems that a new filter chain is started as you can see in logs. But what is the cause???</p>