【问题标题】:Spring Oauth2 separate resource server configurationSpring Oauth2 独立资源服务器配置
【发布时间】:2016-01-18 07:34:02
【问题描述】:

我正在尝试为 oauth2 配置单独的身份验证和资源服务器。 我能够成功配置授权服务器并能够验证和生成访问令牌。现在我想配置一个资源服务器,它可以与带有 api 端点的身份验证服务器对话以验证访问令牌。 下面是我的资源服务器配置。

@Configuration
@EnableResourceServer
@EnableWebSecurity
public class Oauth2SecurityConfiguration extends WebSecurityConfigurerAdapter      {


 @Override
 protected void configure(HttpSecurity http) throws Exception {
     System.out.println("Oauth2SecurityConfiguration before");   
     http
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/api/v1/**").authenticated();
     System.out.println("Oauth2SecurityConfiguration  after");
}

@Bean
public AccessTokenConverter accessTokenConverter() {
    return new DefaultAccessTokenConverter();
}

@Bean
public RemoteTokenServices remoteTokenServices() {
    final RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
    remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:9000/authserver/oauth/check_token");
    remoteTokenServices.setClientId("clientId");
    remoteTokenServices.setClientSecret("clientSecret");
    remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
    return remoteTokenServices;
}

@Override
@Bean
public AuthenticationManager authenticationManager() throws Exception {
    OAuth2AuthenticationManager authenticationManager = new OAuth2AuthenticationManager();
    authenticationManager.setTokenServices(remoteTokenServices());
    return authenticationManager;
}   
}


@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        System.out.println("http.csrf().disable()");
        http.authorizeRequests().antMatchers(HttpMethod.GET, "/api/v1/**").fullyAuthenticated();
        System.out.println("http.authorizeRequests().anyRequest().authenticated()");
    }
}


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

 @Override
 protected MethodSecurityExpressionHandler createExpressionHandler() {
   return new OAuth2MethodSecurityExpressionHandler();
 }
}

问题: 1.为什么我在资源服务器上进行AuthenticationManager,而所有身份验证都委托给身份验证服务器。 (我必须添加它来加载应用程序上下文)

除此之外,我还面临以下问题。

  1. 即使我没有在请求中传递授权标头和访问令牌。它正在通过。

    http GET "http://localhost:8080/DataPlatform/api/v1/123sw/members"
    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8
    Date: Mon, 19 Oct 2015 19:45:14 GMT
    Server: Apache-Coyote/1.1
    Transfer-Encoding: chunked
    {
    "entities": [], 
    "errors": [], 
    "message": null
    }
    
  2. 过滤器只被调用一次我没有看到以下请求的日志。它是否在某处缓存授权?

我是 spring oauth 的新手,如果我做错了什么,请告诉我。我正在使用

spring-security-oauth2 : 2.0.7.RELEASE
spring-security-core   : 4.0.1.RELEASE
java : 1.8

【问题讨论】:

    标签: spring-security oauth-2.0


    【解决方案1】:

    你不需要@EnableWebSecurity Oauth2SecurityConfiguration @EnableResourceServer 就足够了。 您还应该将extends WebSecurityConfigurerAdapter 替换为extends ResourceServerConfigurerAdapter

    如果你想使用你的RemoteTokenServices 实例,我建议你用

    覆盖ResourceServerConfigurerAdapter public void configure(ResourceServerSecurityConfigurer resources) throws Exception
    @Override
    public void configure( ResourceServerSecurityConfigurer resources ) throws Exception
    {
        resources.tokenServices( serverConfig.getTokenServices() );
    }
    

    【讨论】:

    • 但我在文档docs.spring.io/spring-security/oauth/apidocs/org/… 中看到“要使用此过滤器,您必须在应用程序的某处使用@EnableWebSecurity”
    • @EnableWebSecurity 在某处需要。该注释方便地创建了一个 FilterChainProxy。 FilterChainProxy 有一个与安全相关的其他过滤器列表。我怀疑@EnableResourceServer 方便地在@EnableWebSecurity 创建的FilterChainProxy 中添加了OAuth 过滤器。
    【解决方案2】:

    主要的一点是为 auth-server 和 resource-server 创建单独的端点,它们可以分别为它们提供服务,每个都有自己的。 如下图“/user/getEmployeesListRole/**”-通过auth-server访问,“/user/getEmployeesListOAuth2/**”-通过aouth2-server生成的token通过resource-server访问。另外请注意auth -server 和 oauth2-server 具有相同的 auth-manager

    spring-boot aouth2-server、resource-server、auth-server 在一个 spring-boot 应用中的配置

    1.入口点:

    /*AuthApplication.java*/ @SpringBootApplication @EnableDiscoveryClient @EnableGlobalMethodSecurity(prePostEnabled = true) 公共类 AuthApplication { 公共静态无效主要(字符串[]参数){ SpringApplication.run(AuthApplication.class, args); }} 2. aouth2-server的配置:
    /*OAuth2AuthorizationConfig.java*/
         @配置
         @EnableAuthorizationServer
         公共类 OAuth2AuthorizationConfig 扩展 AuthorizationServerConfigurerAdapter {
    私有 TokenStore tokenStore = new InMemoryTokenStore();
    @自动连线 @Qualifier("authenticationManagerBean") 私有 AuthenticationManager authenticationManager;
    @自动连线 @Qualifier("userDetailsS​​erviceBean") 私人用户详细信息服务用户详细信息服务;
    @覆盖 公共无效配置(ClientDetailsS​​erviceConfigurer 客户端)抛出异常 { 客户.inMemory() .withClient("浏览器") .authorizedGrantTypes("密码", "refresh_token") .scopes("ui", "read:ui", "write:ui"); }

    @覆盖 公共无效配置(AuthorizationServerEndpointsConfigurer 端点)抛出异常 { 端点.tokenStore(tokenStore) .authenticationManager(authenticationManager) .userDetailsS​​ervice(userDetailsS​​ervice); }
    @覆盖 公共无效配置(AuthorizationServerSecurityConfigurer oauthServer)抛出异常{ oauthServer.tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()") .passwordEncoder(NoOpPasswordEncoder.getInstance()); }}

    2.1 aouth2-server auth-request [post with basic auth]:
    http://localhost:5000/uaa/oauth/token?grant_type=password&scope=ui write:ui&username=user&password=123456&client_id=browser
    3.Config resource-server:
    /*ResourceServer.java*/
        @配置
           @EnableResourceServer
           类 ResourceServer 扩展 ResourceServerConfigurerAdapter {
             //这里我们指定允许请求到
             // url /user/getEmployeesList 具有有效的访问令牌和范围读取
             @覆盖
             公共无效配置(HttpSecurity http)抛出异常{
                 http.requestMatchers()
                       .antMatchers("/user/getEmployeesList/**")
                       .antMatchers("/user/getEmployeesListOAuth2/**")
               .and().authorizeRequests().anyRequest().access("#oauth2.hasScope('ui')");
    }}
    4。配置身份验证服务器:
    /*WebSecurityConfig.java*/
        @配置
        @EnableWebSecurity
        公共类 WebSecurityConfig 扩展 WebSecurityConfigurerAdapter {
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/resources/**");
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
           http
                .authorizeRequests()     
                .antMatchers("/user/getEmployeesListRole/**")
                   .access("hasAuthority('WRITE_DATA') && hasAuthority('READ_DATA')")           
                      .anyRequest().permitAll()         
                .and().formLogin().permitAll()
                .and().logout().permitAll()
                .and().csrf().disable();              
        }    
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
            auth.inMemoryAuthentication().withUser("admin")
                                         .password("admin")                                  
                                         .authorities("WRITE_DATA", "READ_DATA");                                      
        }
    
        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }    
    
        @Override
        @Bean
        public  UserDetailsService userDetailsServiceBean() throws Exception {
            return super.userDetailsServiceBean();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-08
      • 2017-09-13
      • 2017-03-25
      • 1970-01-01
      • 2015-11-19
      • 2017-03-29
      • 2013-12-21
      • 2018-04-14
      • 2015-08-18
      相关资源
      最近更新 更多