【发布时间】:2021-01-22 06:04:47
【问题描述】:
我有一个使用 .NET Core 3.1 的 Blazor 应用程序。
我使用 Google 身份验证登录,如 @MichaelWashington https://blazorhelpwebsite.com/ViewBlogPost/19 撰写的本文所述
我将[Authorize] 添加到我的控制器中,并且只有登录用户才能访问我的控制器。
我还需要使用 API 密钥授予对控制器的访问权限。我关注了这篇由@JosefOttosson 撰写的文章:https://josef.codes/asp-net-core-protect-your-api-with-api-keys/ 当我将[Authorize] 替换为[Authorize(AuthenticationSchemes = AuthenticationConstants.ApiKeyDefaultScheme)] 时,这也能正常工作
但现在我无法通过 Blazer 网站访问我的控制器。所以我添加了[Authorize(AuthenticationSchemes = AuthenticationConstants.GoogleAuthenticationScheme)],但现在我得到了CORS错误:
Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=[...]
(redirected from 'https://localhost:44380/api/client/2/upload/foo')
from origin 'https://localhost:44380' 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.
我尝试了许多选项,但仍然不断收到此错误。用[Authorize] 替换两个[Authorize(AuthenticationSchemes ... 使我的前端再次工作,但我的邮递员呼叫(模仿第三方呼叫)失败。
如何结合这两种身份验证方法?
在public void Configure(IApplicationBuilder app)我有
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseHttpsRedirection();
app.UseStaticFiles();
在public void ConfigureServices(IServiceCollection services)我有在顶部:
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins, builder => builder
.WithOrigins("http://localhost:44380/")
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod()
.AllowAnyHeader());
});
【问题讨论】:
标签: authentication google-authentication blazor-server-side .net-core-3.1