ASP.NET Core - 使用 Windows 身份验证进行授权 [英] ASP.NET Core - Authorization Using Windows Authentication

查看:83
本文介绍了ASP.NET Core - 使用 Windows 身份验证进行授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have configured my web api to work with windows authentication. My goal is essentially to restrict certain actions in my controllers based on a users windows account. Some will be able to preform read actions while others will be able to preform actions that will write to the underlying database. I have found plenty of documentation on how to set up claims based authorization which is the route I think I need to go. What I have not found is how to set this up with windows auth. I think I am missing a middle step such as registering the windows auth as the identity provider?

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(`???????????????????????`));
    });
}

控制器

[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 身份验证.

I guess another way to ask this question is how do you configure or access claims/roles etc... with windows authentication.

推荐答案

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

That seems you want to use claims-based authorization via policies . After setting windows authentication in your application , you could add custom claim to ClaimsPrincipal ,check user's identity and confirm which permission current user has :

  1. 您可以向应用程序添加声明转换服务:

  1. You can add a claims transformation service to your application:

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);
    }
}

  • 添加到 Startup.cs(.net Core 2.0):

  • Add to Startup.cs(.net Core 2.0) :

        services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
    

  • 设置您的政策:

  • Set your policy :

        services.AddAuthorization(options =>
        {
            options.AddPolicy("Readonly", policy =>
                              policy.RequireClaim("permission", "readOnly"));
    
            options.AddPolicy("Write", policy =>
                            policy.RequireClaim("permission", "write"));
        });
    

  • 通过要求此政策限制对控制器或操作的访问:

  • Restrict access to a controller or action by requiring this policy:

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

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

    If you have already add groups(write,readonly) in your AD and add the related users to group , you can also check the groups :

    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"))
     {
    
     }
    

    这篇关于ASP.NET Core - 使用 Windows 身份验证进行授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