Blog Stats
  • Posts - 44
  • Articles - 0
  • Comments - 107
  • Trackbacks - 0

 

Monday, November 17, 2008

MVC Attributes via ActionFilterAttribute

I needed an attribute to decorate methods/controllers to protect them from being accessed by users that are not logged in.  If I were using a .net provider for authentication I could use the [Authorize] attribute that is provided in the MVC framework.  However, in this case I chose to create my own security.  This means that I need to also create my own [Authorize] attribute (as I love it’s simplicity!).  Finding the way to do this is not that straight forward.  So here is the custom attribute.

 

Code Snippet

0:  public class MustBeLoggedInAttribute : ActionFilterAttribute
1:  {
2:   private WebContext _webContext;
3:   public MustBeLoggedInAttribute()
4:   {
5:   _webContext = new WebContext();
6:   }

7:   public override void OnActionExecuting(ActionExecutingContext filterContext)
8:   {
9:   if(_webContext.Account == null)
10:   {
11:   string loginUrl = "~/Account/Login";

12:   filterContext.HttpContext.Response.Redirect(loginUrl);
13:   }

14:   base.OnActionExecuting(filterContext);
15:   }
16:  }
/pre>

 

And to use this new attribute simply decorate the method you want protect.

Code Snippet

0:  [MustBeLoggedIn]
1:  public ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword)
2:  {

3:   ViewData["Title"] = "Change Password";

4:   // Non-POST requests should just display the ChangePassword form
5:  if (Request.HttpMethod != "POST")
6:   {
7:   return View();
8:   }
/pre>

 

Notice that the name of the custom attribute is MustBeLoggedInAttribute but the usage of the attribute only shows MustBeLoggedIn – no Attribute!

I saw several hits of not using a hard coded Redirect path by specifying the controller and action.  If someone knows this answer for the current release of MVC please post it!  For now I can stick it in a config value or something.

 

 

Copyright © Andrew Siemer - www.andrewsiemer.com