【问题标题】:How to combine Google Authentication and API key Authentication using Blazor?如何使用 Blazor 结合 Google 身份验证和 API 密钥身份验证?
【发布时间】: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


    【解决方案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
    

    我希望它可以帮助其他人。我花了两天时间;-)

    【讨论】:

      猜你喜欢
      • 2020-09-20
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 2013-11-03
      • 2019-02-17
      • 2011-07-25
      相关资源
      最近更新 更多