本文介绍了具有身份的ASP.NET Core中的自定义RoleProvider?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用户登录.
成功后,从外部来源获取用户角色.
将角色应用于用户以在代码中使用.
将用户角色与自定义RoleProvider中的角色进行匹配
在过去的MVC版本中,我能够做到
In past MVC versions I was able to do
<roleManager enabled="true" defaultProvider="...." ...进入web.config以获取自定义角色提供程序,但现在似乎不再如此.
in to the web.config to get a custom role provider, but that doesn't seem to be the case anymore.
基本上我想做的是:
如何在ASP.NET Core中做到这一点?
How do I do this in ASP.NET Core?
推荐答案如果您使用的是基于Cookie的简单身份验证,而不是Identity框架,则可以将您的角色添加为声明,这些角色将由User.IsInRole(...)提取. ,[Authorize(Roles = "...")]等
If you're using simple cookie-based authentication instead of the Identity framework, you can add your roles as claims and they will be picked up by User.IsInRole(...), [Authorize(Roles = "...")], etc.
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) } ); }更多推荐
具有身份的ASP.NET Core中的自定义RoleProvider?
发布评论