简体   繁体   中英

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. The result I get shows failed in the result.Succeeded field and all values are null.

I'm sending the correct google client id and google client secret.

The app builds and sends off the request without an error. I believe that is all correct.

Here's my 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:

    [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

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:

app.UseAuthentication();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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