ASP.NET Core中基于声明的授权

4
2个回答

9
从我的个人经验来看,关于声明(claims)及其如何真正使用它们的适当解释很少。因此,我将通过一个示例来分享我的解释。它使用在Visual Studio 2015中创建的默认ASP.NET MVC核心项目。
这里需要记住的关键是用户可以拥有一个或多个声明。他可以声称自己是“管理员”,并且“名称”等于“bhail”等。因此,他们使用声明这个词。有趣的是,声明可以由ASP.Net应用程序分配,甚至可以来自其他来源,例如Facebook,Twitter等。这一点非常重要,因为我们开始使用使用令牌的SPAs和移动应用程序,而这些令牌反过来又嵌入了声明。但这是另一天的事情。
在下面的示例中,我已修改了默认的AccountController,以在用户注册时向用户分配多个声明:
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {

                await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(ClaimTypes.Role, "Admin"));
                await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(ClaimTypes.Name, "Bhail"));
                await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(ClaimTypes.DateOfBirth, "18/01/1970"));
                await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(ClaimTypes.Country, "UK"));



                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                await _signInManager.SignInAsync(user, isPersistent: false);
                _logger.LogInformation(3, "User created a new account with password.");

                return RedirectToLocal(returnUrl);
            }
            AddErrors(result);
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

很好!我们现在已经有针对用户存储的声明。这些声明又被存储在持久存储器(数据库)中,表名为XXX_Security_User_Claim。我使用了XXX作为前缀,包括身份验证表在内的所有表名都是如此,这样我就可以让几个客户端在同一个数据库上具有安全性,以避免托管成本。该表应包含以下条目: 1 http://schemas.microsoft.com/ws/2008/06/identity/claims/role Admin 2 2 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name Bhail 2 3 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth 01/01/2000 2 4 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country UK 2
现在我们已经完成了用户所能做的事情,需要将注意力转向服务器如何处理它们。因此,我们需要创建策略。策略是声明的集合。所以在Startup.cs中。
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        // Adjustment to params from the default settings
        services.AddIdentity<ApplicationUser, ApplicationRole>()
      .AddEntityFrameworkStores<ApplicationDbContext, int>()
      .AddDefaultTokenProviders();


        services.AddMvc();

        #region Configure all Claims Policies

        services.AddAuthorization(options =>
        {
            //options.AddPolicy("Administrators", policy => policy.RequireRole("Admin"));
            options.AddPolicy("Administrators", policy => policy.RequireClaim(ClaimTypes.Role, "Admin")); // This works the same as the above code
            options.AddPolicy("Name", policy => policy.RequireClaim(ClaimTypes.Name, "Bhail"));

        });
        #endregion

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
    }

重要的一点是这些策略是硬编码的。您应该包括与您分配给用户相同的PolicyTypes,否则它将无法正常工作。 最后一步是在正在检查的控制器和/或操作中包含策略。因此,在HomeController中,我已添加了以下策略检查:
公共类HomeController:控制器 { public IActionResult Index() { 返回视图(); } }
    [Authorize(Policy = "Administrators")]
    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";

        return View();
    }

    [Authorize(Policy = "Name")]
    public IActionResult Contact()
    {
        ViewData["Message"] = "Your contact page.";

        return View();
    }

    public IActionResult Error()
    {
        return View();
    }
}

就是这样!基本上,策略是声明的集合。针对策略进行检查。声明本身分配给用户。与角色分配不同,您现在拥有从多种来源进行多对多授权的能力和灵活性。


6

这非常有帮助。在控制器中应用策略的能力是ASP.NET Core新的/受限制的功能吗?还是MVC5也有实现的方法? - GilliVilla
核心新功能。一些微软公司外部的人正在尝试将其移植回来,但我不知道那是如何进行的。 - blowdart
有没有来自微软以外的人正在进行的公开项目? - GilliVilla

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