1
我有一個使用Angular 2開發的Web應用程序,以及使用Springboot開發的Rest API。Webapp和移動應用程序使用的Spring API
Mme Michu ---> WebApp (Angular 2 - Known origin) ---> API (Springboot CORS)
我在webapp和API之間配置了CORS,它工作正常。
這裏是我的CORSFilter是如何實現的
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter{
public SimpleCORSFilter() {
super();
}
@Autowired
private Environment environment;
private String[] acao;
@Override
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
acao = environment.getProperty("access-control-allow-origin").split(",");
final HttpServletResponse response = (HttpServletResponse) res;
final HttpServletRequest request = (HttpServletRequest) req;
String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", Arrays.asList(acao).contains(origin)?origin:"");
// without this header jquery.ajax calls returns 401 even after successful login and SSESSIONID being succesfully stored.
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Origin, Content-Type, Version");
response.setHeader("Access-Control-Expose-Headers", "X-Requested-With, Authorization, Origin, Content-Type");
if(!request.getMethod().equals("OPTIONS")) {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
acao = environment.getProperty("access-control-allow-origin").split(",");
}
}
的問題是,我需要一個新的移動應用(與離子developped)與API進行交互。
Mme Michu --> MobileApp (Unknown origin) ---> API (Springboot CORS)
CORS策略會阻止來自移動應用程序的請求嗎? 我如何授權來自移動應用程序的請求,因爲我無法知道移動應用程序的「來源」?
任何意見,歡迎...
我不明白你的答案... CORS過濾器是服務器端,所以客戶端(移動應用程序)如何提供一個授予的來源? – DavidPi
服務器發送CORS頭文件,這是正確的,但它不是服務器在源與服務器不匹配時被阻塞。以不同的來源進行測試,您將看到服務器發送的迴應被客戶端(您的瀏覽器)阻止。服務器負責報告允許的來源。 Web瀏覽器負責強制執行請求僅從允許的域發送。 –
超級!我會試試看! Merci;) – DavidPi