Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

asp.net core - How to only accept custom roles(ClaimsTransformer) and not roles from Active Directory

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?}");
            });


        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...