locked
How to add antiforgery token for AJAX call in MVC application RRS feed

  • Question

  • User672776479 posted

    I'm trying mitigate CSRF issues for MVC application but facing issues while adding anti forgery token in following code in cshtml. Tried searching around but no concrete solution found.

    Would appreciate any help..

     <td class="ignoreClick">
                        
                                @Ajax.ActionLink(
                                                    "Delete","DeleteStudent","RqstProcessor",
                                                    new
                                                    {                                                    
                                                        id = current.key
                                                    },
                                                    new AjaxOptions
                                                    {
                                                        AllowCache = false,                                                    
                                                        HttpMethod = "POST",
                                                        UpdateTargetId = "StudentList",
                                                        InsertionMode = InsertionMode.Replace,
                                                    },
                                                    new
                                                    {
                                                        @class = "ignoreClick"
                                                    }
                                                 )
                        
                        </td>

    Friday, June 14, 2019 2:00 PM

All replies

  • User1520731567 posted

    Hi NetCurious,

    This link covers one solution http://tpeczek.com/2010/05/using-antiforgerytoken-with-other-verbs.html

    You could create a form with @Html.AntiForgeryToken() to generate html whose name is __RequestVerificationToken.

    Finally I'm going to write an attribute that inherits from the ValidateAntiForgeryTokenAttribute and that accepts forgery tokens in both the Request.Form and Request.QueryString

    For example:

    In view:

    ...
    @using (Html.BeginForm(null, null, FormMethod.Post))
        {
            @Html.AntiForgeryToken()
        }
    
        @Ajax.ActionLink("Delete","DeleteStudent","Home",new {id = current.key,__RequestVerificationToken = "_" },new System.Web.Mvc.Ajax.AjaxOptions
        {
            AllowCache = false,
            HttpMethod = "POST",
            UpdateTargetId = "StudentList",
            InsertionMode = InsertionMode.Replace
        },new{@class = "ignoreClick"})
    
    ...

    change href in <a>:

    <script type="text/javascript">
        $(document).ready(function () {
            //Finding AntiForgeryToken input
            var antiForgeryToken = $('input[name=__RequestVerificationToken]');
            if (antiForgeryToken.length > 0) {
                //Serializing AntiForgeryToken
                var antiForgeryTokenSerialized = antiForgeryToken.serialize();
                //For each anchor in page
                $('a.ignoreClick').each(function (index, element) {
                    //Replace placeholder with serialized AntiForgeryToken
                    $(element).attr('href', $(element).attr('href').replace('__RequestVerificationToken=_', antiForgeryTokenSerialized));
                });
            }
        });
    </script>

    in controller:

      [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
            public sealed class ValidateAjaxAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
            {
                public void OnAuthorization(AuthorizationContext filterContext)
                {
                    if (filterContext == null)
                    {
                        throw new ArgumentNullException("filterContext");
                    }
    
                    var httpContext = filterContext.HttpContext;
                    var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
                    AntiForgery.Validate(cookie != null ? cookie.Value : null, filterContext.HttpContext.Request.QueryString["__RequestVerificationToken"]);
                }
            }
            [HttpPost]
            [ValidateAjaxAntiForgeryToken]
            public ActionResult DeleteStudent(int id)
            {
                ...
            }

    Best Regards.

    Yuki Tao

    Monday, June 17, 2019 7:13 AM