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

Claims based authorization in ASP.NET Core

是否有针对 ASP.NET Core 使用基于声明的授权的权威示例项目?

类似于 MVC 的 [https://silk.codeplex.com/]

1 小时的研讨会可以吗?

https://github.com/blowdart/AspNetAuthorizationWorkshop

请注意,这并不是说基于声明,因为这不再特别。 ASP.NET Core(现在是 Core,不是 vNext)中的所有身份都是声明身份。

根据我的个人经验,很少有关于声明的正确解释以及如何真正使用它们的方法。所以我将通过一个例子来分享我的解释。它使用在 Visual Studio 2015 年创建的默认 ASP.NET MVC 核心项目。

这里要记住的重要一点是,一个用户可以有一个或多个声明。他可以声称自己是“管理员”并且“名称”等于“bhail”等。这就是他们使用 claim 这个词的原因。有趣的是,Claims 可以由 ASP.Net 应用程序分配,甚至可以从其他来源(如 Facebook、Twitter 等)分配。这非常重要,因为我们开始使用使用令牌的 SPA 和移动应用程序,这些令牌又嵌入了 Claims。但那是另一天。 在下面的示例中,我修改了默认的 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);
    }

太棒了!我们现在存储了针对用户的索赔。这些又存储在持久存储(数据库)中。 Table 是 XXX _Security_User_Claim。我使用 XXX 作为我所有 table 名称的前缀,包括身份 table,这样我就可以在同一个数据库上拥有多个具有安全性的客户端,以避免托管成本。 Table 应包含条目: 1 http://schemas.microsoft.com/ws/2008/06/identity/claims/role 管理员 2 2 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name 拜尔 2 3 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth 2000 年 1 月 1 日 2 4 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country 英国 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,否则它将无法正常工作。 最后一步是包括针对正在检查的控制器 and/or 操作的策略。因此,在 HomeController 中,我添加了以下策略检查:

public class 家庭控制器:控制器 { public IActionResult 索引() { return查看(); }

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

给你!基本上,保单是索赔的集合。根据政策进行检查。而 Claims 本身是分配给用户的。与角色分配不同,您现在可以灵活地从各种来源进行多对多授权。