I created an asp.net core project in visual studio 2015 with windows authentication. I can\'t figure out how to add roles to the Identity.
I have a table with usernames
For anyone interested, here is a simple example of how you can inject an EF DBContext into a custom ClaimsTransformer and add some custom role claims.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped();
services.AddMvc();
services.AddDbContext(options => options.UseSqlServer(
Configuration.GetConnectionString("MyConnStringSetting")
));
(...)
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseClaimsTransformation(context =>
{
var transformer = context.Context.RequestServices.GetRequiredService();
return transformer.TransformAsync(context);
});
(...)
}
MyClaimsTransformer.cs
public class MyClaimsTransformer : IClaimsTransformer
{
private readonly MyDbContext _context;
public MyClaimsTransformer(MyDbContext context)
{
_context = context;
}
public Task TransformAsync(ClaimsTransformationContext context)
{
var identity = (ClaimsIdentity)context.Principal.Identity;
var userName = identity.Name;
var roles = _context.Role.Where(r => r.UserRole.Any(u => u.User.Username == userName)).Select(r => r.Name);
foreach (var role in roles)
{
var claim = new Claim(ClaimTypes.Role, role);
identity.AddClaim(claim);
}
return Task.FromResult(context.Principal);
}
}