mercredi 3 février 2016

How to unit test AntiforgeryToken filter for web api 2

I am trying to write unit test case using mstest for custom filter which has the logic to validate the Antiforgerytoken for POST method in ASP.NET WEB API 2 project.

[AttributeUsage(AttributeTargets.Method, Inherited = true)]
    public class ValidateJsonAntiForgeryTokenAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Filter the validate the antiforgery token
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            try
            {
                #region AntiForgeryValidation

                string cookieToken = null;
                string formToken = null;

                if (actionContext.Request.IsAjaxRequest())
                {
                    IEnumerable<string> tokenHeaders;
                    if (actionContext.Request.Headers.TryGetValues("__RequestVerificationToken", out tokenHeaders))
                    {
                        string[] tokens = tokenHeaders.First().Split(':');
                        if (tokens.Length == 2)
                        {
                            cookieToken = tokens[0].Trim();
                            formToken = tokens[1].Trim();
                        }
                    }
                    if (cookieToken != null && formToken !=null)
                    {
                        AntiForgery.Validate(cookieToken, formToken);
                    }
                    else
                    {
                        AntiForgery.Validate();
                    }                    
                }

                #endregion
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex);
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
            }            
        }
    }

In the below code IsAjaxRequest is an extension method

public static class HttpRequestMessageExtensions
    {
        public static bool IsAjaxRequest(this HttpRequestMessage request)
        {
            IEnumerable<string> headers;
            if (request.Headers.TryGetValues("X-Requested-With", out headers))
            {
                var header = headers.FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(header))
                {
                    return header.ToLowerInvariant() == "xmlhttprequest";
                }
            }

            return false;
        }
    }

Here my issue how to mock the IsAjaxRequest and how to pass actionContext parameter to the OnActionExecuting method.

Can anyone help me to provide some code samples regarding this?

Aucun commentaire:

Enregistrer un commentaire