2017-09-03 149 views
0

我有完美的彈簧啓動應用程序,它使用彈簧oAuth2。當我在主類上使用@EnableResourceServer時,它運行良好。 但啓用服務CORS我在下面類WebSecurityConfigurerAdapter重寫EnableResourceServer?

@Configuration 
    public class CorsConfiguration extends WebSecurityConfigurerAdapter { 
     @Override 
     protected void configure(HttpSecurity http) throws Exception { 

      http.csrf().disable(); 
      http.cors(); 

     } 
     @Bean 
     public CorsConfigurationSource corsConfigurationSource() { 
      final org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration(); 
      configuration.setAllowedOrigins(ImmutableList.of("*")); 
      configuration.setAllowedMethods(ImmutableList.of("HEAD", 
        "GET", "POST", "PUT", "DELETE", "PATCH")); 
      configuration.setAllowCredentials(true); 
    configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type")); 
      final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
      source.registerCorsConfiguration("/**", configuration); 
      return source; 
     } 
    } 

後,我補充一點,類似乎要求不符合的OAuth令牌驗證實現的。即使沒有oAuth令牌的任何請求都可以訪問服務。

我做錯了什麼? 我不能同時使用?有沒有什麼特別的事情可以同時工作? 有沒有更好的方法來啓用CORS這個。 (我試了@CrossOrigin註釋它沒有工作)

回答

1

我不知道你爲什麼想要使用WebSecurityConfigurerAdapter 我認爲你的問題是你沒有轉發你的電話到oAuth進行授權。試試這個它爲我工作

@Configuration 
public class CorsConfiguration extends ResourceServerConfigurerAdapter { 


    @Override 
    public void configure(HttpSecurity http) throws Exception { 
     http.cors().and().csrf().disable().authorizeRequests().anyRequest().authenticated(); 
    } 
    @Bean 
    public CorsFilter corsFilter() { 
     final org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration(); 
     configuration.setAllowedOrigins(ImmutableList.of("*")); 
     configuration.setAllowedMethods(ImmutableList.of("HEAD", 
       "GET", "POST", "PUT", "DELETE", "PATCH")); 
     configuration.setAllowCredentials(true); 

     configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type")); 
     final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
     source.registerCorsConfiguration("/**", configuration); 
     return new CorsFilter(source); 
    } 
    @Override 
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception { 
     resources.resourceId("resource"); 
    } 

} 

這裏這resources.resourceId("resource");應該是資源已在您的OAuth服務器使用

類似的方法是這樣

@Override 
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 
     clients.inMemory().withClient("clinet").secret("secret").accessTokenValiditySeconds(3600).scopes("read", "write") 
       .authorizedGrantTypes("password", "refresh_token").resourceIds("resource"); 
    }