Skip to content

Instantly share code, notes, and snippets.

@haacked
Last active September 18, 2019 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haacked/6267c9381d9c05c4786f6281cb05c1d4 to your computer and use it in GitHub Desktop.
Save haacked/6267c9381d9c05c4786f6281cb05c1d4 to your computer and use it in GitHub Desktop.
Providing Role Claims
/*
This needs to be registered with the IdentityServer in the Startup.cs
by calling AddProfileService<RoleProfileService>() on the builder returned
by AddIdentityServer.
ex...
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApis())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<RoleProfileService>();
*/
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
namespace IdentityServerAspNetIdentity.Extensions
{
public class RoleProfileService : IProfileService
{
readonly UserManager<ApplicationUser> _userManager;
readonly IHttpContextAccessor _httpContextAccessor;
public RoleProfileService(UserManager<ApplicationUser> userManager,
IHttpContextAccessor httpContextAccessor)
{
_userManager = userManager;
_httpContextAccessor = httpContextAccessor;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var sub = context.Subject.GetSubjectId();
var user = await _userManager.FindByIdAsync(sub);
var roleClaims = (await _userManager.GetRolesAsync(user))
.Select(role => new Claim(JwtClaimTypes.Role, role));
context.IssuedClaims.AddRange(roleClaims);
}
public Task IsActiveAsync(IsActiveContext context)
{
//TODO: You might want to implement this differently.
return Task.CompletedTask;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment