Ajax跨域请求附带Cookie/Ajax跨域请求附带身份凭证

 ̄綄美尐妖づ 提交于 2020-05-04 02:50:59

一、跨域请求中默认不带cookie等验证凭证

尤其对于post请求。

对于ajax请求,其中post,get都可以正常访问。

withCredentials: false, // 允许携带cookie

如果设置允许带cookie那么会遇到一个错误:

Failed to load http://pre.api.jmxy.mockuai.c...: 
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
Origin '
http://pre.promotion.jmxy.moc...' is therefore not allowed access.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

 

这个错误的意思:

也就是说Access-Control-Allow-Credentials设置为true 的情况下Access-Control-Allow-Origin不能设置为 *

 

解决方案:

后台响应头中设置对应的允许的域名。

 

 

二、Asp.Net Core中跨域处理+附带Cookie验证

注:登录后cookie存储,由客户端完成,后台仅验证有效性。

 

1.请求中指定

 withCredentials:true  //支持附带详细信息
$.ajax({
    url: apiUrl.getCookie('getone'),
    data: { age: 11 },
    xhrFields: {
        withCredentials:true  //支持附带详细信息
    },
    crossDomain:true,//请求偏向外域
    success: function (data) {
        alert(data);
    }
});

 

2.响应中,单独设置允许的域名

//设置跨域访问
services.AddCors(options =>
{
    options.AddPolicy("any", builder =>
    {
        builder.WithOrigins("http://www.gongjuji.net/", "http://localhost:8080", "http://localhost:8081", "http://localhost:8082")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
    });
});

 

三、特别说明

1.当前设置仅针对同一个根域名的情况下,比如:www.gongjuji.net    和  erp.gongjuji.net 这样。

2.

 

更多:

Asp.Net WebApi 启用CORS跨域访问指定多个域名

Cors 跨域Access-Control-Allow-Origin

Ajax跨域请求中的Cookie问题(默认不带cookie等凭证)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!