Skip to main content

Processing AntiForgeryToken send with Ajax

You might have seen below error while doing ajax post to MVC action that validates AntiForgeryToken.


ASP.net MVC ValidateAntiForgeryToken does not handle passing RVToken in ajax requests by default.
ex: Below token sent in header won't be accepted at Controller level in MVC:


__RequestVerificationToken = $('[name=__RequestVerificationToken]').val()


I found a  better solution that works perfectly fine for all POST requests. Just implement the custom MVC Authorize attribute as shown below code: 
[AttributeUsage(AttributeTargets.Class, AttributeTargets.Method)]
public class MyValidateAntiForgeryToken : AuthorizeAttribute
{
    public override void OnAuthorization( AuthorizationContext filterContext )
    {
        var request = filterContext.HttpContext.Request;
  
        if (request.HttpMethod == WebRequestMethods.Http.Post)
        { 
            if (request.IsAjaxRequest())
            {
                var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
 
                var cookieValue = antiForgeryCookie != null
                    ? antiForgeryCookie.Value 
                    : null;
 
                AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
            }
            else
            {
                new ValidateAntiForgeryTokenAttribute()
                    .OnAuthorization(filterContext);
            }
        }
    }
}
 
You can add this attribute on either a post action method or on the controller class. 

Put the below code in your _Layout.cshtml. This will handle the responsibility of sending AntiForgeryToken on all ajax post requests.
$(document).ready(function () { 
             
            $.ajaxSetup({
                'beforeSend': function (xhr) {
                    securityToken = $('[name=__RequestVerificationToken]').val();
                    xhr.setRequestHeader("__RequestVerificationToken", securityToken);
                }});

        }); 

 

Happy Coding!!!

Popular posts from this blog

Debugging code running on Remote machine

Before performing below steps, you need to make sure you have pdb files matching dll version on the remote machine.  Open below folder in your remote machine C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Remote Debugger\x64  Open that folder and launch as admin  msvsmon.exe  Select all options to allow firewall From Tools > Options  - Keep the settings to default (as shown below) and click ok.  At this point your remote debugger is all set. You need to connect from Visual Studio by entering Machine IP: Port (4022) 

Using IsInRole() with Forms Authentication

A Little background…. Page object provides User [ System.Security.Principal.IPrincipa l ] in order to access to the information about the current authenticated user. User is having following two important members. These members provide way to implement Role-based authorization programmatically. Identity [Property] [ System.Security.Principal.IPrincipal.Identity ] – This property provides important members like AuthenticationType, IsAuthenticated, Name. IsInRole [Method] [ System.Security.Principal . IPrincipa l ] – This method takes single parameter that is string value of Role for which to check the membership.

SharePoint yammer integration error: System.Exception: Unable to load the web part. IsEdit: False, IsAsync: False, FormMode: Invalid, SharedProperties: {"site_url":"http:// ","service_account":"true","webpart_guid":" ","iframe":"true","version":" "} at Yammer.SharePoint.WebParts.YammerAppsWebPart.CreateChildControls()

Hi there,  if you are searching for below error ..  System.Exception: Unable to load the web part. IsEdit: False, IsAsync: False, FormMode: Invalid, SharedProperties: {"site_url":"http:// ","service_account":"true","webpart_guid":" ","iframe":"true","version":" "} at Yammer.SharePoint.WebParts.YammerAppsWebPart.CreateChildControls()  The solution you can try could be disabling uploading file attachments to yammer. Below are the steps: 1.Select your webapplication from CA > Manage web apps 2.On the Ribbon>Yammer>Yammer Settings 3.Deselect 'Enable uploading file attachments to Yammer' 4.Click 'Save Settings'. And you are done! You can now add yammer web part to page and can check again.