【问题标题】:No authenticationScheme was specified, and there was no DefaultChallengeScheme found没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme
【发布时间】:2019-11-02 16:27:34
【问题描述】:

尝试将 Google Token Validation 添加到 asp.Net Core 2.2 API,但当 Controller 标记为 [Authorize] 时出现此错误

目标是通过验证请求标头中的 Access_Token 来保护某些 Web API 功能。 Access Token 是从客户端的 Google OAuth 生成的,需要随每个请求传递给 API。

Startup.cs

public void ConfigureServices(IServiceCollection services)
    ...
    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddGoogle(options =>
    {
        options.ClientId = "[Client ID]";
        options.ClientSecret = "[Client secret]";
    });
    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseAuthentication();

    app.UseMvc();
}

得到以下错误:

处理请求时发生未处理的异常。 InvalidOperationException:未指定 authenticationScheme,并且 没有找到 DefaultChallengeScheme。

【问题讨论】:

    标签: asp.net-core asp.net-core-webapi


    【解决方案1】:

    According to documentation 您无需指定AuthenticationScheme 进行 Google 身份验证

    services.AddAuthentication().AddGoogle(options  =>  
    {  
       ...
    }); 
    

    因为OpenIdConnectDefaults.AuthenticationScheme 的值是OpenIdConnect,但Google 期望Google。你可以使用GoogleDefaults.AuthenticationScheme

    【讨论】:

    • 删除了 (OpenIdConnectDefaults.AuthenticationScheme) 并且仍然得到同样的错误。 InvalidOperationException:没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme。
    • 更改为以下服务。AddAuthentication(cfg => { cfg.DefaultAuthenticateScheme = "Google"; cfg.DefaultChallengeScheme = "Google"; }) .AddGoogle(options => { options.ClientId = ". .."; options.ClientSecret = "..."; });现在运行VS项目后,它在运行后立即崩溃并出现以下错误:程序'[34716] iisexpress.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'。
    • 也可以试试[Authorize(AuthenticationSchemes = GoogleDefaults.AuthenticationScheme)]
    • 如果没有 IIS Express,我就无法运行。还使用了 [Authorize(AuthenticationSchemes = GoogleDefaults.AuthenticationScheme)] 仍然是同样的错误
    • 与问题中或评论中相同的错误?然后尝试在没有 iisexpress 的情况下运行它。或者尝试从评论中删除代码并使用 [Authorize(AuthenticationSchemes = GoogleDefaults.AuthenticationScheme)]。查看示例here
    猜你喜欢
    • 1970-01-01
    • 2018-02-26
    • 2021-10-18
    • 2019-03-22
    • 1970-01-01
    • 2019-08-02
    • 2021-05-24
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多