我有一个包含两个组件的服务器应用程序: a)使用oAuth(Spring security oAuth)保护的一组REST API b)使用基于角色的UI进行管理的仪表板
出于商业原因,这两个组件需要共同托管,即部署为单一战争。 到目前为止,我们只为我们的REST API提供了oAuth,而且一切都很顺利。 当我们尝试对仪表板使用基于表单的身份验证时,问题就出现了。现在,当我们在没有oAuth令牌的情况下访问REST API时,它只是重定向到登录页面而不是发出401未经授权的错误。 我们的配置是这样的: 基于表单的身份验证(WebSecurityConfigurerAdapter):
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/css/**","/img/**","/login/**","/oauth/**).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login")
.defaultSuccessUrl("/delegate/success", true)
.failureUrl("/login/fail")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.permitAll();
OAUTH:
资源提供程序配置:
http
.authorizeRequests()
.antMatchers("/abc").access("#oauth2.hasScope('read')and hasRole('ROLE_USER')")
.antMatchers("/xyz").access("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')")
我们基本上希望配置不同的API以获得不同的保护。客户端应用程序使用的REST API必须通过oAuth和Spring MVC API呈现仪表板页面以及基于表单的身份验证来保护。 这甚至可能吗?
编辑: 添加排序并能够在访问受oauth保护的REST API时获得401未经授权的消息。表单登录不起作用。我可以在不登录的情况下访问所有仪表板页面。 更多代码段:
@Configuration
@EnableResourceServer
public class ResourceProviderConfiguration extends ResourceServerConfigurerAdapter {
.....
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/abc").access("#oauth2.hasScope('read')and hasRole('ROLE_USER')")
.antMatchers("/xyz").access("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')").
.and()
.requestMatchers()
.antMatchers("/abc","/xyz","/others");
}
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationProviderConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
ClientDetailsService webClientDetailsService;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
.......
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
......
}
@Configuration
@EnableWebSecurity
@Order(5)
public class UserAuthenticationConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/css/**","/img/**","/login/**",
"/oauth/**).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login")
.defaultSuccessUrl("/delegate/success", true)
.failureUrl("/login/fail")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.permitAll();
}
}
Spring安全日志:
DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token']
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/def'; against '/oauth/token'
DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token_key']
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/def'; against '/oauth/token_key'
DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/check_token']
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/def'; against '/oauth/check_token'
DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found
DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/abc/**']
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/def'; against '/abc/**'
DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/xyz/**']
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/def'; against '/xyz/**'
DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@7f8059. A new one will be created.
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG o.s.s.w.h.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@cebda04
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/def'; against '/logout'
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET '/def'' doesn't match 'POST /login/new
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@905571d8: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 127.0.0.1; SessionId: 794828541EF505314237BBC81C2ACAF4; Granted Authorities: ROLE_ANONYMOUS'
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG o.s.security.web.FilterChainProxy - '/def' at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/def'; against '/css/**'
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/def'; against '/oauth/**'
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/def'; against '/img/**'
DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/def'; against '/login/**'
DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Public object - authentication not attempted
DEBUG o.s.security.web.FilterChainProxy - '/def' reached end of additional filter chain; proceeding with original chain
DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'webservice' processing GET request for ['/handler/def']
最终配置有效: 1.在资源提供程序配置(默认为3)之后,将@Order添加到Web安全配置程序。
确保WebSecurityConfigurerAdapter具有.anyRequest()。authenticated()config
@Configuration
@EnableResourceServer
public class ResourceProviderConfiguration extends ResourceServerConfigurerAdapter {
.....
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/abc").access("#oauth2.hasScope('read')and hasRole('ROLE_USER')")
.antMatchers("/xyz").access("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')").
.and()
.requestMatchers()
.antMatchers("/abc","/xyz","/others");
}
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationProviderConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
ClientDetailsService webClientDetailsService;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
.......
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
......
}
@Configuration
@EnableWebSecurity
@Order(5)
public class UserAuthenticationConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/css/**","/img/**","/login/**",
"/oauth/**).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login")
.defaultSuccessUrl("/delegate/success", true)
.failureUrl("/login/fail")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.permitAll();
}
}
答案 0 :(得分:1)
我可以看到它在日志中检查您的permitAll()
匹配器,但没有anyRequest().authenticated()
的迹象。您还需要向HttpSecurity
添加请求匹配器(即http.requestMatchers().anyRequest()
)。