2013-10-15 24 views
2

我正在使用Dropwizard,我將託管,以及一個網站,在谷歌雲(GCE)上。這意味着,有2處當前處於活動狀態:如何修復服務器和網站的跨站點源策略

Some.IP.Address - UI Some.IP.Address:8080 - Dropwizard服務器

當UI嘗試從我dropwizard服務器調用什麼,我得到跨站點原點錯誤,這是可以理解的。但是,這對我來說是一個問題。我該如何解決?如果我能以某種方式欺騙這些地址,這將是非常好的,這樣我就不必在UI中完全限定資源。

什麼,我要做到這一點是:

$獲得( '/供應商/上傳/ display_information')

或者,如果我必須完全限定

$不用彷徨('http://Some.IP.Address:8080/provider/upload/display_information')

我試着在Dropwizard中通過這個谷歌組線程(https://groups.google.com/forum/#!topic/dropwizard-user/ybDOTOxjlLI)設置原始過濾器,但它似乎沒有工作。

+0

[避開相同來源策略的方式]的可能重複(http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy) – Quentin

回答

2

在由服務器在http://Some.IP.Address服務的index.html中,您可能有一個如下所示的jQuery腳本。

$.get('http://Some.IP.Address:8080/provider/upload/display_information', data, callback); 

當然,由於同源策略(SOP),您的瀏覽器將不允許訪問http://Some.IP.Address:8080。協議(http,https)和主機以及端口必須相同。

要在Dropwizard上實現跨源資源共享(CORS),您必須向Servlet環境添加CrossOriginFilter。該過濾器將爲服務器發送的每個響應添加一些Access-Control-Headers。在您的Dropwizard應用程序寫入的run方法:

import org.eclipse.jetty.servlets.CrossOriginFilter; 

public class SomeApplication extends Application<SomeConfiguration> { 

    @Override 
    public void run(TodoConfiguration config, Environment environment) throws Exception { 
     FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); 
     filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); 
     filter.setInitParameter("allowedOrigins", "http://Some.IP.Address"); // allowed origins comma separated 
     filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin"); 
     filter.setInitParameter("allowedMethods", "GET,PUT,POST,DELETE,OPTIONS"); 
     filter.setInitParameter("preflightMaxAge", "5184000"); // 2 months 
     filter.setInitParameter("allowCredentials", "true"); 

     // ... 
    } 

    // ... 

} 

該解決方案適用於Dropwizard 0.7.0,可以在https://groups.google.com/d/msg/dropwizard-user/xl5dc_i8V24/gbspHyl4y5QJ找到。

此過濾器將爲每個響應添加一些Access-Control-Headers。有關CrossOriginFilter的初始化參數的詳細說明,請參閱http://www.eclipse.org/jetty/documentation/current/cross-origin-filter.html