ASP.NET Core 2.1 Custom RoleProvider with Windows Authentication

前端 未结 2 1693
忘了有多久
忘了有多久 2020-12-31 21:13

I am migrating applications away from the ASP.Net MVC 5 framework to the new .Net Core 2.1.

I used Windows Authentication with a Custom RoleProvider in the MVC 5 Pro

相关标签:
2条回答
  • 2020-12-31 21:53

    Managing custom permissions in net core is usually done via claims. You can do this via aspnet identity( How to add claims in ASP.NET Identity) or you can write your own middleware.

    Once you have claims, you need to create Policies. This is done via the Startup.cs class in the ConfigureServices method.

    services.AddAuthorization(options =>
            {
                options.AddPolicy("HR", policy => policy.RequireClaim("HRTeam"));
                options.AddPolicy("Helpdesk", policy => policy.RequireClaim("HelpdeskTeam"));
            });
    

    And then decorate your controllers/actions with the Authorize attribure

    [Authorize(Policy="Helpdesk")]
    public class HelpDeskController : Controller
    
    0 讨论(0)
  • 2020-12-31 21:58

    I had the same problem - the solutions given in the post weren't helpful but the comments pointed me in the right direction. You need to add claims to your ClaimsPrincipal.

    Step 1: Create a ClaimsTransformer - Replace "Admin" and add a separate claim for each role you fetch from your database

    using System.Security.Claims;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Authentication;
    
    public class ClaimsTransformer : IClaimsTransformation
    { 
        public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var ci = (ClaimsIdentity) principal.Identity;
            var c = new Claim(ci.RoleClaimType, "Admin");
            ci.AddClaim(c);
            return Task.FromResult(principal);
        }
    }
    

    Step 2: Add your ClaimsTransformer to the ConfigureServices method of Startup.cs

    services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.AuthenticationScheme);
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/dist";
    });
    
    services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
    

    Step 3: You can now add Role based Authorization attributes within your Controllers

    [Authorize(Roles = "Admin")]
    [HttpGet("[action]/{id}")]        
    public User GetUser([FromRoute] int id)
    {
        UserLogic ul = new UserLogic();
        return ul.GetUser(id);
    }
    
    0 讨论(0)
提交回复
热议问题