Tuesday, 28 June 2016

We API: Implementing custom authorization.

Step 1: Create new CustomAPIAuthorizeAttribute.cs class and inherit it from ActionFilterAttribute. Now write the following code in that class.

 public class CustomAPIAuthorizeAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Override the OnActionExecuting method to perform check validation operation.
        /// </summary>
        /// <param name="actionContext">HttpActionContext object</param>
       public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!SkipAuthorization(actionContext))
            {
                if (!actionContext.Request.Headers.Contains("SessionId"))
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Message = "SessionId missin in headers", Status = false });
                    return;
                }

                var tokenValue = actionContext.Request.Headers.GetValues("SessionId").FirstOrDefault();
                //now validate token value from db and apply check accordingly
            }
        }
    
    //This function checks the AllowAnonymous attribute existance on the controller action method.
    private static bool SkipAuthorization(HttpActionContext actionContext)
        {
            Contract.Assert(actionContext != null);

            return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()
                   || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
        }
   }

Step 2: In this account api controller you can see the two methods. On Login method I have added [AllowAnonymous] attribute. This helps us to access this method anonymously. And for access the GetUserProfile method you need SessionId in the request headers because I have added [CustomAPIAuthorize] attribute on the top of account controller.

    /// <summary>
    /// Account controller
    /// </summary>
    [RoutePrefix("api/Account")]
    [CustomAPIAuthorize]    
    public class AccountController : APIController
    {
        [HttpPost]
        [Route("Login")]
        [AllowAnonymous]
        public async Task<IHttpActionResult> Login(LoginModel info)
        {
            //do code for validate login info
            return Ok();
        }

        [HttpGet]
        [Route("GetUserProfile")]
        public async Task<IHttpActionResult> GetUserProfile()
        {
            return Ok();
        }
    }

No comments:

Post a Comment