使用 oAuth 和基于表单的身份验证配置 Spring Security

Posted

技术标签:

【中文标题】使用 oAuth 和基于表单的身份验证配置 Spring Security【英文标题】:Configuring spring security using oAuth and form based authentication 【发布时间】:2015-03-27 05:58:47 【问题描述】:

我有一个包含两个组件的服务器应用程序: a) 一组使用 oAuth (Spring security oAuth) 保护的 REST API b) 具有基于角色的 UI 的管理仪表板

出于业务原因,这两个组件需要共同托管,即部署为单一战争。 到目前为止,我们只有 oAuth 用于我们的 REST API,一切都很好。 当我们尝试对仪表板使用基于表单的身份验证时,问题就开始了。现在,当我们在没有 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 未经授权的消息。表单登录不起作用。我无需登录即可访问所有仪表板页面。 更多代码sn-ps:

 @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添加到网络安全配置器中。

    确保 WebSecurityConfigurerAdapter 具有 .anyRequest().authenticated() 配置

    @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();
    
    
    
    

【问题讨论】:

你在WebSecurityConfigurerAdapter 上使用什么@Order(它需要在ResourceServerConfiguration 之后 默认为3)? 我们为 ResourceServerConfiguration 添加了 1 的顺序,为 WebSecurityConfigurerAdapter 添加了 2 的顺序。它仍然显示相同的行为。未经授权的 REST API 访问重定向到登录页面 您是如何更改ResourceServerConfiguration 的顺序的? (我不会那样做的。) 对。那方法没用。我现在已将 ResourceServerConfiguration 更改为 @Order(3) 并将 WebSecurityConfigurerAdapter 更改为 @Order(4)。我确实收到了 REST API 的 401 未经授权的错误,但 Web 配置不起作用!我无需身份验证即可访问仪表板中的任何链接。我们还使用 AuthorizationServerConfigurerAdapter 和 GlobalMethodSecurityConfiguration。我在这里缺少任何固有的顺序吗?我找不到任何有关此的文档。如果您有链接,请分享。谢谢! 如果没有看到更多代码,我真的无法判断您做了什么。为什么你还有ResourceServerConfiguration(通常你使用@EnableResourceServer 导入它)? 【参考方案1】:

我可以看到它在日志中检查您的 permitAll() 匹配器,但没有 anyRequest().authenticated() 的迹象。您还需要向HttpSecurity 添加请求匹配器(即http.requestMatchers().anyRequest())。

【讨论】:

以上是关于使用 oAuth 和基于表单的身份验证配置 Spring Security的主要内容,如果未能解决你的问题,请参考以下文章

Oauth 和 Spring 安全性

一个应用程序中的 Spring Security OAuth2 身份验证和表单登录

Spring Cloud OAuth2:身份验证后再次重定向到登录页面,就像使用表单登录时未经身份验证一样

如何基于使用 Oauth2 协议的身份验证改进 JWT 访问令牌和刷新令牌?

使用 Spring security Javaconfig 进行基本和基于表单的身份验证

基于 oauth 的身份验证查询