Reputation: 67355
I have an ASP.NET MVC website where I've established a system of Permissions. There are, for example, some links that are hidden when the current user does not have sufficient permissions. However, if they manually type in the URL of that link, they can still access the content.
I know I can use the [Authorize]
attribute to prevent users without the right user role, but how can I implement my own attribute to block an action for users that do not meet custom requirements, without having to write a manual check inside each of those actions?
Upvotes: 3
Views: 3017
Reputation: 25694
If you are using ASP.NET Membership, you can configure a RoleProvider and give your users roles.
Then, you can use the Roles property on the AuthorizeAttribute to check for a role.
[Authorize(Roles="Admin, SuperUser")]
Upvotes: 1
Reputation: 1039508
You could write a custom Authorize
attribute and override the AuthorizeCore
method where you could place your custom authorization logic:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authroized = base.AuthorizeCore(httpContext);
if (!authroized)
{
return false;
}
// at this stage the base authorization process has passed.
// now implement your custom authorization logic and return true or false
// here you have access to the HttpContext and as a consequence to all
// request and route parameters so you could implement any
// authorization logic you want
// And of course if you want a completely custom authorization logic
// ignoring the base functionality don't call the base method above
// but completely override anything here
}
}
Now all that's left is to decorate the corresponding controllers/actions with this custom attribute.
Upvotes: 9