'How to get AntiForgeryToken value without hidden input

@Html.AntiForgeryToken() renders hidden input

<input name="__RequestVerificationToken" type="hidden" value="GuiNIwhIJZjINHhuS_8FenaFDXIiaE" />

How can I get token value only? Without ugly code like this:

public static IHtmlString AntiForgeryTokenValue(this HtmlHelper htmlHelper) {
        var field = htmlHelper.AntiForgeryToken().ToHtmlString();
        var beginIndex = field.IndexOf("value=\"") + 7;
        var endIndex = field.IndexOf("\"", beginIndex);
        return new HtmlString(field.Substring(beginIndex, endIndex - beginIndex));
    }


Solution 1:[1]

The anti-CSRF capabilities of MVC actually depend on two tokens: one is a hidden form element, and the other is a cookie. So the Html.AntiForgeryToken() helper doesn't just return an HTML snippet. It also has a side effect of setting this cookie. Note that the cookie value and the form value are not equal since they each encode different pieces of information.

If you use the AntiForgery.GetTokens API, this method will return the raw tokens instead of generating an HTML snippet. The parameters to this method are:

  • oldCookieToken: If the request already contains an anti-CSRF cookie token, provide it here. This parameter may be null.
  • newCookieToken (out parameter): If oldCookieToken was null or did not represent a valid anti-CSRF cookie token, this parameter will be populated with the value that you should put in the response cookie. If oldCookieToken represented a valid anti-CSRF token, then newCookieToken will contain null when the method returns, and you don't have to set a response cookie.
  • formToken (out parameter): This parameter will be populated with the token that should be present in the form body when posting back to the server. This is the value that ends up being wrapped by the hidden input element in a call to Html.AntiForgeryToken().

If you use this API to generate cookie and form tokens manually, you'll need to call the corresponding overload of AntiForgery.Validate in order to validate the tokens.

Solution 2:[2]

I realize this question is old, but based on what I read here I came up with a reasonably simple solution that seems to work for me. I'm using it on an AngularJS SPA that uses partial templates, only some of which involve POST submissions.

I put this code at the top of view:

@{
    string cookieToken, formToken;
    string oldCookieToken = Request.Cookies[AntiForgeryConfig.CookieName] == null ? null : Request.Cookies[AntiForgeryConfig.CookieName].Value;
AntiForgery.GetTokens( oldCookieToken, out cookieToken, out formToken );

    if( oldCookieToken == null ) 
    {
        Request.Cookies.Add( new HttpCookie( AntiForgeryConfig.CookieName,     cookieToken ) );
    }
    else 
    {
        Request.Cookies[AntiForgeryConfig.CookieName].Value = cookieToken;
    }
}

and then wherever I need the form's antiforgery token (e.g., in an ajax or angularjs POST) I just include '@formToken' in the headers:

$http.post(route, JSON.stringify(args), {
     headers: {
        '@AntiForgeryConfig.CookieName':  '@formToken',
        'Content-Type': 'application/json; charset=utf-8',
     },
});

Note that because in this example I'm expecting JSON data back from my action method I also had to implement anti-forgery validation based on headers, not form fields. There's a nice post about this at http://johan.driessen.se/posts/Updated-Anti-XSRF-Validation-for-ASP.NET-MVC-4-RC.. Here's the implementation:

[AttributeUsage( AttributeTargets.Method | AttributeTargets.Class,
                AllowMultiple = false, Inherited = true )]
public sealed class ValidateJsonAntiForgeryTokenAttribute
                            : 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,
                             httpContext.Request.Headers[AntiForgeryConfig.CookieName] );
    }
}

and here's how it's used:

    [HttpPost]
    [ValidateJsonAntiForgeryToken]
    public JsonResult RecordVisit( VisitInfo info )

Solution 3:[3]

This is a bit old, but i found no real answers for this one. I peeked around and found this solution. I need the formtoken in an javascriptobject, so this helper came in handy.

public static class AntiForgeryHtmlExtensions { public static string AntiForgeryFormToken(this HtmlHelper helper) { string cookieToken, formToken; AntiForgery.GetTokens(null, out cookieToken, out formToken); HttpContext.Current.Response.Cookies.Set(new HttpCookie(AntiForgeryConfig.CookieName, cookieToken)); return formToken; } }

As @Levi mentioned, calling GetTokens, has sideeffects, so we have to set the response-cookie before returning the token.

Solution 4:[4]

For asp.net core use dependency injection to get IAntiforgery and then call GetAndStoreTokens

public class TestController
{
    public TestController(IAntiforgery antiforgery)
    {
        var tokens = antiforgery.GetAndStoreTokens(HttpContext);
    }
}

Solution 5:[5]

If using core you can do this in the layout or razor page like so:

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Antiforgery
@{
    var afToken = Antiforgery.GetAndStoreTokens(HttpContextAccessor.HttpContext!).RequestToken;
}

<html lang="en">
<head></head>
<body>
    <script type="text/javascript">
        window.XCSRF = '@afToken';
        console.log(window.XCSRF);
    </script>

now you can access the token using javascript window.XCSRF variable

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Levi
Solution 2 Mark Olbert
Solution 3 Jesper Jensen
Solution 4 Thomas
Solution 5 George Filippakos