c# - ASP.NET Core - 使用 Windows 身份验证进行授权

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

我已配置我的 Web API 以使用 Windows 身份验证。我的目标本质上是根据用户 Windows 帐户限制 Controller 中的某些操作。有些将能够执行读取操作,而另一些将能够执行写入底层数据库的操作。我找到了大量关于如何设置基于声明的授权的文档,这是我认为我需要走的路线。我还没有找到如何使用 Windows 身份验证进行设置。我想我错过了中间步骤,例如将 Windows 身份验证注册为身份提供者?

startup.cs

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

    services.AddAuthentication(IISDefaults.AuthenticationScheme);

    services.AddAuthorization(options =>
    {
        options.AddPolicy("readOnly", policy =>
                          policy.RequireClaim(`???????????????????????`));
        options.AddPolicy("write", policy =>
                          policy.RequireClaim(`???????????????????????`));
    });
}

Controller

[Authorize(Policy = "ReadOnly")]
public class MyController : Controller
{
    public ActionResult SomeReadOnlyAction()
    {
        //Return data from database
    }

    [Authorize(Policy = "Write")]
    public ActionResult AWriteAction()
    {
        //Create/Update/Delete data from database
    }
}

我想问这个问题的另一种方式是如何使用 Windows 身份验证配置或访问声明/角色等...。

最佳答案

您似乎想通过策略使用基于声明的授权。在应用程序中设置 Windows 身份验证后,您可以向 ClaimsPrincipal 添加自定义声明,检查用户身份并确认当前用户拥有哪些权限:

  1. 您可以将声明转换服务添加到您的应用程序中:

    class ClaimsTransformer : IClaimsTransformation
    {
        public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var id = ((ClaimsIdentity)principal.Identity);
    
            var ci = new ClaimsIdentity(id.Claims, id.AuthenticationType, id.NameClaimType, id.RoleClaimType);
            if (ci.Name.Equals("name"))
            {
                ci.AddClaim(new Claim("permission", "readOnly"));
            }
            else
            {
                ci.AddClaim(new Claim("permission", "write"));
    
            }
    
    
            var cp = new ClaimsPrincipal(ci);
    
            return Task.FromResult(cp);
        }
    }
    
  2. 添加到Startup.cs(.net Core 2.0):

        services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
    
  3. 设置您的政策:

        services.AddAuthorization(options =>
        {
            options.AddPolicy("Readonly", policy =>
                              policy.RequireClaim("permission", "readOnly"));
    
            options.AddPolicy("Write", policy =>
                            policy.RequireClaim("permission", "write"));
        });
    
  4. 通过要求此策略来限制对 Controller 或操作的访问:

        [Authorize(Policy = "Write")]
        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";
    
            return View();
        }
    

如果您已经在AD中添加了群组(写入、只读)并将相关用户添加到群组中,您还可以查看群组:

public static class Security
{
    public static bool IsInGroup(this ClaimsPrincipal User, string GroupName)
    {
        var groups = new List<string>();

        var wi = (WindowsIdentity)User.Identity;
        if (wi.Groups != null)
        {
            foreach (var group in wi.Groups)
            {
                try
                {
                    groups.Add(group.Translate(typeof(NTAccount)).ToString());
                }
                catch (Exception)
                {
                    // ignored
                }
            }
            return groups.Contains(GroupName);
        }
        return false;
    }
}

并使用类似:

 if (User.IsInGroup("GroupName"))
 {

 }

关于c# - ASP.NET Core - 使用 Windows 身份验证进行授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53524466/

相关文章:

c# - LINQ 中具有外连接的 Nullable Int

asp.net - 在现有应用程序中集成 ASP.Net 和 ('classic' ) ASP

asp.net - 如何在 ASP.NET 中获取网络打印机

asp.net-web-api - 在 asp.net Core API 中检测请求是否来自移动设备

使用 HashSet(pluralsight 代码)的假数据库上下文的 C# 单元测试(新 Q)

c# - 在 WP 8 (C#) 中调用 WinRT 组件时出现 System.IO.FileNotFoundException 错误

c# - MySqlDataReader 关闭连接

asp.net - 我应该使用 IFormFile 在 ASP.NET Core API 中上传文件吗

asp.net-core - 与部署在 IIS 中的多个子域站点共享同一 session (aspnet core)

c# - 手动引发控件上的 LostFocus 事件