如何在 .Net Core 6 中传递 google 身份验证的客户端 ID

How to pass the Client Id for google authetication in .Net Core 6

我正在尝试在 .Net Core 6 中使用 google 身份验证。我已经在 google 开发人员控制台中生成了凭据并添加到代码中。


using LoginKud.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<AppDbContext>();

builder.Services.AddAuthentication().AddGoogle(options => {
    options.ClientId = builder.Configuration["591241482908-66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com"];
    options.ClientSecret = builder.Configuration["GOCSPX-jHKaxxxxxxx"];
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();

app.Run();


我已经提供了客户 ID 和客户秘密 ID,但我得到了 The 'ClientId' option must be provided. (Parameter 'ClientId') 错误 每次我运行这个程序。我该如何解决?

我认为问题出在这两行内:

   options.ClientId = builder.Configuration["591241482908-66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com"];
options.ClientSecret = builder.Configuration["GOCSPX-jHKaxxxxxxx"];

您应该将设置中的键传递给那里,而不是值。

暂时尝试直接传递值:

   options.ClientId = "591241482908 66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com";
   options.ClientSecret = "GOCSPX-jHKaxxxxxxx";

如果它有助于输入您的配置键和值,如下所示:

"clientId":"591241482908 66qgk38nbf1un6mxxxxxxxxxx.apps.googleusercontent.com",
"clientSecret":"GOCSPX-jHKaxxxxxxx"

并将您的代码重写为:

options.ClientId = builder.Configuration["clientId"];
options.ClientSecret = builder.Configuration["clientSecret"];