Settings with cookies when Cross-domain Ajax requests __ajax

Source: Internet
Author: User
Tags java web
1. Unrelated cookies cross domain Ajax request Client

Take Jquery Ajax for example:

$.ajax ({
        URL: ' http://remote.domain.com/corsrequest ',
        data:data,
        dataType: ' json ',
        type: ' POST ',
        crossdomain:true,
        contentType: "Application/json",//Post must
        ...

The main note is the parameter crossdomain:true. When you send Ajax, the Request header contains additional information that spans the domain but does not contain cookies. Server-Side

Cross-domain permission is primarily controlled by the server side. The server side provides the Allow policy for cross-domain access by setting Access-control-allow-origin and related series of parameters in the header of the response. Introduction to the setting of related parameters, see [Access_control_cors]

Take Java as an example:

methods in/** * Spring Controller: *
    /@RequestMapping (value = "/corsrequest")
    @ResponseBody
    Public map<string, object> mainheaderinfo (httpservletresponse response) {
        Response.setheader (" Access-control-allow-origin "," * ");
        ...
}
Allow Cross-domain request access from all domains by setting ' * ' in the response header.
Response.setheader ("Access-control-allow-origin", "*");
Allow Cross-domain access only from a specific domain http://my.domain.cn:8080
Response.setheader ("Access-control-allow-origin", "http://my.domain.cn:8080");
More flexible settings that allow all domain names that contain mydomain.com to be accessed.
if (Request.getheader ("Origin"). Contains ("mydomain.com")) {
    Response.setheader ("Access-control-allow-origin") , Request.getheader ("Origin"));
}
2. Cross-domain AJAX requests with cookies Client
$.ajax ({
        URL: ' http://remote.domain.com/corsrequest ',
        data:data,
        dataType: ' json ',
        type: ' POST ',
        xhrfields: {
            withcredentials:true
        },
        crossdomain:true,
        contentType: "Application/json",
        ...

When you send Ajax by setting up Withcredentials:true, Cookie information is taken in the Request header. Server-Side

Accordingly, for the client's parameters, the server side also needs to be set:

methods in/** * Spring Controller: *
    /@RequestMapping (value = "/corsrequest")
    @ResponseBody
    Public Map<string, object> getuserbaseinfo (httpservletresponse response) {
        if Request.getheader ("Origin"). Contains ("woego.cn")) {
            Response.setheader ("Access-control-allow-origin", Request.getheader ("Origin"));
        Response.setheader ("Access-control-allow-credentials", "true");
        ...
}

Corresponding to the client's xhrFields.withCredentials:true parameter, the server side sets Access-control-allow-credentials = True in the response header To run the client to carry a certificate-type access. By setting the Credentials parameter, you can maintain a Cookie for Cross-domain Ajax. Here's what you need to be aware of:

when server-side Access-control-allow-credentials = True, the value of the parameter Access-control-allow-origin cannot be ' * ' . 3. Using cross-domain Filter in Java

Adding access-control-allow-origin to each request is obviously inappropriate when more interfaces are allowed for cross-domain access. Using Filter is a good choice for comparing native Java Web applications.

Note: Different frameworks, especially those that support rest, provide their own cross-domain settings, such as Spring4 Config, to give priority to finding support from the framework in use.

Filter itself is very simple, you can directly the above two sentences set Header to extract the statement to write a filter. A Filter:org.apache.catalina.filters.CorsFilter in Tomcat is recommended here.

introduced
This class can be used in Tomcat Catalina.jar by referencing the jar package under Tomcat/lib to the project. But if you are ' neat ' about your project's jar environment, you can also copy the svn source of this class to your project separately, modifying (deleting) a reference to the ' log ' and ' exception hints ' can run in any native Java Web project.

Set Method
Set filter in Web.xml:

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class> org.apache.catalina.filters.corsfilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
< /filter-mapping>

A little supplement:
The default settings for filter include:

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class> org.apache.catalina.filters.corsfilter</filter-class>
  <init-param>
        <param-name> cors.allowed.origins</param-name>
        <param-value>*</param-value>
  </init-param>
  <init-param>
        <param-name>cors.support.credentials</param-name>
        <param-value >true</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</ Filter-mapping>

The cors.allowed.origins here is ' * ', but the implementation has been optimized to not conflict with credentials.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.