具有身份的ASP.NET Core中的自定义RoleProvider?

编程入门 行业动态 更新时间:2024-10-27 20:25:15
本文介绍了具有身份的ASP.NET Core中的自定义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.

基本上我想做的是:

  • 用户登录.
  • 成功后,从外部来源获取用户角色.
  • 将角色应用于用户以在代码中使用.
  • 将用户角色与自定义RoleProvider中的角色进行匹配
  • 如何在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?

    本文发布于:2023-11-14 14:48:20,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1587579.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:自定义   身份   ASP   NET   Core

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!