where is mapping table of Id and it's role stored?

asp.net-core authorization c# entity-framework-core windows-authentication

Question

I'm using asp.net core authorization.I have some roles like SuperAdmin ,Admin,User. Each user will be assigned one of them. SuperAdmin can change the role of any user.So basically i want dynamic role system. So where to map user-Role data and

[Authorize(Roles = "Admin")]

goes where to check the role of user? means where this thing checks the role.

I'm using Windows Authentication

1
0
10/24/2019 5:21:57 AM

Popular Answer

You can use claims-based authorization via policies . After setting windows authentication in your application , you could add custom claim to ClaimsPrincipal ,check user's identity and confirm which permission/role the current user has :

  1. You can add a claims transformation service to your application:

    class ClaimsTransformer : IClaimsTransformation
    {
        public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var id = ((ClaimsIdentity)principal.Identity);
    
            var ci = new ClaimsIdentity(id.Claims, id.AuthenticationType, id.NameClaimType, id.RoleClaimType);
    
            //read database or flies or query AD to confirm user role by use ci.Name(username)
            if (....)
            {
                ci.AddClaim(new Claim("role", "Admin"));
            }
            else
            {
                ci.AddClaim(new Claim("role", "user"));
    
            }
    
    
            var cp = new ClaimsPrincipal(ci);
    
            return Task.FromResult(cp);
        }
    }
    
  2. Add to Startup.cs :

        services.AddAuthentication(IISDefaults.AuthenticationScheme);
        services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
    
  3. Set your policy :

        services.AddAuthorization(options =>
        {
            options.AddPolicy("Admin", policy =>
                              policy.RequireClaim("role", "Admin"));
    
            options.AddPolicy("User", policy =>
                            policy.RequireClaim("role", "user"));
        });
    
  4. Restrict access to a controller or action by requiring this policy:

        [Authorize(Policy = "Admin")]
        public IActionResult Contact()
        {
           .....
        }
    

You can also use AD groups as roles . Base on your requirement , you can modify above codes to fit your scenario . Manage user/roles could use local database or ASP.NET Core Identity auto-create tables.

0
10/25/2019 7:53:38 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow