Further information can be provided if required, first post here!
I'm currently managing a website in asp.net mvc4 with the standard role authorisation(webpages_roles/webpages_usersinroles)
functionality.
This works fine to a point, actionresults within controllers are decorated as appropriate with tags such as:
[Authorize(Roles = "Admin")]
or where one of multiple roles can access:
[Authorize(Roles = "Admin, Manager")]
What I need to do, is to authorize multiple roles, a situation of "AND"
rather than "OR"
.
E.g. the user must be both in the "Manager"
role and the "Finance"
role to access a controller. Users with only "Manager"
or only "Finance"
but not both mustn't be able to access the action result.
How would this be achieved? Search results show people talk about extending the authorize attribute but if there is specific advice on how to do that or something more straight forward it in this case it would be very useful!
Spike's solution worked with a minor modification, the for each
was using var
to create a char
datatype, the IsInRole
function required a string
Final code:
public class AndAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
IPrincipal user = httpContext.User;
try
{
if (Roles != null && Roles.Any())
{
foreach (string r in Roles.Split(','))
{
if (!user.IsInRole(r))
return false;
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
}