You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SetIsOriginAllowed需注意什么?当前代码是否存在CSRF风险?

CORS配置中EndsWith的安全隐患及修正方案

问题核心

当前代码里的origin => origin.EndsWith("SomeWebsite.com")确实存在安全漏洞:maliciousSomeWebsite.com这类恶意域名完全能绕过校验,进而发起带凭证的跨域请求,存在CSRF攻击风险。

为什么会被绕过?

EndsWith("SomeWebsite.com")的逻辑是只要域名末尾字符串匹配就放行,不管前面的前缀是什么。比如maliciousSomeWebsite.com的结尾就是SomeWebsite.com,自然会通过校验。而你开启了AllowCredentials(),浏览器会自动携带Cookie、HTTP认证信息等,恶意域名就能利用这些凭证发起CSRF攻击,操作用户在你的站点上的账号。

正确的修正方式

直接改成origin.EndsWith(".SomeWebsite.com")能拦截这类伪域名,但要注意:主域名SomeWebsite.com本身会被这个规则排除在外,所以需要把主域名也加入允许列表。完整的校验逻辑应该是:

app.UseCors(options => options
    .SetIsOriginAllowed(origin => 
        origin.Equals("SomeWebsite.com", StringComparison.OrdinalIgnoreCase) || 
        origin.EndsWith(".SomeWebsite.com", StringComparison.OrdinalIgnoreCase))
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials()
    .SetPreflightMaxAge(TimeSpan.FromSeconds(2520))
);

额外建议

  • 加上StringComparison.OrdinalIgnoreCase忽略大小写,避免因域名大小写差异导致的错误拦截或放行(比如somewebsite.com和SomeWebsite.com都应该被允许)。
  • 如果你的业务只需要允许特定几个域名,优先使用WithOrigins("SomeWebsite.com", "api.SomeWebsite.com")这种精确匹配的方式,比模糊匹配的安全性更高。

内容的提问来源于stack exchange,提问作者David Klempfner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 06:47:14