CORS(Cross-Origin-Resoure-Sharing)

来源:互联网 发布:美工刀削水果 编辑:程序博客网 时间:2024/04/27 20:23

最近在做Ionic Hybrid App 项目时,在手机上调试时,发现不用在服务端配置 CORS,也可以实现跨域访问问题。为什么呢?

Cordova Whitelist Guide

因为 platforms\android\res\xml\config.xml 文件中默认配置了:

<access origin="*" />   ----> Access to all domains


Understanding CORS

HTTP access control (CORS)

Using CORS

服务器中的web.xml配置了允许跨域访问的配置,如下:

<filter>    <filter-name>corsFilter</filter-name>    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>    <init-param>        <param-name>cors.supportedMethods</param-name>        <param-value>GET, POST, HEAD, PUT, DELETE, OPTIONS</param-value>    </init-param></filter><filter-mapping>    <filter-name>corsFilter</filter-name>    <url-pattern>/service/*</url-pattern></filter-mapping>

chrome 浏览器发出请求,如下图:
这里写图片描述

这里写图片描述

CORS
CORS is an oft-misunderstood feature of new browsers that is configured by a remote server. CORS stands for Cross-Origin-Resource-Sharing, and was designed to make it possible to access services outside of the current origin (or domain) of the current page.

Like many browser features, CORS works because we all agree that it works. So all major browsers like Chrome, Firefox, and IE support and enforce it. By using these browsers, you benefit from the security of CORS.

That means certain browsers do not enforce it, so it is not relevant there. One large example is a native Web View for things like Cordova and Phonegap (and hence, Ionic apps). However, these tools often have configuration options for whitelisting domains so you can add some security that way.

Configuring CORS on the Server
The way CORS works is the server decides which domains it will accept as clients. This means an open API like Twitter might allow any clients, or a closed API might decide to only allow access from the domain of the running client app.

I won’t get into the details of configuring CORS on the server side, but it’s really just setting some headers. Here’s how you might do it in nginx.

There is one header in particular you must have if you want to do session based authentication in a single page app: Access-Control-Allow-Credentials: true which we show next.

Credentials and CORS
One thing to note when using withCredentials: true in your app and configuring the server for CORS is that you may not have your Access-Control-Allow-Origin header set to ‘‘. It must be configured to a few select origins. If you absolutely must have this set to , then I suggest doing something beyond cookie based authentication, such as token-based authentication.

0 0