Problems with IsInRole - customRoleProvider
I implemented a custom RoleProvider with custom Authentication over the weekend. Using the Silverlight Business Template, I was able to put a [RequiresRole("Admin")] attribute on a service request:
[RequiresRole("Admin")]
public IQueryable<P_BUDGET> GetBudgets()
{
return this.ObjectContext.P_BUDGET;
}
This worked like a charm. I used the following code
I 开发者_运维知识库then dropped in Kyle McClellans authorization library. If I set a "RequiresRole" attribute on a HyperlinkButton in my XAML (s:Authorization.RequiresRole="Admin"), it hides the button successfully on app load. When I login, I expected it to identify the "Admin" role that my test user is in, eventually changing the visibility of that HLB to true. However, when I step through the code, I get into my App.Web.g.cs file, and it has this function:
public bool IsInRole(string role)
{
if ((this.Roles == null))
{
return false;
}
return global::System.Linq.Enumerable.Contains(this.Roles, role);
}
In the above code, this.Roles is null. What am I missing here? The first code block uses the "GetRolesForUser" method, which I've overridden, and returns a list of roles from a View I have in my db. The second used the IsInRole, which I have read is not something you should modify.
Your help is appreciated!
Your custom role provider should be responsible for generating the list of roles from your database or verifying if the user is in a role via a database call
Take a look at this sample code from microsoft: http://msdn.microsoft.com/en-us/library/system.web.security.roleprovider.isuserinrole.aspx
i've implemented my custon role provider, you need to create the roles in the global.asax, int Application_Start method. I've something like this:
void Application_Start(object sender, EventArgs e)
{
Roles.ApplicationName = "MyAppName";
if (!Roles.RoleExists("admin"))
Roles.CreateRole("admin");
if (!Roles.RoleExists("operator"))
Roles.CreateRole("operator");
if (!Roles.RoleExists("user"))
Roles.CreateRole("user");
}
Good luck.
Roles
in this case is a property of the UserBase
class inherited by the User
class that's defined in the supporting web project (Models/User
folder). By default, this uses the Forms Authentication mecanism and data about users, profiles, "roles", etc. are stored in a local database (in the App_Data
folder). For this to work, I suggest that you override this property to return the specific roles you need, and you should also set Forms Authentication to use your own user data.
Hope this helps :)
Thanks for the answers guys, but I found the solution here by a comment made by Kyle McClellan in his own answer. I was already overriding GetAuthenticatedUser, part of which included getting my roles from the db. Quite simply, I had to put user.Roles = roles, where roles is a list of the roles returned from my db View.
精彩评论