实施Google Open ID与.NET Core 2.1的正确方法是什么?

问题描述 投票:0回答:1

我正在尝试通过遵循Pluralsight培训来学习ASP.NET核心身份验证选项。在该培训中,他们使用Azure进行身份验证。

我想用谷歌。以下是添加Google Auth的代码:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddOpenIdConnect(options =>
        {
            _configuration.Bind("Google", options);
        })
        .AddCookie();

        services.AddSingleton<IGreeter, Greeter>(); // Dependency Injection for custom service Greeter
        services.AddDbContext<OdeToFoodDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("OdeToFood")));
        services.AddScoped<IRestaurantData, SqlRestaurantData>(); // scoped to http transaction, dbcontext is not thread safe
        services.AddMvc();
    }

在appsettings.json我有这些定义:

{
    "Google": {
        "ClientId": "234092845903-n92krp955lrp46mdf445g5vo0sqp2eks.apps.googleusercontent.com",
        "ClientSecret": "bRg1flFud87hfsef89jMKoGW"
    },
    "Greeting":  "Hello from appsettings.json !!",
    "ConnectionStrings": {
        "OdeToFood": "Server=(localdb)\\MSSQLLocalDB;Database=OdeToFood;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
}

但是,当我运行应用程序而不是Google登录屏幕时,我收到错误消息:

处理请求时发生未处理的异常。 InvalidOperationException:向OpenIdConnectOptions提供Authority,MetadataAddress,Configuration或ConfigurationManager Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectOptions.Validate()


InvalidOperationException:向OpenIdConnectOptions提供Authority,MetadataAddress,Configuration或ConfigurationManager Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectOptions.Validate()Microsoft.AspNetCore.Authentication.RemoteAuthenticationOptions.Validate(string scheme)Microsoft.AspNetCore.Authentication.AuthenticationHandler.InitializeAsync(AuthenticationScheme) scheme,HttpContext context)Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context,string authenticationScheme)Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)Microsoft.AspNetCore .Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我究竟做错了什么?

ClientID和ClientSecret在Google Developers Console中定义。

asp.net-core google-authentication
1个回答
1
投票

在Startup类中添加此方法。

services.AddAuthentication().AddGoogle(googleOptions => { googleOptions.ClientId = Configuration["Authentication:Google:ClientId"]; googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"]; });

© www.soinside.com 2019 - 2024. All rights reserved.