ASP.Net MVC5:使用身份登录后如何与用户连接角色

时间:2018-05-11 06:41:07

标签: asp.net-mvc-5 asp.net-identity

我们用具有特定角色名称的授权属性保护动作

[Authorize(Roles="members, admin")]

假设用户和角色在db表中映射。因此,当用户登录时,我如何使用身份为登录用户附加角色。

这里我发布的网址和示例显示人们如何在mvc4中使用自定义表单身份验证执行相同操作。只是看到代码,我希望能够理解我正在尝试使用身份使用asp.net mvc 5。 https://www.codeproject.com/Articles/408306/Understanding-and-Implementing-ASP-NET-Custom-Form 请参阅上面的URL以获取asp.net mvc 4的自定义表单身份验证

protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
    if (FormsAuthentication.CookiesSupported == true)
    {
        if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
        {
            try
            {
                //let us take out the username now                
                string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;

                //let us extract the roles from our own custom cookie
                string roles = DBHelper.GetUserRoles(username);

                //Let us set the Pricipal with our user specific details
                e.User = new System.Security.Principal.GenericPrincipal(
                  new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
            }
            catch (Exception)
            {
                //somehting went wrong
            }
        }
    }
}

我正在使用asp.net mvc 5&身份系统。请帮助和指导我。感谢

1 个答案:

答案 0 :(得分:0)

您必须先登录用户ID

var UserName= await User.Identity.GetUserId()

然后您可以将任何角色分配给登录用户,如

var _context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
UserManager.AddToRole("UserName", "UserRole");
相关问题