NetCore中跨域策略的一个坑

事件回顾

最近,一个一直使用的前后端分离项目部署到某环境时突然报跨域了。首先肯定想到是后端问题。后端用NetCore项目作为网关接收前端请求,并配置了跨域策略。
使用的跨域策略:

services.AddCors(options =>
            options.AddPolicy("AllowSameDomain",
            builder => builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials())
);

app.UseCors("AllowSameDomain");

报错:HttpRequest at 'xxx' from origin 'xxx' has been blocked by CORS policy: 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'.

问题解决

网上查阅发现:
前端使用了 withCredentials: true,而恰恰这个使用是不允许AllowAnyOrigin()的,意思就是不允许返回的Access-Control-Allow-Origin:*。
于是将跨域策略改为:

app.UseCors(builder =>
{
    builder.SetIsOriginAllowed(_ => true)
          .AllowCredentials()
          .AllowAnyHeader();
});

不再报错

参考博文:
https://www.cnblogs.com/May-day/p/13965087.html

posted @ 2020-12-31 22:45  Muphalem  阅读(708)  评论(0编辑  收藏  举报
/* 看板娘 */