I am running Windows Authentication and using Claims Transformer to add custom roles to users. How can I only use roles from DB and not have it use Active Directory for authorization as well? Thanks in advance.
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var ci = (ClaimsIdentity)principal.Identity;
string UserName = ci.Name;
using (var scope = _serviceProvider.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<DbContext>();
List<string> roles = dbContext.vUserRoles.Where(c => c.UserName.Equals(UserName)).Select(c => c.RoleName.ToString()).ToList();
foreach (var item in roles)
{
var dbrole = new Claim(ci.RoleClaimType, item);
ci.AddClaim(dbrole);
}
return await Task.FromResult(principal);
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
});
services.AddAuthorization();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…