是否有针对 ASP.NET Core 使用基于声明的授权的权威示例项目?
类似于[ https://silk.codeplex.com/]用于 MVC。
最佳答案
根据我的个人经验,很少有关于声明的正确解释以及如何真正使用它们的方法。所以我将通过一个例子来分享我的解释。它使用在 Visual Studio 2015 中创建的默认 ASP.NET MVC 核心项目。
这里要记住的重要一点是,一个用户可以有一个或多个声明。他可以声称自己是“管理员”并且“名称”等于“bhail”等。这就是他们使用 claim 这个词的原因。有趣的是,Claims 可以由 ASP.Net 应用程序分配,甚至可以从其他来源(例如 Facebook、Twitter 等)分配。这非常重要,因为我们开始使用 SPA 和移动应用程序,这些 SPA 和移动应用程序使用依次嵌入 Claims 的 token 。但那是另一天。 在下面的示例中,我修改了默认的 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);
}
太棒了!我们现在存储了针对用户的 claim 。这些又存储在持久存储(数据库)中。该表是 XXX _Security_User_Claim。我使用 XXX 作为我所有表名的前缀,包括身份表,这样我就可以在同一个数据库上拥有多个具有安全性的客户端,以避免托管成本。该表应包含条目: 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 01/01/2000 2 4 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country英国 2
现在我们已经完成了用户可以做什么,我们需要将注意力集中在服务器将如何处理这些事情上。所以我们需要创建策略。保单是 claim 的集合。所以在 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,否则它将无法正常工作。 最后一步是包括针对正在检查的 Controller 和/或操作的策略。因此,在 HomeController 中,我添加了以下策略检查:
公共(public)类 HomeController : Controller { 公共(public) IActionResult 索引() { 返回 View ();
[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();
}
}
给你!基本上,保单是 claim 的集合。根据政策进行检查。而 Claims 本身是分配给用户的。与角色分配不同,您现在可以灵活地从各种来源进行多对多授权。
关于c# - ASP.NET Core 中基于声明的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40011981/