2

Using custom identity database instead of ASP.NET core Identity and authenticating via cookie! (cookie auth works as expected however "User.Identity.Name" is always empty?)

How do I set and get the claim identity name "User.Identity.Name" ?

var claims = new[] { new Claim("name", "john"), new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, "MyCookieMiddlewareInstance");
await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", new ClaimsPrincipal(identity));

enter image description here

2 Answers 2

1

You need to provide the same claim type you used inside your "name" claim to the constructor of ClaimsIdentity:

var identity = new ClaimsIdentity(
    claims,
    "MyCookieMiddlewareInstance",
    "name",
    ClaimTypes.Role);

If you do not specify claim types the default values are ClaimTypes.Name and ClaimTypes.Role, which you are seeing with your debugger as NameClaimType and RoleClaimType respectively.

Sign up to request clarification or add additional context in comments.

Comments

1

As you can see in your image the type name of the name claim is http://schemas.xmlsoap.org/ws/2005/identity/claims/name. This means you are using the ws federation claim types (which are the default).

You can either use that default type to set your name claim.

new Claim(ClaimTypes.Name, "john");

Or you can overwrite the mapping in your StartUp which saves you from doing it in your authorization controller.

services.Configure<IdentityOptions>(options =>
{
     // or `= "name"` if you dont want the dependency
     options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
}

The other two claim type names that come to mind and would make sense to overwrite are these two.

ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.