如何使用 Windows 身份验证在 IIS 上授权 CORS 预检请求

2024-01-10

我在 ASP.net Core 2(Windows 身份验证)上有一个 API,在 Angular 上有一个前端。 我做了一个 cors 配置来从 SPA 角度查询我的后端,但由于预检而被阻止,他被 IIS 服务器拒绝,因为他没有标识信息。

错误信息 :

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://XXXXXX' is therefore not allowed access. The response had HTTP status code 401.

代码侧正面:

//MY HEADER
private headers = new Headers({
    'Content-Type': 'application/json', 
    'Access-Control-Allow-Credentials':'true',
    'Access-Control-Allow-Origin':'true'
});

//REQUEST
let options = new RequestOptions({headers:this.headers, withCredentials:true});
return this.http.get(this.tasksUrl,options).map(res=>res.json());

代码面背面:(Startup.cs)

public void ConfigureServices(IServiceCollection services)
{
   services.AddCors();
   services.AddCors(options =>
   {
       options.AddPolicy("AllowSpecificOrigin",
            builder =>
            {
               builder.WithOrigins("http://theURLofTheFront:8080" )
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials();
            });
   });
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        app.UseCors("AllowSpecificOrigin");
        app.UseMvc();
    }

我试试这个:

CORS 预检请求使用 Windows 身份验证返回 HTTP 401 https://stackoverflow.com/questions/38201776/cors-preflight-request-returning-http-401-with-windows-authentication.

我添加了自定义标头来指定 IIS 上的“Access-control-allow-origin”,但对我不起作用。

这对我不起作用:https://blogs.msdn.microsoft.com/friis/2017/11/24/putting-it-all-together-cors-tutorial/ https://blogs.msdn.microsoft.com/friis/2017/11/24/putting-it-all-together-cors-tutorial/

我无法删除默认授权规则。

我提前替你谢谢你


有多种方法可以实现此目的,可以在类似问题上找到其他答案 -->用于 PUT 和 POST 的 Angular4 ASP.NET Core 1.2 Windows 身份验证 CORS 给出 401 https://stackoverflow.com/questions/45108307/


跨域资源共享模块

可以使用以下命令来配置 IIS跨域资源共享模块 https://www.iis.net/downloads/microsoft/iis-cors-module.
正如这里所见:https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module
此处提供更多信息:https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module

IIS CORS 模块旨在处理 CORS 预检请求 在其他 IIS 模块处理相同请求之前。 OPTIONS 请求 始终是匿名的,因此 CORS 模块为 IIS 服务器提供了一种方法 即使匿名也能正确响应预检请求 需要在服务器上禁用身份验证。

您需要通过 Web Config 启用 CORS 模块:

<?xml version="1.0"?>
<configuration>
  <system.webServer>
    <cors enabled="true">
      <add origin="*" allowCredentials="true" />
    </cors>
  </system.webServer>
</configuration>

为了更精细的控制:

<?xml version="1.0"?>
<configuration>
  <system.webServer>
    <cors enabled="true">
      <add origin="https://readonlyservice.constoso.com" allowCredentials="true">
        <allowMethods>
            <add method="GET" />
            <add method="HEAD" />
        </allowMethods>
        <allowHeaders>
            <add header="content-type" /> 
            <add header="accept" /> 
        </allowHeaders>
      </add>
      <add origin="https://readwriteservice.constoso.com" allowCredentials="true">
        <allowMethods>
            <add method="GET" />
            <add method="HEAD" />
            <add method="POST" />
            <add method="PUT" /> 
            <add method="DELETE" />         
        </allowMethods>
      </add>
    </cors>
  </system.webServer>
</configuration>

重定向选项

您可以重定向所有 OPTIONS 请求以始终给出 OK 状态。 然而,这将颠覆预检请求的整个概念,因此仅当它适用于您的情况时才使用它。

安装重定向模块 https://learn.microsoft.com/en-us/iis/configuration/system.webserver/httpredirect/#setup in IIS.
将以下重定向添加到您的 Web Config。

<rewrite>
    <rules>
        <rule name="CORS Preflight Anonymous Authentication" stopProcessing="true">
            <match url=".*" />
            <conditions>
                <add input="{REQUEST_METHOD}" pattern="^OPTIONS$" />
            </conditions>
            <action type="CustomResponse" statusCode="200" statusReason="Preflight" statusDescription="Preflight" />
        </rule>
    </rules>
</rewrite>

中间件

或者,可以通过在 IIS 中启用匿名身份验证并在 Net Core API 中创建一个中间件来检查人员是否经过正确身份验证来实现所需的结果。

中间件:

public AuthorizationMiddleware(RequestDelegate next, ILogger logger)
{
    _next = next;
    _log = logger;
}

