[英]Claims based authorization in ASP.NET Core
根据我的个人经验,对索赔的正确解释以及如何真正使用它们的方法很少。 所以我将通过一个例子来分享我的解释。 它使用在Visual Studio 2015中创建的默认ASP.NET MVC核心项目。
这里要记住的基本要素是用户可以拥有一个或多个声明。 他可以自称是“管理员”,并且“名称”等于“bhail”等。因此他们使用“索赔”一词的原因。 有趣的是,索赔可以由ASP.Net应用程序分配,甚至可以从Facebook,Twitter等其他来源分配。这一点非常重要,因为我们开始使用使用令牌的SPA和移动应用程序,而令牌又嵌入了索赔。 但那是另一天。 在下面的示例中,我修改了默认的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/声明/名称 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/身份/声明/国家英国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中我添加了以下策略检查:
public class HomeController:Controller {public IActionResult Index(){return 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();
}
}
你去! 基本上政策是索赔的集合。 检查是针对政策的。 并且声明本身被分配给用户。 与角色分配不同,您现在拥有从各种来源进行多对多授权的强大功能和灵活性。
1小时的研讨会会吗?
https://github.com/blowdart/AspNetAuthorizationWorkshop
请注意,这并不是基于声明,因为这不再是特殊的。 ASP.NET Core中的所有身份(现在是Core,而不是vNext)都是声明身份。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.