net mvc forgery foreign asp anti asp.net-mvc xss

asp.net-mvc - mvc - csrf asp net



Generando AntiForgeryToken en WebForms (5)

Esta es una pregunta antigua, pero la última plantilla de Visual Studio 2012 ASP.NET para formularios web incluye código anti CSRF integrado en la página maestra. Si no tienes las plantillas, aquí tienes el código que genera:

Protected Sub Page_Init(sender As Object, e As System.EventArgs) '' The code below helps to protect against XSRF attacks Dim requestCookie As HttpCookie = Request.Cookies(AntiXsrfTokenKey) Dim requestCookieGuidValue As Guid If ((Not requestCookie Is Nothing) AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue)) Then '' Use the Anti-XSRF token from the cookie _antiXsrfTokenValue = requestCookie.Value Page.ViewStateUserKey = _antiXsrfTokenValue Else '' Generate a new Anti-XSRF token and save to the cookie _antiXsrfTokenValue = Guid.NewGuid().ToString("N") Page.ViewStateUserKey = _antiXsrfTokenValue Dim responseCookie As HttpCookie = New HttpCookie(AntiXsrfTokenKey) With {.HttpOnly = True, .Value = _antiXsrfTokenValue} If (FormsAuthentication.RequireSSL And Request.IsSecureConnection) Then responseCookie.Secure = True End If Response.Cookies.Set(responseCookie) End If AddHandler Page.PreLoad, AddressOf master_Page_PreLoad End Sub Private Sub master_Page_PreLoad(sender As Object, e As System.EventArgs) If (Not IsPostBack) Then '' Set Anti-XSRF token ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty) Else '' Validate the Anti-XSRF token If (Not DirectCast(ViewState(AntiXsrfTokenKey), String) = _antiXsrfTokenValue _ Or Not DirectCast(ViewState(AntiXsrfUserNameKey), String) = If(Context.User.Identity.Name, String.Empty)) Then Throw New InvalidOperationException("Validation of Anti-XSRF token failed.") End If End If End Sub

Tengo un sitio de .NET Webforms gracias a que debo publicar en mi aplicación MVC que actualmente se encuentra dentro del sitio de Webform como una aplicación separada.

La aplicación Webform necesita POSTAR algunos valores confidenciales a la aplicación MVC.

¿Hay alguna manera de generar un AntiForgeryToken () en mi aplicación de WebForms para que se pueda pasar con la publicación del formulario?

De lo contrario, ¿alguien sabe de algún otro código de falsificación personalizado que me permita hacer algo similar a la AntiForgeryValidation de MVC?


Implementarlo usted mismo no es demasiado difícil.

  • Generar un GUID
  • Ponlo en un campo oculto.
  • También póngalo en Session o Cookie (en este último caso, con algo de protección contra manipulación indebida)
  • Al inicio del procesamiento del formulario, compare el campo y el token almacenado.

(Si observa la implementación de MVC, hay muy poco más que eso. Unos pocos métodos de ayuda son todo lo que necesita).


La versión C # de Ian Ippolito responde aquí:

public partial class SiteMaster : MasterPage { private const string AntiXsrfTokenKey = "__AntiXsrfToken"; private const string AntiXsrfUserNameKey = "__AntiXsrfUserName"; private string _antiXsrfTokenValue; protected void Page_Init(object sender, EventArgs e) { // The code below helps to protect against XSRF attacks var requestCookie = Request.Cookies[AntiXsrfTokenKey]; Guid requestCookieGuidValue; if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue)) { // Use the Anti-XSRF token from the cookie _antiXsrfTokenValue = requestCookie.Value; Page.ViewStateUserKey = _antiXsrfTokenValue; } else { // Generate a new Anti-XSRF token and save to the cookie _antiXsrfTokenValue = Guid.NewGuid().ToString("N"); Page.ViewStateUserKey = _antiXsrfTokenValue; var responseCookie = new HttpCookie(AntiXsrfTokenKey) { HttpOnly = true, Value = _antiXsrfTokenValue }; if (FormsAuthentication.RequireSSL && Request.IsSecureConnection) { responseCookie.Secure = true; } Response.Cookies.Set(responseCookie); } Page.PreLoad += master_Page_PreLoad; } protected void master_Page_PreLoad(object sender, EventArgs e) { if (!IsPostBack) { // Set Anti-XSRF token ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey; ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty; } else { // Validate the Anti-XSRF token if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty)) { throw new InvalidOperationException("Validation of Anti-XSRF token failed."); } } } protected void Page_Load(object sender, EventArgs e) { } }


Puede utilizar la reflexión para obtener los métodos MVC utilizados para configurar la cookie y la entrada de formulario correspondiente utilizada para la validación de MVC. De esa manera, puede tener una acción MVC con los [AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken] que puede publicar desde una página generada por WebForms.

Vea esta respuesta: Usando un MVC HtmlHelper de un WebForm


WebForms tiene un análogo bastante similar en Page.ViewStateUserKey . Al establecer eso en un valor por usuario (la mayoría elige HttpSessionState.SessionId ), WebForms validará el ViewState 1 como parte de la comprobación de MAC .

overrides OnInit(EventArgs e) { base.OnInit(e); ViewStateUserKey = Session.SessionId; }

1 Hay escenarios en los que ViewStateUserKey no ayudará . Principalmente, se reducen a hacer cosas peligrosas con solicitudes GET (o en Page_Ladir sin verificar IsPostback), o deshabilitar ViewStateMAC.