public async Task Invoke(HttpContext httpContext)
{
    //Allow OPTIONS requests to be anonymous
    if (httpContext.Request.Method != "OPTIONS" && !httpContext.User.Identity.IsAuthenticated)
    {
        httpContext.Response.StatusCode = 401;
        await httpContext.Response.WriteAsync("Not Authenticated");
    }
    await _next(httpContext);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Windows 身份验证在 IIS 上授权 CORS 预检请求 的相关文章

随机推荐

  • Linux 获取开机以来的系统时间

    我需要找到系统时间 因为我的 C 代码中的 Linux 机器已通电 time 和 gettimeofday 等函数返回自纪元以来的时间 而不是开机以来的时间 如何查找自开机以来的时间或时钟滴答数 提前致谢 该信息是通过以下方式提供的 pro
  • 清单中的 Android 抽象活动

    对于我的应用程序 我将创建各种扩展 android app Activity 和 android app Service 类的抽象类 当我对抽象类进行子类化时 如何将它们添加到 Android 清单中 我是否需要将抽象类和我的子类都添加到清
  • 使用 Jsoup 获取网页元素

    我正在尝试使用Jsoup从名为 Morningstar 的网站获取股票数据 我查看了其他论坛 但无法找出问题所在 我正在尝试进行更高级的数据报废 但我似乎甚至无法获得价格 我要么返回 null 要么什么也没有返回 我知道其他语言和 API
  • Doctrine – 如何在两个实体之间建立一对一的关系

    我有两个表 用户和联系人 Users id username Contacts id user id 电子邮件 我简化了结构 那么 如何正确设置条令实体呢 ORM Entity ORM Table name users class User
  • 从sql server 2005迁移到2008对应用程序的影响

    我们正在将 ASP NET Web 应用程序的后端从 sql server 2005 升级到 sql server 2008 或 2012 您能告诉我这对整个应用程序有什么影响吗 所有这些改变我们都必须做一次彻底成功的转型 我们也在考虑将前
  • 如何正确扩展WCF返回的类?

    我在我的项目中使用 WCF 服务 该服务返回一个名为 Store 的类 我创建了一个继承自 Store 的新本地类 我的课程名为 ExtendedStore 我的 ExtendedStore 看起来像这样 class ExtendedSto
  • 仅在 Linux 上通过命令行将 xlsx 转换为文本 CSV [关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 简单的问题 目前是否可以从命令行调用 LibreOffice 以打开 xlsx 并将其转换 另存为 csv 或者 如果这是不可能的 当前通过命令行执行
  • 使用 Javascript 生成 SVG 路径的库?

    我在用着Rapha l http raphaeljs com 满足我的 SVG 渲染需求 但我发现 Path 语法有点低级 那么有谁知道一个很好的 Javascript 包装器 库 它允许这样的事情 var pathStr move 10
  • 指针条件 while(*s1++=*s2++)

    int main char str1 Overflow char str2 Stack char s1 str1 s2 str2 while s1 s2 printf s str1 return 0 当这个条件被打破时 while s1 s
  • Python 并行计算 - Scoop

    我正在尝试熟悉 Scoop 库 此处的文档 https media readthedocs org pdf scoop 0 7 scoop pdf https media readthedocs org pdf scoop 0 7 scoo
  • ASP.NET 代码隐藏类中的静态方法是非线程安全的吗?

    我可以用吗static我的 ASP NET 中的方法Pages and UserControls如果类不使用任何实例成员 IE protected void gridView PageIndexChanging object sender
  • ggplot 未绘制正确的颜色[重复]

    这个问题在这里已经有答案了 gb lt read csv results gradient boosting csv p lt ggplot gb geom point aes x pred y y alpha 0 4 fill darkg
  • 本地 Laradock Nginx 项目上的 SSL 证书

    我需要你的帮助来在我的本地计算机上使用 Nginx 和 SSL 假 证书设置我的 Laradock 带有 Docker 我不知道如何设置它 请你帮助我好吗 Thanks 要使用当前版本的 laradock 截至 2019 年 11 月 使用
  • Ruby 连接字符串并添加空格

    我有 4 个字符串变量name quest favorite color speed那可能是空的 我想将它们连接在一起 在非空的之间添加空格 代码的简单性 即查看和理解的简单程度 比速度更重要 So name Tim quest destr
  • 如何在 CUDA 内核启动之间使用共享内存?

    我想在同一内核的多次启动中使用共享内存中的值 我可以这样做吗 不 你不能 共享内存具有线程块生命周期 存储在其中的变量可以被属于一组的所有线程访问 global 函数调用
  • 如何获取 Quartz 用于描边 NSBezierPath 的路径

    我使用这段代码用一条宽的黑色虚线来描画 NSBezierPath c and strForBezier在其他地方定义 NSGlyph glyph for n 0 n lt len n glyph font glyphWithName str
  • Kafka-MongoDB Debezium 连接器:分布式模式

    我正在研究 debezium mongodb 源连接器 我可以通过将 kafka bootstrap 服务器地址提供为远程计算机 部署在 Kubernetes 中 和远程 MongoDB url 来在本地计算机上以分布式模式运行连接器吗 我
  • Python functools.wraps 相当于类

    使用类定义装饰器时 如何自动转过来 name module and doc 通常 我会使用 functools 中的 wraps 装饰器 这是我为一个类所做的事情 这不完全是我的代码 class memoized Decorator tha
  • 按名称读取 javascript cookie

    我已经使用设置了一个cookie document cookie MYBIGCOOKIE value expires now toGMTString path 现在该网站上设置了 5 到 10 个 cookie 有没有办法通过名称检查该 c
  • 如何使用 Windows 身份验证在 IIS 上授权 CORS 预检请求

    我在 ASP net Core 2 Windows 身份验证 上有一个 API 在 Angular 上有一个前端 我做了一个 cors 配置来从 SPA 角度查询我的后端 但由于预检而被阻止 他被 IIS 服务器拒绝 因为他没有标识信息 错