问题
What's the data source Asp.net MVC uses to see if the user is in which role. And how can i change it so that it works with my own database table (when i write [Autorize(Roles="admin")] it checks in the table if the user is in the role )
回答1:
What's the data source Asp.net MVC uses to see if the user is in which role.
It uses the RoleProvider that is configured in your web.config. If you want to use custom tables you could write a custom role provider by inheriting from the RoleProvider class and implementing the abstract members. The IsUserInRole method is the one that you should always implement because that's what will be used in this case:
public class MyRoleProvider: RoleProvider
{
public override bool IsUserInRole(string username, string roleName)
{
// go and hit your custom datasource to verify if the user
// is in the required role and return true or false from this
// method
...
}
}
Then you could register your custom role provider in web.config in order to replace the default one:
<system.web>
...
<roleManager enabled="true" defaultProvider="MyRoleProvider">
<providers>
<add name="MyRoleProvider" type="Mynamespace.MyRoleProvider" />
</providers>
</roleManager>
</system.web>
And if you don't want to be using any providers (judging from your previous question that seems to be the case) then you should write a custom Authorize attribute which is not using a role provider at all but is using some custom code of yours:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.User.Identity.IsAuthenticated)
{
// no user is authenticated => no need to go any further
return false;
}
// at this stage we have an authenticated user
string username = httpContext.User.Identity.Name;
return IsInRole(username, this.Roles);
}
private bool static IsInRole(string username, string roles)
{
// the username parameter will contain the currently authenticated user
// the roles parameter will contain the string specified in the attribute
// (for example "admin")
// so here go and hit your custom tables and verify if the user is
// in the required role
...
}
}
and finally decorate your controller action with this custom attribute instead of relying on the default one which is based on the role provider:
[MyAutorize(Roles = "admin")]
public ActionResult Index()
{
...
}
来源:https://stackoverflow.com/questions/14921897/how-to-relate-roles-in-filter-attribute-with-my-database