我正在使用Spring Security 3.2
和Spring Security OAuth 1.0.5
实施OAuth 2。它适用于基于xml的配置。现在我尝试迁移到基于java的配置,我面临的问题是,它不是返回令牌,而是将我重定向到登录页面!以下是配置:
SecurityInitializer.java
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;
}
}
}
WebInitializer.java
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected Class<?>[] 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();
}
}
}
我试图开始记录,我得到了以下内容:
[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&grant_type=password&username=user&password=bypass&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&grant_type=password&username=user&password=bypass&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<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.getAccessToken(java.security.Principal,java.lang.String,java.util.Map<java.lang.String, java.lang.String>)] (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)
<!-- continue with new filter chain -->
[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)
我看到令牌是Written [409d7529-2f54-4ec0-8439-3f2730e89e3c] as "application/json;charset=UTF-8"
生成的,但是为什么它重定向到登录页面而不是返回json?
任何人都请让我知道我错了什么?任何帮助将不胜感激! 更新:问题似乎是新的过滤器链已启动,您可以在日志中看到。但是原因是什么?