sangeun jo
sangeun jo

Reputation: 59

System.Security.Claims.ClaimsPrincipal.Identities return null

I trying to make social login in .NET Core 6.0 using Microsoft.AspNetCore.Authentication.Google nuget package.

But I encountered this error:

enter image description here

This is my AccountController:

using netcore_social_login.Dtos;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Mvc;

namespace netcore_social_login.Controllers
{
    [Route("account")]
    public class AccountController : Controller
    {
        private AuthenticationProperties _authenticationProperties;

        [HttpGet("login")]
        public IActionResult GoogleLogin()
        {
            var properties = new AuthenticationProperties
            {
                RedirectUri = Url.Action("GoogleLoginProc")
            };
            _authenticationProperties = properties;

            return Challenge(properties, GoogleDefaults.AuthenticationScheme);
        }

        [HttpGet("signin-google")] 
        public async Task<IActionResult> GoogleLoginProc()
        {
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            var identities = result.Principal.Identities //it returns null
                .FirstOrDefault()
                .Claims.Select(claim => new ClaimJson
                {
                    Issuer = claim.Issuer,
                    OriginalIssuer = claim.OriginalIssuer,
                    Type = claim.Type,
                    Value = claim.Value,
                    ValueType = claim.ValueType
                });

            var providerKey = identities
                .Where(x => x.Type.Equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"))
                .Select(x => x.Value)
                .FirstOrDefault();

            var emailAddress = identities
                .Where(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")
                .Select(x => x.Value)
                .FirstOrDefault();

            return RedirectToAction("Index", "Home");
        }
    }
}

And this is the Home/Index view:

@{
    ViewData["Title"] = "Home Page";
    Layout = null;
}

<h1>Sns Login Example</h1>
<ul>
    <li><a asp-controller="Account" asp-action="GoogleLogin">Google login</a></li>
    <li><a href="#">Facebook login</a></li>
    <li><a href="#">Kakao logn</a></li>
</ul>

Here is my Program.cs code file:

using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromSeconds(10);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
    options.Cookie.Name = ".Cookies.NetCoreSocialLogin";
    options.LoginPath = new PathString("/account/login");
    options.LogoutPath = new PathString("/account/logout");
    options.AccessDeniedPath = new PathString("/error/403");
})
.AddGoogle(options =>
{
    options.CallbackPath = "/account/signin-google"; //if I removed this line, it would raise url mismatch error. 
    options.ClientId = "client id";
    options.ClientSecret = "secret";
});


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.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

And the URI of google web client ID is

https://localhost:44378/account/signin-google

I think everything is correct but I don't know why its not working.

If you have a code example of .NET Core social login, please leave link.

Thank you.

Upvotes: 0

Views: 2480

Answers (2)

sangeun jo
sangeun jo

Reputation: 59

I found a google example for the netcore google login.

https://youtu.be/6nQf76HF20A

And this is my code for netcore 6.0.

https://github.com/sangeun-jo/NetCoreSocialLoginExample/tree/65f9118e367c8915294e3b1dca25281b27894b39

Upvotes: 1

Qing Guo
Qing Guo

Reputation: 9092

var identities = result.Principal.Identities //it returns null

Below is a demo about your Identities return null question, you can refer to it.

In Program.cs:

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
    options.Cookie.Name = ".Cookies.NetCoreSocialLogin";
    options.LoginPath = new PathString("/account/signin-google");
   
})
.AddGoogle(options =>
{
  
    options.ClientId = "xxxx";
    options.ClientSecret = "xxxx";// add  your OAuth credentials
});

In AccountController:

    [AllowAnonymous, Route("account")]
    public class AccountController : Controller
    {
        [Route("signin-google")]
        public IActionResult GoogleLogin()
        {
            var properties = new AuthenticationProperties { RedirectUri = Url.Action("GoogleResponse") };
            return Challenge(properties, GoogleDefaults.AuthenticationScheme);
        }

        [Route("google-response")]
        public async Task<IActionResult> GoogleResponse()
        {
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            var claims = result.Principal.Identities
                .FirstOrDefault().Claims.Select(claim => new
                {
                    claim.Issuer,
                    claim.OriginalIssuer,
                    claim.Type,
                    claim.Value
                });

            return Json(claims);
        }
    }

result:

enter image description here

Upvotes: 1

Related Questions