How to add Roles to Windows Authentication in ASP.NET Core

前端 未结 3 1988
梦谈多话
梦谈多话 2021-01-31 06:40

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

3条回答
  •  佛祖请我去吃肉
    2021-01-31 07:10

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

提交回复
热议问题