我正在尝试通过遵循Pluralsight培训来学习ASP.NET Core身份验证选项。在该培训中,他们使用Azure进行身份验证。
我想使用Google。这是添加Google身份验证的代码:
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提供授权,MetadataAddress,Configuration或ConfigurationManager Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectOptions.Validate()
InvalidOperationException:向OpenIdConnectOptions提供授权,MetadataAddress,Configuration或ConfigurationManager Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectOptions.Validate() Microsoft.AspNetCore.Authentication.RemoteAuthenticationOptions.Validate(字符串方案) Microsoft.AspNetCore.Authentication.AuthenticationHandler.InitializeAsync(AuthenticationScheme方案,HttpContext上下文) Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext上下文,字符串authenticationScheme) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext上下文) Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext上下文) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)
我在做什么错了?
ClientID和ClientSecret在Google Developers Console中定义。
答案 0 :(得分:1)
在Startup类中添加此方法。
services.AddAuthentication().AddGoogle(googleOptions =>
{
googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});