ASP.Net Core 3.0 Windows 使用基于自定义角色的授权进行身份验证

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

我希望在 ASP.NET 3.0 MVC 应用程序中使用 Windows 身份验证,我从 SQL 数据库中提取角色以确保 API 安全。我将用 [Authorize(Roles = "Admin")]

之类的东西装饰 API 控制器方法

我这里的很多东西都是从这个网站上得到的,但我卡在了最后一部分。 我可以看到该角色已应用到该用户,但无法获得工作授权。

为此,我首先从 ClaimsTransformer 开始,它将用于通过声明向我的用户应用角色。

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 - 配置服务

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 - 配置

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

在 API 控制器中,我可以像这样设置一个没有授权的方法,当我检查 User.IsInRole("Admin");

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

        return Ok(result);
    }

但是,如果我像这样用 [Authorize(Roles = "Admin")] 修饰控制器方法,那么我会在调用此方法时收到 Forbidden 响应。

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

        return Ok(result);
    }

在这种情况下,这是一个小而常见的换行错误,the orderUseAuthentication(用户是谁)然后是 UseAuthorization(允许用户做什么).这就解释了为什么授权不起作用。