[英]Using OAuth2 in C# MVC result from google fails with null principle
目標是使用 .NET6 在 C# MVC 應用程序中針對 Google 實施 OAuth2。 我得到的結果在 result.Succeeded 字段中顯示失敗,所有值都是 null。
我正在發送正確的谷歌客戶端 ID 和谷歌客戶端密碼。
該應用程序構建並發送請求而不會出現錯誤。 我相信這都是正確的。
這是我的 Program.cs
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false)
.Build();
var googleClientId = config.GetValue<string>("GoogleClientId");
var googleClientSecret = config.GetValue<string>("GoogleClientSecret");
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddGoogle(options =>
{
options.ClientId = googleClientId;
options.ClientSecret = googleClientSecret;
options.CallbackPath = "/account/google-response";
}).AddCookie(options =>
{
options.LoginPath = "/account/google-login"; // Must be lowercase
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/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.UseAuthorization();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
這是發送和接收結果的帳戶 controller:
[AllowAnonymous, Route("account")]
public class AccountController : Controller
{
[Route("google-login")]
public IActionResult GoogleLogin()
{
var properties = new AuthenticationProperties { RedirectUri = Url.Action("GoogleResponse") };
return new ChallengeResult(GoogleDefaults.AuthenticationScheme, properties);
}
[Route("google-response")]
public async Task<IActionResult> GoogleResponse()
{
var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
// This is coming back with result.Succeeded == false, and result.Principal == null
var succeeded = result.Succeeded;
if (result.Principal == null) throw new Exception("Principal is null");
if (result.Principal.Identities == null) throw new Exception("Identities is null");
var claims = result.Principal.Identities
.FirstOrDefault().Claims.Select(claim => new
{
claim.Issuer,
claim.OriginalIssuer,
claim.Type,
claim.Value
});
return Json(claims);
}
}
不知道出了什么問題。
謝謝您的幫助。
補充:不確定這是否有幫助,但我從谷歌返回的有效負載:
state: CfDJ8Dcp9PtNslFFr9WdoNMnaxZuUE3bX_7go4zy8_XDg2ZIar8NvdxzZlhJ9mM9c8-E3cp9TchRcjvMwbX4XaMmTC79aKO7IuI39yHgZ6nrOEqORPDU9kfHGH-bgJB5S1bXIQcJ3y3wKMD39N6IDa-ygAxqoiFkd05Lf05d9RoA8bZ0h8DcbYbqpbK73rQraTQhBAdxVJlz2CLGXkzOhIoJmhdOn38poxjNILyGPOGRqA0t code: 4/0AX4XfWjHBoCnvig2U2JG8tuPnqIvjQeC5VN_u_pSOcqIFFOjw7UadqI04qJ3iw4QyF2ngg scope: email profile openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email authuser : 0 提示:同意
發現問題。 我沒有為應用程序配置授權和身份驗證。 (我是加倍授權。)具體來說,這一行放在 StartUp.cs 的 Configure 方法中時解決了這個問題:
app.UseAuthentication();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.