【发布时间】:2019-07-09 07:37:27
【问题描述】:
我一直在尝试在 ASP.NET Core 2.2 / Angular 7 项目上设置 Discord Oauth2 令牌身份验证,但过程相当坎坷。
我正在使用this
我似乎真的找不到任何示例来提供超过设置这一切所需的解释的一小部分。我目前正在处理的错误如下:
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"});
}
...
}
我一直在尝试什么
我尝试关注this
我尝试了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.UseCors() 在 app.useMvc 之前被调用
还有其他想法吗?
【问题讨论】:
-
添加
AllowAnyMethod有影响吗? -
@John 不幸的是,我试过了
-
绝对是针对您的 API 的 CORS 请求失败了吗?阅读该消息,我不相信它是。当然,我可能是错的。
-
是的,它是说
discordapp.com拒绝允许从localhost:5000运行的您的 应用程序访问它。如果他们甚至允许授权基于localhost的应用程序,那么在discordapp.com端进行配置也是可行的。 -
我希望您需要将您的网络应用程序重定向到
http://localhost:5000/api/v1/Authentication/SignIn,而不是向那里发出 XHR 请求。