title: How can I retrieve anti-forgery tokens in a JavaScript function if cookies have the HttpOnly header set?
body: <p>I have a web application I am writing on the ASP.NET MVC 4.7 framework and I am trying to properly add anti forgery tokens to my JavaScript AJAX calls.</p>
  <p>I am learning from OWASP and Microsoft documentation.
  According to this article from Microsoft, the best way to prevent CSRF in AJAX is with anti forgery tokens.</p>
  <p><a href="https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks</a></p>
  <p>In my application currently, when there is a form submission, a JavaScript function is called to handle the AJAX call to my API. If JavaScript is disabled then a regular http request is made to a C# function which also uses AJAX to call the API.</p>
  <p>The article shows a bit of C# code which can retrieve the token so it can be passed with the AJAX call. The problem I am running into here is that in order to mix C# and JS functions they use the razor syntax and inline-scripting.</p>
  <p>I don’t use inline-scripting for security reasons, and I also have the HttpOnly header set for all cookies. So, to avoid inline-scripting, these JavaScript functions are running in a separate .js file which means I can’t use any C# code to retrieve the token. Also, because of the httpOnly header on the cookies, I do not believe I can retrieve the token using pure javascript.</p>
  <p>Passing and validating the tokens works fine with the c# implementation, but I don’t see a way to do this in javascript.</p>
  <p>Can someone tell me where I am wrong? Or what I am missing?</p>
  <p>If there’s nothing that can be done about this then I may have to completely delete the JavaScript submit functions, but this would mean client side validation would be limited.</p>
  <p>Thanks ahead of time for any assistance.</p>
  <p>(P.S.) I can’t just pass the token to a JavaScript function for two reasons.</p>
  <p>One, I don’t want to pass the token as a plain text parameter in the webpage because then the token would always be plain text in the html.</p>
  <p>Two, I am not using “OnClick” at all as that is seen as lining-scripting. This is working off of listener events so I can’t exactly pass a parameter to the function anyways.</p>