Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

@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));
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
890 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...