Thursday, August 30, 2012

Create a Custom Authorize Attribute in ASP.NET MVC


 Sample code for a creating a simple Authorize attribute. 
A user with "admin" username can only access the action which is decorated by [AdminAuthorize] attribute.

  
public class AdminAuthorize : AuthorizeAttribute
    {
        //return true if username is admin else return false
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            }
            Users = httpContext.User.Identity.Name.ToLower();
 
            return (Users == "admin");
        } 
    }

0 comments:

Post a Comment