简体   繁体   English

在 C# MVC 结果中使用 OAuth2 来自谷歌的 null 原则失败

[英]Using OAuth2 in C# MVC result from google fails with null principle

The goal is to implement OAuth2 against Google in a C# MVC app using .NET6.目标是使用 .NET6 在 C# MVC 应用程序中针对 Google 实施 OAuth2。 The result I get shows failed in the result.Succeeded field and all values are null.我得到的结果在 result.Succeeded 字段中显示失败,所有值都是 null。

I'm sending the correct google client id and google client secret.我正在发送正确的谷歌客户端 ID 和谷歌客户端密码。

The app builds and sends off the request without an error.该应用程序构建并发送请求而不会出现错误。 I believe that is all correct.我相信这都是正确的。

Here's my Program.cs这是我的 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();

Here's the account controller that sends and receives the result:这是发送和接收结果的帐户 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);
        }
    }

在此处输入图像描述

Not sure what is wrong.不知道出了什么问题。

Thanks for the help.谢谢您的帮助。

Added: Not sure if this is helpful, but the payload that I'm getting back from Google:补充:不确定这是否有帮助,但我从谷歌返回的有效负载:

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 prompt: consent 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 提示:同意

Found the issue.发现问题。 I was not configuring authorization and authentication to the application.我没有为应用程序配置授权和身份验证。 (I was doubly adding authorization.) Specifically, this line when placed in Configure method in StartUp.cs fixed the problem: (我是加倍授权。)具体来说,这一行放在 StartUp.cs 的 Configure 方法中时解决了这个问题:

app.UseAuthentication();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM