Authorize WebAPI request with ActionFilterAttribute

Action filters let you use pre and post processing logic which can be applied globally, to an action method or Controller class. These are generally used for applying logic for logging, caching, authorization etc. which can be shared across Controllers.

For adding Authorization to a WebAPI, we can use ActionFilterAttributes to enable strict access for a particular role or user. The ActionFilterAttribute class below implements the authorization logic.

The base ActionFilterAttribute class has the following methods that you can override as per the MS documentation:

  • OnActionExecuting – This method is called before a controller action is executed.
  • OnActionExecuted – This method is called after a controller action is executed.
  • OnResultExecuting – This method is called before a controller action result is executed.
  • OnResultExecuted – This method is called after a controller action result is executed.

As an example, you have a class called TokenFilter that inherits from ActionFilterAttribute. This class overrides the following methods OnActionExecuting and OnActionExecuted as below:

public class TokenFilter : ActionFilterAttribute
{


	public override void OnActionExecuting(HttpActionContext actionContext)
	{
		try
		{
			if (CheckValidHeaders(actionContext))
			{
				var auth_token = actionContext.Request.Headers.GetValues("access-token").FirstOrDefault();
				
				var ValidateObj = MyUtils.ValidateToken(auth_token);
				if (!ValidateObj.IsAuthenticated)
				{
					var error = MyUtils.GetNotSignedInErrorMessage();
					var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, error);
					actionContext.Response = response;
				}
				else
				{
					if (!ValidateObj.IsDurationValid)
					{
						auth_token = MyUtils.GenerateToken(email);
						actionContext.Request.Headers.Remove("access-token");
						actionContext.Request.Headers.Add("access-token", auth_token);
					}

					HttpContext.Current.Items.Add("access-token", auth_token);
					
				}
			}
			else
			{
				var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "error message");
				actionContext.Response = response;
			}
		}
		catch (Exception ex)
		{
			var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "error message");
			actionContext.Response = response;
		}
	}

The above code OnActionExecuting will check for valid Headers in the request, Validates the auth token and also generates the token if required. The new auth token is again injected into the Request Headers.

The OnActionExecuted method is as below:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    var auth_token = HttpContext.Current.Items["access-token"].ToString();
    actionExecutedContext.Response.Headers.Add("access-token", auth_token);
    var email = HttpContext.Current.Items["emailid"].ToString();
    actionExecutedContext.Response.Headers.Add("emailid", email);
}

Similary, other custom headers can be used to Authorize the request.

The below Authorize Filter class will authorize the user based on email id:

public class AuthorizeUserAttribute : ActionFilterAttribute
{
	bool IsinRole = false;
	public override void OnActionExecuting(HttpActionContext actionContext)
	{
		if (HttpContext.Current.Request.Headers["emailid"] != null)
		{
			var email = HttpContext.Current.Request.Headers["emailid"].ToString();
			 IsinRole = MyUtils.Checkroles(email, "admin");
			if(!IsinRole)
			{
				var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "error message");
				actionContext.Response = response;
			}
		}

	}
}

The below controller will use the TokenFilter and AuthorizeUser attributes to use the Filter out Unauthorized users as below:

[TokenFilter]
[AuthorizeUser]
public class ValuesController : ApiController
{

}

So any Action method that gets called for this Controller, has to have a valid token and a valid role Authorized to access this Controller.


Get great detals on Mobile Phones at Alibaba.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.