Authentication 如何使用Blazor将Google身份验证和API密钥身份验证结合起来?

Authentication 如何使用Blazor将Google身份验证和API密钥身份验证结合起来?,authentication,google-authentication,blazor-server-side,.net-core-3.1,Authentication,Google Authentication,Blazor Server Side,.net Core 3.1,我有一个使用.NETCore3.1的Blazor应用程序。 我使用Google身份验证登录,如@MichaelWashington撰写的本文所述 我将[Authorize]添加到我的控制器,并且只有登录的用户才能访问我的控制器 我还需要使用API密钥授予对控制器的访问权限。我遵循了@JosefOttosson撰写的这篇文章:当我将[Authorize]替换为[Authorize(AuthenticationSchemes=AuthenticationConstants.apikeDefaultS

我有一个使用.NETCore3.1的Blazor应用程序。 我使用Google身份验证登录,如@MichaelWashington撰写的本文所述
我将
[Authorize]
添加到我的控制器,并且只有登录的用户才能访问我的控制器

我还需要使用API密钥授予对控制器的访问权限。我遵循了@JosefOttosson撰写的这篇文章:当我将
[Authorize]
替换为
[Authorize(AuthenticationSchemes=AuthenticationConstants.apikeDefaultScheme)]

但现在我无法通过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(iaapplicationbuilder应用程序)
中,我有

app.UseRouting();
应用程序UseCors(MyAllowSpecificCorigins);
app.UseHttpsRedirection();
app.UseStaticFiles();
public void ConfigureServices(IServiceCollection services)
中,我在顶部有:

services.AddCors(选项=>
{
options.AddPolicy(myAllowSpecificCorigins,builder=>builder
.来源(“http://localhost:44380/")
.SetIsOriginAllowed((主机)=>true)
.AllowAnyMethod()
.AllowAnyHeader());
});

我终于弄明白了。我当时很头疼,因为有时它能用,有时它不能用。当我注销,然后在前端使用谷歌身份验证再次登录时,它就不起作用了。
在登录代码中

wait HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
新的ClaimsPrincipal(谷歌用户),
版权所有),;
正在使用。请查看CookieAuthenticationDefaults.AuthenticationScheme。它正在使用/设置不同的方案

因此,添加
[Authorize(AuthenticationSchemes=CookieAuthenticationDefaults.AuthenticationScheme)]
后,我的控制器一直工作

我的控制器现在看起来像这样:

[授权(AuthenticationSchemes=AuthenticationConstants.GoogleAuthenticationScheme)]
[授权(AuthenticationSchemes=AuthenticationConstants.apikeDefaultScheme)]
[授权(AuthenticationSchemes=CookieAuthenticationDefaults.AuthenticationScheme)]
公共类元控制器:BaseApiController
我希望它能帮助别人。我花了两天时间;-)