Thursday 21 January 2016

Custom Authorization in MVC



-- Create an attribute for authorization

[AttributeUsage(AttributeTargets.All)]
public class CheckUserAuthorised : System.Web.Http.AuthorizeAttribute
{
   public CheckMobileUserAuthorised()
   {

   }

   public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext ctx)
   {
        //Do authorization logic here

                if (not  authorized  user)
                {
                    ctx.Response = ctx.Request
                                               .CreateResponse(System.Net.HttpStatusCode
                                                                                          .Unauthorized);
                }
    }


-- Implement attribute on method
 
     [CheckUserAuthorised]
     public bool Logout(AuthEntity authEntity)
     {

            //Do method’s code here           

     }