Custom AuthorizeAttribute: An example
A great feature in MVC 3 is something called annotaions. Annotations is mainly used for authorization and validation. By annotating your controllers, actions and models you get a clear seperation of validation/authorization logic and your code. The code gets cleaner, we all like that right?
There are bunch of built in annotations in MVC 3 like:
- [Authorize] – Forces a user to login
- [Required] – Makes a model property required
You can also write your own annotations which I’m about to show you.
This custom annotaion is how you can force a user to only edit, for instance, his own profile.
All you need to do is to create a class that inherits of the AuthorizeAttribute class
and override the method AuthorizeCore(HttpContextBase httpContext).
public class AuthorizeUserProfileEdit : AuthorizeAttribute
{
private string ParamName;
public AuthorizeUserProfileEdit(string paramName)
{
ParamName = paramName;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
string userNameParam = httpContext.Request[ParamName];
if (userNameParam.Equals(
httpContext.User.Identity.Name,
StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
return false;
}
}
As you can see there is not much to the code that needs exmplaining.
The constructor takes one argument that sets what paramenter name to check against.
The AuthorizeCore(HttpContextBase httpContext) then checks the value of the parameter against the currently logged in user. If it is the same the method returns true and the user is allowed to edit the profile, else the user is prompted to log in.
You then annotate your edit methods in your controller like this:
[AuthorizeUserProfileEdit("userName")]
[HttpGet]
public ActionResult Edit(string userName)
{
...
}
And like this in your post method:
[AuthorizeUserProfileEdit("userName")]
[HttpPost]
public ActionResult Edit(string userName, FormCollection collection)
{
...
}
Just supply the argument name as parameter to the annotaion and you are ready to go!
Can’t be much simplier!
Latest comments