代码之家  ›  专栏  ›  技术社区  ›  Slava

实现Google Open ID Connect的正确方法是什么。净核心2.1?

  •  0
  • Slava  · 技术社区  · 6 年前

    我正在努力学习ASP。NET核心身份验证选项,请遵循Pluralsight培训。在培训中,他们使用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();
        }
    

    在应用程序设置中。我定义了这些:

    {
        "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"
        }
    }
    

    然而,当我运行应用程序时,我得到的不是谷歌登录屏幕,而是一个错误:

    处理请求时发生未经处理的异常。 InvalidOperationException:向OpenIdConnectOptions提供权限、元数据地址、配置或配置管理器 微软AspNetCore。认证。OpenIdConnect。OpenIdConnectOptions。验证()


    InvalidOperationException:向OpenIdConnectOptions提供权限、元数据地址、配置或配置管理器 微软AspNetCore。认证。OpenIdConnect。OpenIdConnectOptions。验证() 微软AspNetCore。认证。RemoteAuthenticationOptions。验证(字符串方案) 微软AspNetCore。认证。AuthenticationHandler。InitializeAsync(AuthenticationScheme,HttpContext上下文) 微软AspNetCore。认证。AuthenticationHandlerProvider。GetHandlerAsync(HttpContext上下文,字符串身份验证方案) 微软AspNetCore。认证。认证中间件。调用(HttpContext上下文) 微软AspNetCore。静态文件。静态文件中间件。调用(HttpContext上下文) 微软AspNetCore。诊断学。developerCeptionPageMiddleware。调用(HttpContext上下文)

    我做错了什么?

    ClientID和ClientSecret是在Google开发者控制台中定义的。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Llazar    5 年前

    在Startup类中添加此方法。

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