Lucas Lobosque
Lucas Lobosque

Reputation: 399

AspNet Core - Settings `NameClaimType` and `RoleClaimType`

How do I change the Identity values NameClaimType and RoleClaimType to "sub" and "role" instead the default SOAP URLs below:

NameClaimType and RoleClaimType (More context on the motivation on this github issue: https://github.com/GestionSystemesTelecom/fake-authentication-jwtbearer/issues/4)

Upvotes: 4

Views: 8175

Answers (3)

Boris Maslennikov
Boris Maslennikov

Reputation: 351

  1. Configure your identity
services.AddDefaultIdentity<IIdentityUser>(options =>
{ 
    options.ClaimsIdentity.UserNameClaimType = "sub";
    options.ClaimsIdentity.RoleClaimType = "role";
})
  1. Configure your JWT token
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(options =>
     {
           options.TokenValidationParameters.NameClaimType = "sub";
           options.TokenValidationParameters.RoleClaimType = "role";
     });
  1. Use await CreateAsync(user) method on IUserClaimsPrincipalFactory<IIdentityUser> instance. It will create correct ClaimsIdentity object with user claims that you can use during JWT token generation.
var principal = await _userClaimsPrincipalFactory.CreateAsync(user);
var token = new JwtSecurityToken(issuer, audience, principal.Claims, notBefore, expires, credentials);

Upvotes: 6

To set custom claim names use code below

 services.Configure<IdentityOptions>(options =>
 {
    options.ClaimsIdentity.UserNameClaimType = "value";
    options.ClaimsIdentity.UserIdClaimType = "value";
    options.ClaimsIdentity.RoleClaimType = "value";
 });

Upvotes: 2

Nick Muller
Nick Muller

Reputation: 2273

When constructing the ClaimsIdentity class, there's a constructor overload that allows specifiying the claim type for name and role. See the official api docs.

Upvotes: 3

Related Questions