1

Background

I need to use an AntiForgeryToken from a WebForms page (hosted in a cms). The page should post data to an MVC 2.0 action that is part of the solution. The action should use the ValidateAntiForgeryToken attribute.

I did try the solution from here: Using an MVC HtmlHelper from a WebForm but it didn't seem to work, as the rendered antiforgerytoken was signalled as invalid from the controller action.

Current solution

Now I've solved it such that I have an action available rendering a partial view containing only an input tag with an antiforgerytoken.

View

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.AntiForgeryToken() %>

The page uses javascript to pull in the antiforgerytoken into the form like so:

Form

<form id="jsonForm" action="/my/action" method="post">
  <input id="tokenPlaceholder" type="hidden" />

Fetch antiforgery token

<script type="text/javascript">
    $(function () {
        $.ajax({
            url: "/antiforgery/token",
            type: "GET",
            success: function (data, textStatus, jqXHR) {
                $("#tokenPlaceholder").replaceWith(data);
            }
        });
    });
</script>

This works as far as the form posting is valid according to the ValidateAntiforgeryToken attribute.

Questions

Is there any security issues with adding the antiforgery token to the form this way?

Is there a simpler way I didn't dry?

Community
  • 1
  • 1
Carl R
  • 8,104
  • 5
  • 48
  • 80

1 Answers1

0
 <script>
@functions{
    public string TokenHeaderValue()
    {
        string cookieToken, formToken;
        AntiForgery.GetTokens(null, out cookieToken, out formToken);
        return cookieToken + ":" + formToken;                
    }
}

$.ajax("/antiforgery/token", {
    type: "post",
    contentType: "application/json",
    data: {  }, // JSON data goes here
    dataType: "json",
    headers: {
        'RequestVerificationToken': '@TokenHeaderValue()'
    }
});
 </script>

When you process the request, extract the tokens from the request header. Then call the AntiForgery.Validate method to validate the tokens. The Validate method throws an exception if the tokens are not valid.

 void ValidateRequestHeader(HttpRequestMessage request)
 {
   string cookieToken = "";
   string formToken = "";

IEnumerable<string> tokenHeaders;
if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
{
    string[] tokens = tokenHeaders.First().Split(':');
    if (tokens.Length == 2)
    {
        cookieToken = tokens[0].Trim();
        formToken = tokens[1].Trim();
    }
}
AntiForgery.Validate(cookieToken, formToken);
}

Learn more on original post

Bellash
  • 7,560
  • 6
  • 53
  • 86