简体   繁体   中英

ASP.Net Core 3.0 Windows Authentication with Custom Role Based Authorization

I'm looking to use Windows Authentication in an ASP.NET 3.0 MVC app with roles I pull from a SQL database for API security. I will decorate the API controller methods with something like [Authorize(Roles = "Admin")]

A lot of what I have here, I've picked up from this site, but I'm stuck on the last part. I can see that the role is applied to the user, but can't get the authorization to work.

To do this, I first start with a ClaimsTransformer, which will be used to apply roles through claims to my users.

ClaimsTransformer.cs

    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        //This sample will automatically apply the Admin role to the user
        //In the real app, I will check the user against my DB and apply all roles (as claims) here
        var ci = (ClaimsIdentity)principal.Identity;
        var c = new Claim(ci.RoleClaimType, "Admin");
        ci.AddClaim(c);

        return await Task.FromResult(principal);
    }

Startup.cs - ConfigureServices

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        //Register the ClaimsTransformer here
        services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();

        //Use windows authentication
        services.AddAuthentication(IISDefaults.AuthenticationScheme);
        services.AddAuthorization();
    }

Starup.cs - Configure

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();
        app.UseAuthentication();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

DataController.cs

In the API controller, I can set up a method with no authorization like this and see the result showing true when I check if User.IsInRole("Admin");

    [HttpGet]   
    public async Task<IActionResult> GetData1()
    {
        var result = User.IsInRole("Admin");

        return Ok(result);
    }

However, if I decorate the controller method with [Authorize(Roles = "Admin")] like this, then I get a Forbidden response on calls to this method.

    [HttpGet]       
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> GetData1()
    {
        var result = User.IsInRole("Admin");

        return Ok(result);
    }

In this case it's a small but common mistake of switching lines, the order is UseAuthentication (who is the user) and then UseAuthorization (what is the user allowed to do). That explains why authorization doesn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM