在过去的MVC版本中,我能够做到
<roleManager enabled="true" defaultProvider="...." ...
在web.config中获取自定义角色提供程序,但似乎不再是这种情况.
基本上我想做的是:
>用户登录.
>成功时,从外部源获取用户角色.
>将角色应用于用户以在代码中使用.
>将用户角色与自定义RoleProvider中的角色相匹配
我如何在ASP.NET Core中执行此操作?
解决方法
如果您使用简单的基于cookie的身份验证而不是Identity框架,则可以将您的角色添加为声明,并且它们将被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) } ); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。