【问题标题】:Custom RoleProvider in ASP.NET Core with Identity?带有身份的 ASP.NET Core 中的自定义 RoleProvider?
【发布时间】:2016-03-14 19:35:38
【问题描述】:
在过去的 MVC 版本中,我能够做到
<roleManager enabled="true" defaultProvider="...." ...
在 web.config 中获取自定义角色提供程序,但现在似乎不再是这种情况了。
基本上我想做的是:
- 用户登录。
- 成功后,从外部来源获取用户角色。
- 将角色应用于要在代码中使用的用户。
- 将用户角色与自定义 RoleProvider 中的角色匹配
如何在 ASP.NET Core 中执行此操作?
【问题讨论】:
标签:
c#
asp.net
asp.net-mvc
authorization
asp.net-core
【解决方案1】:
如果您使用简单的基于 cookie 的身份验证而不是身份框架,您可以将您的角色添加为声明,它们将被User.IsInRole(...)、[Authorize(Roles = "...")] 等获取。
private async Task SignIn(string username)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username)
};
// TODO: get roles from external source
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
claims.Add(new Claim(ClaimTypes.Role, "Moderator"));
var identity = new ClaimsIdentity(
claims,
CookieAuthenticationDefaults.AuthenticationScheme,
ClaimTypes.Name,
ClaimTypes.Role
);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity),
new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddMonths(1)
}
);
}