2016-11-04 60 views
0

我有一個Spring啓動應用程序,具有Oauth認證和資源服務器以及一個單一的應用程序。我有一個單獨的服務器上的前端,從一個單獨的位置。我的前端應用程序似乎並沒有進行預檢操作到後端,它總是與401迴應我的配置看起來爲如下:Spring security,OAUTH Cors,選項

// ... annotations 
public class OAuthConfig extends WebSecurityConfigurerAdapter { 

    // ... authencication providers 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     // @formatter:off 
     http 
     .csrf().disable() 
     .authorizeRequests() 
      .antMatchers("/", "/*.html", "layout/**", "/js/**", "/css/**", "/images/**", "/font/**", 
        "/signup", "/register", 
        "/oauth/**") 
      .permitAll() 
      .and() 
       .authorizeRequests() 
       .antMatchers(HttpMethod.OPTIONS, "/oauth/**").permitAll() 
      ; 

     // @formatter:on 
    } 

    // ... beans 
} 

注意,我不得不添加例外靜態內容爲好,因爲儘管有任何文件,但它似乎沒有以其他方式工作。

// ... annotations 
public class MvcConfig extends WebMvcConfigurerAdapter { 

// ... resource resolver, view resolver 

    @Override 
    public void addCorsMappings(CorsRegistry registry) { 
     registry.addMapping("/**"); 
    } 

} 

我試圖指定更明確,但沒有成功,以及:

@Override 
public void addCorsMappings(CorsRegistry registry) { 
    registry.addMapping("/api/**").allowedMethods("GET","POST","OPTIONS","DELETE","UPDATE"); 
    registry.addMapping("/register"); 
    registry.addMapping("/signup"); 
    registry.addMapping("/oauth/**").allowedMethods("GET","POST","OPTIONS"); 
} 
//... annotations 
public class ResourceServerConfig extends ResourceServerConfigurerAdapter { 

    // ... resource id config 

    @Override 
    public void configure(HttpSecurity http) throws Exception { 
     //@formatter:off 
     http 
     .anonymous().disable() 
      .requestMatchers() 
      .antMatchers("/api/**") 
     .and() 
      .authorizeRequests() 
      .antMatchers("/api/**").authenticated() 
     .and() 
      .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler()); 
     //@formatter:on 
    } 

} 

在這一點上我無法弄清楚,如果我錯過了什麼重要配置,以通過認證端點(以及API端點的其他部分)實現CORS

回答

0

如果您有HTTP 401錯誤,對我來說,這並不意味着CORS配置是問題。 401應該是未經授權的,所以這個問題可能會在你的安全配置中更多。如果這是一個交叉來源問題,您會在請求的資源上出現錯誤,例如「No」Access-Control-Allow-Origin'標題存在。「

事實上,我有一個我的應用程序獲得HTTP 200(確定)的請求失敗,因爲一個交叉來源問題。

如果你需要幫助,你應該提供詳細的請求/響應,你有401錯誤代碼。


我知道這不是一個真正的答案,但我沒有評論的聲望,所以我希望這會有所幫助。

0

您也可以在服務器上配置CORS。這將適用於您的應用程序的所有API。或者你在你的resquest和response中設置'Access-Control-Allow-Origin to *',以便你的api可以響應來自任何服務器的任何請求。

相關問題