I have created an IdentityServer4 server from is4aspid
template (Basic IdentityServer that uses ASP.NET Identity for user management), it come with 2 sample users.
After that, I have create a razor pages client follow instructions from IdentityServer4 docs.
The app works but application gets from identity server unknown claims, here they are (type=value
):
s_hash=tFpbakJatWNQIjaChraJAw
sid=Sj6JGUgztjOIK1Cq8E-HoA
sub=a070c8cc-d962-440c-a796-e0c169e87578
auth_time=1586427090
idp=local
amr=pwd
I have defining server client on appsettings.json as:
{
"ClientId": "mvc",
"Enabled": true,
"ClientName": "Mvc Client",
"AllowedGrantTypes": [ "client_credentials", "authorization_code" ],
"RequirePkce": true,
"ClientSecrets": [ { "Value": "hide_for_privacity" } ],
"RedirectUris": [ "https://localhost:5001/signin-oidc" ],
"FrontChannelLogoutUri": "http://localhost:5001/signout-oidc",
"PostLogoutRedirectUris": [ "http://localhost:5001/signout-callback-oidc" ],
"AllowOfflineAccess": true,
"AllowedScopes": [ "openid", "profile", "offline_access", "api1" ]
}
The authentication in the client is setup as follows:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = "http://localhost:5099";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc";
options.ClientSecret = "hide_for_privacity";
options.ResponseType = "code";
options.UsePkce = true;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access");
options.SaveTokens = true;
});
I have decoded the returned token using jwt.io and it's the payload:
{
"nbf": 1586427096,
"exp": 1586427396,
"iss": "http://localhost:5099",
"aud": "mvc",
"nonce": "637220238868623664.MzdjNjI0NmMtNWNhMy00YTg4LWIzYTUtYjcxMTFmMTNlYjhiYWY0ZmM5NTQtNDY1Mi00ZWVhLTlkNjUtY2UzMzIwMjY5NjA4",
"iat": 1586427096,
"at_hash": "Z_Cwm-4UzmH8v8PyW2d0Rg",
"s_hash": "tFpbakJatWNQIjaChraJAw",
"sid": "Sj6JGUgztjOIK1Cq8E-HoA",
"sub": "a070c8cc-d962-440c-a796-e0c169e87578",
"auth_time": 1586427090,
"idp": "local",
"amr": ["pwd"]
}
Why I don't receive de user name and roles defined in the server??
The first thing is to confirm you have add roles to database and add roles to user . In SeedData.cs
, you could seed role like :
public static void SeedRoles(RoleManager<IdentityRole> roleManager)
{
if (!roleManager.RoleExistsAsync("NormalUser").Result)
{
IdentityRole role = new IdentityRole();
role.Name = "NormalUser";
IdentityResult roleResult = roleManager.
CreateAsync(role).Result;
}
if (!roleManager.RoleExistsAsync("Administrator").Result)
{
IdentityRole role = new IdentityRole();
role.Name = "Administrator";
IdentityResult roleResult = roleManager.
CreateAsync(role).Result;
}
}
And add roles to user in EnsureSeedData
function :
...
SeedRoles(roleMgr);
var alice = userMgr.FindByNameAsync("alice").Result;
if (alice == null)
{
alice = new ApplicationUser
{
UserName = "alice"
};
var result = userMgr.CreateAsync(alice, "Pass123$").Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
userMgr.AddToRoleAsync(alice,"NormalUser").Wait();
...
}
After that you could add custom claims to tokens :
public class ProfileService : IProfileService
{
protected readonly UserManager<ApplicationUser> _userManager;
public ProfileService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
ApplicationUser user = await _userManager.GetUserAsync(context.Subject);
IList<string> roles = await _userManager.GetRolesAsync(user);
IList<Claim> roleClaims = new List<Claim>();
foreach (string role in roles)
{
roleClaims.Add(new Claim(JwtClaimTypes.Role, role));
}
//add user claims
roleClaims.Add(new Claim(JwtClaimTypes.Name, user.UserName));
context.IssuedClaims.AddRange(roleClaims);
}
public Task IsActiveAsync(IsActiveContext context)
{
return Task.CompletedTask;
}
}
And register in Startup.cs:
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(Config.Clients)
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<ProfileService>(); <-- add this line
In Config.cs
, in your client config , set AlwaysIncludeUserClaimsInIdToken
to true to make the claims available in ID toke :
AlwaysIncludeUserClaimsInIdToken=true,
Now the claims are inside the ID Token , and you can also change OIDC config in client app to set the role claim using the JwtClaimTypes.Role
type from token :
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
....
options.TokenValidationParameters.RoleClaimType = "role";
});