Skip to main content

Generate new token on each request in MVC Ajax post call (Custom Code)

Generate new token on each request in MVC Ajax post call (Custom Code)
Image result for mvc

Step: 1
In controller add below Code to generate new random token and store it in the session
protected string GenerateCSRFToken()
{
 RandomNumberGenerator rng = new RNGCryptoServiceProvider("Add Your Salt String");
 var tokenData = new byte[64];
 rng.GetBytes(tokenData);
 var token = Convert.ToBase64String(tokenData);
 Session["CSRFtoken"] = token.Trim();
 return token;
}

Step: 2
In controller generate new token and pass it to view using ViewData.
public ActionResult Index()
{
 ViewData["CSRFtoken"] = GenerateCSRFToken();
 return View();
}

Step: 3
In View create hidden field and assign ViewData value to it.
<input type="hidden" value="@ViewData["CSRFtoken"]" id="hdnCSRFtoken" />

Step: 4
In View read and pass the hidden field value as method parameter/
<script type="text/javascript">
        ConvertToStringify = function (data) {
            data.name = JSON.stringify(data.name);
            return (data);
        };
        $(document).ready(function () {
            $("#btnAjaxJsonSubmit").click(function (event) {
                var txtvalue = $('#txtName').val();
                var myname = txtvalue;
                var token = $('#hdnCSRFtoken').val();
                $.ajax({
                    url: '@Url.Action("Create", "CSRFAjaxwithJsonStringify")',
                    type: "POST",
                    data: ConvertToStringify({ name: myname, token: token }),
                    dataType: "json",
                    traditional: true,
                    async: true,
                    success: function (response) {
                        $('#hdnCSRFtoken').val(response.CSRFNewToken);
                        alert(response.Message);
                    },
                    error: function (xhr) {
                        debugger;
                        alert(xhr.status);
                    }
                });
            });
        });
    </script>

Step: 5
In Controller validate session token value and parameter value and generate new token on success and pass to View.
public JsonResult Create(string name,string token)
        {
            var sessiontoken = Convert.ToString(Session["CSRFtoken"]);
            if (token == sessiontoken)
            {
                var newtoken = GenerateCSRFToken();
                return Json(new { Success = true, Message = name, CSRFNewToken = newtoken });
            }
            else
            {
                return Json(new { Success = false, Message = "Failed" });
            }
        }

Step: 6
In view update new token in hidden field value on success.
<script type="text/javascript">
        ConvertToStringify = function (data) {
            data.name = JSON.stringify(data.name);
            return (data);
        };
        $(document).ready(function () {
            $("#btnAjaxJsonSubmit").click(function (event) {
                var txtvalue = $('#txtName').val();
                var myname = txtvalue;
                var token = $('#hdnCSRFtoken').val();
                $.ajax({
                    url: '@Url.Action("Create", "CSRFAjaxwithJsonStringify")',
                    type: "POST",
                    data: ConvertToStringify({ name: myname, token: token }),
                    dataType: "json",
                    traditional: true,
                    async: true,
                    success: function (response) {
                        $('#hdnCSRFtoken').val(response.CSRFNewToken);
                        alert(response.Message);
                    },
                    error: function (xhr) {
                        debugger;
                        alert(xhr.status);
                    }
                });
            });
        });
    </script>


Comments

Popular posts from this blog

Visual Studio 2010 Error HRESULT E_FAIL has been returned from a call to a COM component.

I was using Visual Studio 2010.  I was debugging a web application and an exception happened and VS 2010 froze.  I ended the VS 2010 in the task manager and when I went back to developing, I found on every form for every ASP.net control I get:  Error Creating Control - Error HRESULT E_FAIL has been returned from a call to a COM component.  Also I am unable to edit  the form or add anything from the toolbox. Solution: This error comes because of Caching of Visual Studio Delete the Cache. You can delete the project cache at "Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplatesCache", then run "devenv /setup" to build the cache again to see if it helps.

Password Protected File Validation for(.doc/.docx/.xls/.xlsx/.pdf) file types

Password Protected File Validation for(.doc/.docx/.xls/.xlsx/.pdf) file types protected void btnUpload_Click( object sender, EventArgs e)         {             //Check if File Upload control has file or not             if (FileUpload1.HasFile)             {                 //Get Uploaded file bytes                 var bytes = FileUpload1.FileBytes;                 //Get Uploaded File Extension                 FileInfo objFileInfo = new FileInfo (FileUpload1.FileNam...

PDF Editor

http://www.pdfescape.com PDFescape is a free, online PDF reader, editor, form filler, & form designer. Free PDF Reader Free PDF Editor Free PDF Form Filler Free PDF Form Designer Free Webmaster Tools No Downloads No Watermarks A new way to open and edit PDF files online, PDFescape frees users from the typical software requirements for using the de facto document file format. Completely online, PDFescape requires no more than a modern internet browser and an active internet connection. Select any of the major features above to learn more.