我有一个使用.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(AuthenticationSchemes ...
替换两个[Authorize]
可以使我的前端再次工作,但我的邮递员呼叫(模仿第3方呼叫)失败。
如何结合这两种身份验证方法?
我在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());
});
答案 0 :(得分:1)
我终于明白了。我在敲头,因为有时它起作用了,有时却没有。当我注销后再使用Google身份验证在前端再次登录时,它再也没有作用。
在登录代码中
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(GoogleUser),
authProperties);
使用。观看CookieAuthenticationDefaults.AuthenticationScheme
。它正在使用/设置其他方案。
因此,添加[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
后,我的控制器将一直工作。
我的控制器现在看起来像这样:
[Authorize(AuthenticationSchemes = AuthenticationConstants.GoogleAuthenticationScheme)]
[Authorize(AuthenticationSchemes = AuthenticationConstants.ApiKeyDefaultScheme)]
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public class MetaController : BaseApiController
我希望它可以帮助其他人。我花了两天时间;-)