简体   繁体   中英

ASP.NET MVC custom role provider not working

I have setup a custom role provider implemented using the code below except it seems it's never being used, and the default provider is being used instead. When decorating the HomeController with the [Authorize(Roles = "Administrator")] attribute the CustomRoleProvider constructor is being called (I only included the constructor in to see whether the breakpoint would be hit) but none of the methods are being called. And then I am left with a HTTP Error 401.0 - Unauthorized page.

Aside from adding the necessary bits to the web.config I haven't done anything else to get Windows authentication to work. I assume it's working though because if I don't include <allow users="*"></allow> (obviously without the inclusion of the Authorize attribute) I get a 401.2.: Unauthorized: Logon failed due to server configuration error, so I assume I'm being authenticated.

I've cleared my browser cookies as per this SO post but that had no effect.

CustomerRoleProvider

public class CustomRoleProvider : RoleProvider
{
    public CustomRoleProvider()
    {            
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        bool isUserInRole = false;

        // omitted for brevity

        return isUserInRole;
    }

    public override string[] GetRolesForUser(string username)
    {
        string[] roles = null;

        // omitted for brevity

        return roles;
    }

    // omitted for brevity

}

web.config

    <authentication mode="Windows">
    </authentication>
    <authorization>
      <allow users="*"></allow>
      <deny users="?"/>
    </authorization>
    <roleManager defaultProvider="CustomRoleProvider" enabled="true">
      <providers>
        <clear />
        <add name="CustomRoleProvider" type="ProjectName.UI.Mvc.Code.Providers.CustomRoleProvider" />
      </providers>
    </roleManager>

Home Controller

[Authorize(Roles = "Administrator")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

This was caused from not having IIS Express set to use Windows Authentication. To fix I selected the project in Solution Explorer, opened the Properties window set Windows Authentication = Enabled and Anonymous Authentication = Disabled . Custom role provider now works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM