Tuesday, 7 June 2016

MVC Authorization filter

MVC supports 4 types of filter

  • Authorization
  • Action
  • Result
  • Exception

Authorization filter
It is executed after the user is authenticated in MVC life-cycle. It is basically used to authorize user from resources of your application. You can create your own custom authorization filter. A class which extend AuthorisationFilterAttribute class and overrides its OnAuthorization() method is authorization filter.

Example - Suppose you need to access user data from WEB API by providing authorization token. 

Controller
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
    [HttpGet]
    [Route("GetUserAppProfile")]
    [AppAuthorization]
    public IHttpActionResult GetUserProfile()
    {
        try
        {
            long userId = Convert.ToInt64(Request.Headers.GetValues("UserId").FirstOrDefault());
            var res = _userRepository.GetUserAppProfile(userId);
            return Ok(res);
        }
        catch (Exception ex)
        {
            return Content<object>(HttpStatusCode.InternalServerError, new { Status = false, Message = ex.Message });
        }
    }
}

Custom filer
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (!actionContext.Request.Headers.Contains("AuthToken"))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Status = false, Message = "Token is missing" });
            }
            else
            {
                string authToken = actionContext.Request.Headers.GetValues("AuthToken").FirstOrDefault();

                if (string.IsNullOrEmpty(authToken))

                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Status = false, Message = "Token is missing" });
                }
                else
                {
                    long userId = userService.AuthorizeAppUser(authToken);

                    if (userId != null)

                    {
                        actionContext.Request.Headers.Add("UserId", userId.ToString());
                    }
                    else
                    {
                        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Status = false, Message = "Invalid token" });
                    }
                }               
            }
            base.OnAuthorization(actionContext);
        }//End
    }

Before execution of action method, This custom authorization filter will execute and check for authentication token in header if token doesn't exist. It will straight forward return the status and message. And will not execute the action method.

No comments:

Post a Comment