Search code examples
c#asp.netauthenticationrazor-pages

After SignIn User.Identity.Name is empty, but User.Identity.IsAuthenticated is set right


Application is developed in Razor Pages ASP.NET Core

I am signing in user through LDAP this way:

public async Task<IActionResult> OnPostAsync()
{
    var user = authService.Login(UserName, Password);
    if (null != user)
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, UserName),
            
        };
        ClaimsIdentity identity = new ClaimsIdentity(claims, "Cookies", "user", "role");
        
        await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies", "user", "role")));
    }
    else
    {
        return Unauthorized();
    }
    return Redirect("~/Index");
} 

And this is how look Startup.cs

services.Configure<LdapConfig>(Configuration.GetSection("Ldap"));
services.AddScoped<IAuthenticationService, LdapAuthenticationService>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
    options.LoginPath = "/Account/SignIn";

});           

services
   .ConfigureApplicationCookie(options =>
   {
       options.Cookie.Name = "TicketTracker.ldap.identity";
       options.Cookie.HttpOnly = true;
       options.Cookie.Expiration = TimeSpan.FromDays(150);
       options.LoginPath = "/Account/Signin"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
       options.LogoutPath = "/Account/Signout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
       options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
       options.SlidingExpiration = true;
       options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
   }); 

Everything works fine about authetication, but I can not acces the name of current user which is signed in.

Does anybody know what to do?

Thanks!


Solution

  • Issue solved myself thanks for no help!

    options.Cookie.Name = "TicketTracker.ldap.identity";
    

    It was at this line, I just replace it with

    options.Cookie.Name = ".AspNetCore.Cookies";
    

    Because name of the cookie is created by claim identity which I am passing trough SignInAsync method.

    Work fine now.