0
votes

I use custom membership for Users and Roles in my MVC3 application. I have custom user/roles class. And I have the extended the RoleProvider and MembershipProvider classes for this.

I seem to have a case of roles going missing sometimes in my application and my Authorize [Roles='xyz'] attribute not working correctly and trying to redirect to Account/LogOn. When my user logs into the application, all I do is

if (ModelState.IsValid)
            {
                if (MyCustomSecurity.Login(model.UserName, model.Password, model.RememberMe))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
--other stuff
}

MyCustomSecurity.Login method basically looks up the user in the database and if valid sends a true value back.

When trying to debug the issue with my application, I came across the links below

http://www.codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF ASP.NET MVC Forms Authentication + Authorize Attribute + Simple Roles

Should I also be overriding FormsAuthentication_OnAuthenticate() as mentioned in this link? Or does the RoleProvider extended class take care of this?
Thank You

1

1 Answers

0
votes

If you use roles in AuthorizeAttribute, and roles are your own classes, so you need to override RoleProvider, especially method GetRolesForUser:

public class CustomRoleProvider : RoleProvider
{
    public override string[] GetRolesForUser(string username)
    {
    // put your logic to discover which roles the user has
    }
}

After doing that, you have to register you CustomRoleProvider in Web.Config:

<roleManager enabled="true" defaultProvider="CustomRoleProvider">
    <providers>
        <clear/>
        <add name="CustomRoleProvider" type="%YOURNAMESPACE%.CustomRoleProvider" />
    </providers>
</roleManager>