ASP.NET Identity check user roles is not working

前端 未结 3 650
慢半拍i
慢半拍i 2020-12-03 17:13

I have an ASP.NET MVC 5 application. I\'m using the standard ASP.NET Identity provider for user and role management. It is important that I\'m using the IdentityUser from an

相关标签:
3条回答
  • 2020-12-03 17:33

    Do you have this entry in your web.config?

        <roleManager enabled="true">
            <providers>
                <clear />
                <add connectionStringName="ApplicationServices" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" applicationName="/" />
            </providers>
        </roleManager>
    

    Also, if I remember correctly, there is a different namespace for the role provider assembly in different versions of .NET.

    0 讨论(0)
  • 2020-12-03 17:49

    There seems to be an issue. [The issue by design]

    • The role names are case sensitive in AuthorizeAttribute and User.IsInRole
    • The role names are case insensitive in UserManager.IsInRole

    Moreover, check for the correct role name is used for the verification.

    [The above is based on the test performed with below code. Role Name="Admin", User is added to Role "Admin".]

    [Authorize(Roles="Admin")] /*True as "Admin" has A capital as entered in Role name*/
    public ActionResult Secured()
    {
        if (User.IsInRole("admin")) /*This is False*/
        {
             Console.WriteLine("In");
        }
        if(UserManager.IsInRole(User.Identity.GetUserId(), "admin")) /*This is True!!*/
        {
             Console.WriteLine("In");
        }
        return View();
    }
    

    If we change the attribute to [Authorize(Roles="admin")], it redirects to Login page.

    0 讨论(0)
  • 2020-12-03 17:53

    In that case you need to logout and login the user again.

    Because the roles data is also stored in cookies, So you must issue the cookie again to work it.

    0 讨论(0)
提交回复
热议问题