ASP.NET Core 2 : Ajax calls to API with [Authorize] fail the preflight request

拥有回忆 提交于 2019-12-12 22:21:17

问题


I have an API controller with the [Authorize] attribute to ensure all calls are made by properly logged-in users (via OpenIdConnect, targeting Azure AD) . When I load the page that makes the Ajax calls, the API responds properly.

However, after a certain amount of time, the user has to be reauthorized, and thus a call to https://login.microsoftonline.com/ is made by the ASP.NET Core framework to reauth the user. That calls fails with the following error:

Failed to load https://login.microsoftonline.com/common/oauth2/authorize?[truncated]: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://my.website.com' is therefore not allowed access.

I tried to configure the CORS header with this code, but that doesn't solve my issue:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // allow reconnection on API calls
    app.UseCors(builder => builder
        //.WithOrigins("https://login.microsoftonline.com")
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials()
    );

    app.UseMvc();
}

Note that ASP.NET Core version 1.0 didn't have that issue (though ASP.NET MVC 5 did).


回答1:


I found a workaround to my problem.

I didn't solve the preflight request CORS issue. login.microsoftonline.com doesn't include CORS headers, so I'm not even sure it can be solved.
However, I found a way to increase the cookie timeout, to decrease the need to re-auth the user.

When using Microsoft.AspNetCore.Identity, there are several cookies:

  • the IdentityConstants.ApplicationScheme cookie
  • the IdentityConstants.ExternalScheme cookie
  • the IdentityConstants.TwoFactorRememberMeScheme cookie
  • the IdentityConstants.TwoFactorUserIdScheme cookie

The one used for AJAX requests is the IdentityConstants.ExternalScheme cookie, which by default is set to expire after 5 minutes (you can see the defaults on github).

To increase the external cookie timeout:

services.ConfigureExternalCookie(options =>
{
    options.ExpireTimeSpan = TimeSpan.FromDays(14);
});


来源:https://stackoverflow.com/questions/48439791/asp-net-core-2-ajax-calls-to-api-with-authorize-fail-the-preflight-request

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