使用 Azure Active Directory 验证 .NET Core 2.2 API 时出现 CORS 错误

2024-03-15

我正在尝试在基于 Visual Studio 2019.Core 2.2 的基本 .NET Core 2.2 + React 项目模板构建的网页上使用 AzureAD 设置多租户 OpenId 身份验证。Core 2.2 因为 3.0 上的身份验证中间件根本没有触发对于任何配置,这似乎是一个常见问题,并且有关 Core 3.x 身份验证的文档很少,有时甚至是矛盾的。我想我已经尝试了一切,但现在我却不知所措。

这里,当调用 API 时,身份验证中间件似乎根据服务器输出正确启动:

From javascript:
    // Tried also without custom headers and trying to make the middleware handle the thing by itself
    fetch('api/SampleData/WeatherForecasts', {
      method: "get",
      headers: new Headers({
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "true"
      })
    })

Server output:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:44363/api/SampleData/WeatherForecasts  
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
      Executing endpoint '********.Controllers.SampleDataController.WeatherForecasts (******)'
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Route matched with {action = "WeatherForecasts", controller = "SampleData", area = "", page = ""}. Executing controller action with signature System.Collections.Generic.IEnumerable`1[******.Controllers.SampleDataController+WeatherForecast] WeatherForecasts() on controller ******.Controllers.SampleDataController (*********).
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[12]
      AuthenticationScheme: AzureADOpenID was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action *****.Controllers.SampleDataController.WeatherForecasts (*******) in 439.0343ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint '******.Controllers.SampleDataController.WeatherForecasts (*******)'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 464.9224ms 302 

但当返回 HTTP 200 响应时,我总是在浏览器中收到 cors 错误:

Access to fetch at 'https://login.microsoftonline.com/common/oauth2/authorize?client_id=**********************&redirect_uri=https%3A%2F%2Flocalhost%3A44363%2Fsignin-oidc&response_type=id_token&scope=openid%20profile&response_mode=form_post&nonce=**************************************************&x-client-SKU=ID_NETSTANDARD2_0&x-client-ver=5.3.0.0' (redirected from 'https://localhost:44363/api/SampleData/WeatherForecasts') from origin 'https://localhost:44363' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我可以手动打开登录页面,但浏览器因此无法重定向。我什至将该应用程序发布为 Azure Web App,但仍然遇到相同的 CORS 错误。我认为我已经在 Startup.cs 中正确设置了所有内容,但似乎没有任何效果。然后我什至从 Azure Web App 设置了 cors-policy 以允许 * 来源,然后允许相关来源,但问题仍然存在。

启动.cs:

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

      services.AddSpaStaticFiles(configuration => {
        configuration.RootPath = "ClientApp/build";
      });

      services.Configure<CookiePolicyOptions>(options => {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
      });

      services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
          .AddAzureAD(options => Configuration.Bind("AzureAd", options)).AddCookie();

      services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => {
        options.TokenValidationParameters = new TokenValidationParameters {
          ValidateIssuer = false,
        };

        options.Events = new OpenIdConnectEvents {
          OnTicketReceived = context => {
            return Task.CompletedTask;
          },
          OnAuthenticationFailed = context => {
            context.Response.Redirect("/Error");
            context.HandleResponse(); // Suppress the exception
            return Task.CompletedTask;
          }
        };
      });
      /*
      Tried also with this
      services.AddCors(setup => {
        setup.AddPolicy("corspolicy", policy => {
          policy
          .AllowAnyOrigin()
          .AllowAnyHeader()
          .AllowAnyMethod();          
        });
      });
      */
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      } else {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
      }

      app.UseAuthentication(); // Tried putting this and .UseCors to different places
      app.UseStaticFiles();
      app.UseSpaStaticFiles();
      //app.UseCors("corspolicy"); 
      app.UseCors(policy => {
        policy
        .AllowAnyOrigin() // Tried with hardcoded origins
        .AllowAnyMethod()
        .AllowCredentials() // Tried without this also
        .AllowAnyHeader();        
      });
      app.UseHttpsRedirection();

      app.UseMvc(routes => {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
      });
      app.UseSpa(spa => {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment()) {
          spa.UseReactDevelopmentServer(npmScript: "start");
        }
      });
    }

控制器:

  [Authorize]
  [EnableCors] // Tried with named policy and without EnableCors
  [ApiController] // Tried without this
  [Route("api/[controller]")]
  public class SampleDataController : Controller
  {
    private static string[] Summaries = new[]
    {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

    [HttpGet("[action]")]
    public IEnumerable<WeatherForecast> WeatherForecasts()
    {
      var rng = new Random();
      return Enumerable.Range(1, 5).Select(index => new WeatherForecast {
        DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
      });
    }
   // Nonrelevant things omitted
  }

经过长时间的调查,你的问题的简短答案是“你无法通过 ajax 请求来实现它”。实际上,您需要浏览器转到您发出“挑战”请求的控制器。 这篇文章解释了一切:https://www.blinkingcaret.com/2018/10/10/sign-in-with-an-external-login-provider-in-an-angular-application-served-by-asp-net-core/ https://www.blinkingcaret.com/2018/10/10/sign-in-with-an-external-login-provider-in-an-angular-application-served-by-asp-net-core/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Azure Active Directory 验证 .NET Core 2.2 API 时出现 CORS 错误 的相关文章

随机推荐

  • 获取 WhatsApp 消息

    是否可以创建一个监听器来获取消息whatsApp在安卓中 我的意思是就像你有一个broadcastReceiver在android中收听传入的短信 这件事是否需要任何 API 或者这是合法的事情 还是我需要获得任何许可whatsApp Wh
  • 如何在没有源代码的情况下在类中放置断点?

    我有一个 Web 应用程序 我需要找到访问 http 请求对象的所有类 因为其中一个类导致了难以发现的错误 因此我想在ServletRequest实现的一些方法中放置断点 然而 这个实现是由 Weblogic 提供的 我没有其来源 如何在没
  • GeoChart:标记加载速度非常慢

    google charts load current packages geochart google charts setOnLoadCallback drawRegionsMap function drawRegionsMap var
  • 使用 iconv 将 UTF8 转换为 UTF16

    当我使用 iconv 从 UTF16 转换为 UTF8 时 一切都很好 但反之亦然 它不起作用 我有这些文件 a 16 strings Little endian UTF 16 Unicode c program text a 8 stri
  • Android-布局的正确定位

    我似乎无法按照我想要的方式正确定位我的布局 我的布局看起来像这样 LinearLayout LinearLayout ListView LinearLayout TextView TextView TextView Button 我的目标是
  • 如何更改全局 .vscode 文件夹的位置?

    我正在 Linux 上设置 Visual Studio Code 由于机器是共享的 我的 HOME文件夹的大小受到限制 没有空间容纳扩展名 存储在 HOME vscode 我尝试安装它们失败了 我在其他开发目录上确实有足够的空间 但我找不到
  • 从 Android 通讯录中删除联系人

    我正在尝试从手机通讯录中删除联系人 该联系人会从手机联系人中删除 但不会从服务器端 Google 联系人 中删除 并且当 Google 联系人同步触发时 已删除的联系人会重新出现 下面是我的代码 public static void del
  • BIRT:无法检索 XML 数据源。 XML 数据源文件无效或该文件不存在

    我创建了一个 XML 数据源 用于从本地应用程序获取 XML 数据 创建数据集时出现以下错误 org eclipse datatools connectivity oda OdaException XML data source canno
  • Python:剥离除数字之外的所有内容

    我必须从几个字符串中的每个字符串中提取一个数字 测量的时间值 我怎样才能优雅地做到这一点 所有数字均为正数 且最多保留两位小数 例如 2 3 40 09 101 4 E 表示法中没有数字 我正在寻找的代码应该执行类似于以下伪代码的操作 gt
  • Swift 中未宣布辅助功能自定义操作

    当我添加accessibilityCustomActions对于一个对象 它在设备上可以正常工作 只要能够上下滑动操作并选择它们 但没有任何公告表明有 可用操作 我应该将其写入accessibilityLabel myself 我认为通过将
  • 如何查明实体框架对象是否已更改?

    我有一个叫做Uczestnik刚刚保存到数据库 var konsultant uczestnik Konsultanci uczestnik Konsultanci null null attached object and reuse i
  • 如何检测仅包含空格的字符串?

    包含一个空格的字符串长度始终等于 1 alert My str length str length 空格是一个字符 所以 str alert My str length str length My str length 3 如何区分空字符串
  • 使用 Dygraphs 绘制图表:根据缩放进行数据采样

    尽管与其他解决方案相比 Dygraphs 的性能非常好 但当查看越来越多的数据点时 性能不可避免地会变慢 我已经在本地加载了所有数据 Dygraphs 有没有办法智能地显示较低的分辨率 就数据点数量而言 然后在缩放时显示更多内容 虽然没有内
  • 同一解决方案中的 MVC 和 Web API 项目

    我不久前创建了一个解决方案 其中包含一个 Web API 2 项目 向移动设备提供 JSON 数据 和一个类库 包括我的数据访问服务 Web API 项目使用 Ninject 进行 DI 一切正常 现在我需要为几个网页添加一个单独的 MVC
  • 如何在 Odoo 12 中使用 Python XML-RPC 注册付款

    首先我创建了这个函数 def invoiceRegisterPayment self register payment row confirm result self ODOO OBJECT execute kw self DATA sel
  • 如何设置SBT的默认项目

    假设我有一个包含三个项目的构建 A B 和 C 如果我当前处于 A 的上下文中并重新加载构建 则重新加载后可能会将上下文更改为 C 因此 每次重新加载后我都必须更改项目上下文 有没有办法将特定项目设置为默认上下文 SBT 选择第一个词法项目
  • 来自服务器的错误:拨打后端时出错:拨打 tcp 10.9.84.149:10250: getsockopt: 连接被拒绝

    我有一个包含三个节点的 kubernetes 集群 10 9 84 149 10 9 105 90 and 10 9 84 149 当我的应用程序尝试在某个 pod 内执行命令时 kuebctl exec it
  • 使用 powershell 合并两个相似但两列不同的表

    我需要连接在 Powershell 中创建的两个表 问题在于 在它们共享的 5 列中 每个表中有两列不同 我怎样才能连接这两个表 然后能够对它们进行排序 我猜我会让两个人做以下事情 例子 表格1 列 a b c d e 表2 a x c d
  • 带分支的 Git LFS 的工作流程是什么?

    我已将 Git LFS 引入到我在 bitbucket org 上的一个存储库中 分叉此存储库的用户无法推送到他们的分叉 因为那里没有空间可容纳 LFS 文件 我的理解是 当您在那里分叉存储库时 LFS 文件不会被复制 将 Git LFS
  • 使用 Azure Active Directory 验证 .NET Core 2.2 API 时出现 CORS 错误

    我正在尝试在基于 Visual Studio 2019 Core 2 2 的基本 NET Core 2 2 React 项目模板构建的网页上使用 AzureAD 设置多租户 OpenId 身份验证 Core 2 2 因为 3 0 上的身份验