c# - 具有自定义角色授权的 ASP.Net Core 3.0 Windows 身份验证

标签 c# asp.net-core asp.net-web-api authorization windows-authentication

我希望在 ASP.NET 3.0 MVC 应用程序中使用 Windows 身份验证,并从 SQL 数据库中提取角色以实现 API 安全性。我将使用类似 [Authorize(Roles = "Admin")] 的东西来装饰 API Controller 方法。

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

为此,我首先从 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 Controller 中,我可以像这样设置一个没有授权的方法,并在检查 User.IsInRole("Admin"); 时看到结果显示为 true。
    [HttpGet]   
    public async Task<IActionResult> GetData1()
    {
        var result = User.IsInRole("Admin");

        return Ok(result);
    }

但是,如果我用 [Authorize(Roles = "Admin")] 装饰 Controller 方法像这样,然后我在调用此方法时收到 Forbidden 响应。
    [HttpGet]       
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> GetData1()
    {
        var result = User.IsInRole("Admin");

        return Ok(result);
    }

最佳答案

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

关于c# - 具有自定义角色授权的 ASP.Net Core 3.0 Windows 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58825446/

相关文章:

c# - WPF:从代码隐藏向元素添加阴影效果

c# - 从范围 '' 引用类型为 '' 的变量 '',但未定义

c# - 从代码相同的 PCL 项目生成 .NET 4.0 库

C# : How to get number of days from an object of DateTime

azure - 使用 OAuth 使用 EWS 应用程序发送电子邮件是否必须使用 full_access_as_app

asp.net-core - "The library ' hostpolicy.dll ' required"如果从部署文件夹运行,但emitEntryPoint为true

javascript - 如何将一些字符串或数据从 API 传递到 Angular 6 中的 Angular 组件?

c# - 如何将架构过滤器添加到一个 Swashbuckle api 文档版本

javascript - 如何设置 OnClientClick 值 - 语法?

javascript - 使用 Angular JS $http.post() 将 json 数据发布到 WCF REST 在 Chrome 中失败但在 IE 中成功