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

9
我希望在使用ASP.NET 3.0 MVC应用程序中,通过SQL数据库中提取的角色来实现API安全性时,使用Windows身份验证。我会像这样为API控制器方法添加修饰:[Authorize(Roles = "Admin")] 我从这个网站学到了很多东西,但是在最后一部分卡住了。我可以看到角色已经应用于用户,但无法使授权起作用。
为了做到这一点,我首先使用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 - 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 - 配置

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")时,看到结果显示为true。

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

        return Ok(result);
    }

然而,如果我像这样使用[Authorize(Roles = "Admin")]修饰控制器方法,那么调用该方法时会得到一个“禁止访问”的响应。

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

        return Ok(result);
    }

1
为什么不使用基于策略的授权和授权服务?请查看文档。它比角色更高级。 - user4864425
1
还要注意的是,顺序是UseAuthentication(谁是用户),然后是UseAuthorization(用户被允许做什么)。这就解释了为什么授权不起作用。 - user4864425
啊,太好了!问题出在UseAuthorization和UseAuthentication的顺序上。 非常感谢。如果你公布答案,我可以给你鸣谢。 回答你的第一个回复,我也研究了策略。由于顺序的原因,它也没有起作用。我正在从基于角色的系统迁移,所以只是匹配我已有的内容,但我知道我可以扩展。再次感谢。 - madvora
我不知道你是否知道,所以我提到了它。很高兴我能帮忙,谢谢。 - user4864425
1个回答

6
在这种情况下,是一种小但常见的错误,即切换行的顺序,顺序UseAuthentication(谁是用户)然后是 UseAuthorization(用户被允许做什么)。这就解释了为什么授权不起作用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接