繁体   English   中英

为什么此CORS政策无法使用ASP.NET Core

[英]Why is this CORS policy not working ASP.NET Core

我一直在尝试在ASP.NET Core 2.2 / Angular 7项目上设置Discord Oauth2令牌认证,这是一个相当坎bump的过程。

我正在用这个

我似乎真的找不到任何示例,这些示例所提供的解释仅占全部内容的一部分。 我当前正在处理的错误如下:

Access to XMLHttpRequest at 'https://discordapp.com/oauth2/authorize?client_id=<removed>&scope=identify&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fsignin-discord&state=<removed>'
(redirected from 'http://localhost:5000/api/v1/Authentication/SignIn') from origin 'http://localhost:5000' 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

对于上下文,这是我的一些代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder => builder.WithOrigins("http://localhost:5000").AllowAnyHeader());
    });
    ...
    services.AddAuthentication(options =>
        {
            options.DefaultScheme = DiscordAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = DiscordAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.LoginPath = "/login";
            options.LogoutPath = "/signout";
            options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
            options.SlidingExpiration = true;
        })
        .AddDiscord(options =>
        {
            options.ClientId = "<removed>";
            options.ClientSecret = "<removed>";
            options.Scope.Add("identify");
        });
    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseCors("AllowAll");
    ...
}

// in AuthenticationController.cs
public class AuthenticationController : Controller
{
    [HttpPost("[action]")]
    public IActionResult SignIn()
    {
        return Challenge(new AuthenticationProperties {RedirectUri = "http://localhost:5000"});
    }
    ...
}

我一直在尝试

我尝试遵循

我尝试了所有这些services.addCors()app.UseCors()组合都无济于事

services.AddCors();
app.UseCors(builder =>
   builder.WithOrigins("http://localhost:5000").AllowAnyHeader());

services.AddCors();
app.UseCors(builder =>
   builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

以及两者之间的一切。 无论我对cors做什么,该错误都不会改变。 另外,是的,我安装了Microsoft.AspNetCore.Cors nu-get软件包。 是的,在app.useMvc之前调用了app.UseCors()

还有其他想法吗?

我今天遇到了类似的问题,但后来发现了。 确保您使用的是相同版本的网络核心。 我碰巧同时使用了2.1和2.2软件包。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM