我一直在尝试在ASP.NET Core 2.2 / Angular 7项目上设置Discord Oauth2令牌认证,这是一个坎bump的旅程。
我正在使用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
还有其他想法吗?
答案 0 :(得分:0)
我今天遇到了类似的问题,但后来发现了。确保您使用的是相同版本的网络核心。我碰巧同时使用了2.1和2.2软件包。