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")));
        return Unauthorized();
    return Redirect("~/Index");

And this is how look Startup.cs

services.AddScoped<IAuthenticationService, LdapAuthenticationService>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
    options.LoginPath = "/Account/SignIn";


   .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?


Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply