Showing posts with label CustomAttribute. Show all posts
Showing posts with label CustomAttribute. Show all posts

Thursday, October 11, 2018

Default and Custom Authorization Attribute in MVC

1. Default Authorization Attribute
The standard ASP.NET  MVC  project's  [Authorize] attribute is as below.
 [Authorize] 
 public class HomeController : Controller { 
   //....  
 } 
Also we can specify roles and users with  [Authorize] attribute.
 [Authorize(Users = "user1,user2")]  
 public class HomeController : Controller { 
   //....  
 } 
 [Authorize(Roles= "Admin")]  
 public class HomeController : Controller { 
   //....  
 } 
The AuthorizeAttribute Class is defined as:
 [AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, Inherited = true,   
 AllowMultiple = true)]  
 public class AuthorizeAttribute : FilterAttribute,  
 IAuthorizationFilter  
 <>{  
 public AuthorizeAttribute()  
 {…}  
 protected virtual bool AuthorizeCore(HttpContextBase httpContext)  
 {…}  
 public virtual void OnAuthorization(AuthorizationContext filterContext)  
 <>{…}  
 protected void HandleUnauthorizedRequest(AuthorizationContext filterContext)  
 <>{…}  
 .  
 .  
 .  
 }
2. Custom Authorization Attribute
The class is derived from the AuthorizeAttribute class since the common behaviors are needed.
 using System.Web.Mvc;
 public class CustomAuthorizeAttribute : AuthorizeAttribute 
   { 
   protected override bool AuthorizeCore(HttpContextBase httpContext)
          {
            //Get the current user 
            if (httpContext.Request.IsAuthenticated && !string.IsNullOrEmpty(ApplicationContext.Current.UserId))
                return true;
            else
                return false;
          }
   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)  
          {  
            filterContext.Result = new HttpUnauthorizedResult();  
          } 
    }

Below is the way we use the created CustomAuthorize attribute.
 [CustomAuthorize] 
 public class HomeController : Controller { 
   //....  
 } 
If you need to add roles or users with the above Custom Attribute , just add the constructor to the CustomAuthorizeAttribute class with the roles/ users as params and define the role names above in the action method, controller.
   private readonly string[] allowedroles; 
   public CustomAuthorizeAttribute(params string[] roles)  
   {  
      this.allowedroles = roles;  
   }  
   //Then check the current user is in the allowedroles.
And use the created custom attribute in your action method as below.
 [CustomAuthorize(Roles= "Admin")]  
 public class HomeController : Controller { 
   //....  
 }