2009-08-24 27 views
16

Tôi có trang web .NET Webforms nhờ cần đăng lên Ứng dụng MVC của tôi hiện đang nằm bên trong trang Webform dưới dạng một ứng dụng riêng biệt.Tạo AntiForgeryToken trong WebForms

Ứng dụng biểu mẫu web cần đăng một số giá trị nhạy cảm với Ứng dụng MVC.

Có cách nào để tạo ra một AntiForgeryToken() trong ứng dụng WebForms của tôi để nó có thể được thông qua với biểu mẫu bài đăng.

Nếu không, bất kỳ ai biết về bất kỳ mã chống giả mạo tùy chỉnh nào khác sẽ cho phép tôi thực hiện điều gì đó tương tự như AntiForgeryValidation của MVC.

Trả lời

8

Tự mình thực hiện không quá khó.

  • Tạo một GUID
  • Đặt nó trong một lĩnh vực ẩn
  • Cũng đặt nó trong phiên hoặc Cookie (trong trường hợp thứ hai, với một số bảo vệ chống tamper)
  • Khi bắt đầu xử lý biểu mẫu so sánh trường và mã thông báo được lưu trữ.

(Nếu bạn nhìn vào việc thực hiện MVC, có rất ít nhiều đến nó. Một vài phương pháp helper là tất cả các bạn cần.)

+1

bất kỳ mã để hiển thị như thế nào để làm điều này? –

+2

@ShekharPankaj Xem [Bảng bảo mật .NET OWASP] (https://www.owasp.org/index.php/.NET_Security_Cheat_Sheet#ASP.NET_Web_Forms_Guidance). Hãy chắc chắn rằng bạn hiểu nó trước khi tích hợp (nghĩa là những gì nó bảo vệ bạn khỏi, và quan trọng hơn [những gì nó không bảo vệ bạn khỏi] (http://security.stackexchange.com/q/59470)). – tne

2

WebForms có analog khá tương tự trong Page.ViewStateUserKey. Bằng cách setting that to a per-user value (hầu hết chọn HttpSessionState.SessionId), WebForms sẽ xác thực ViewState như một phần của the MAC check.

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

Có kịch bản mà ViewStateUserKey will not help. Chủ yếu, họ đun sôi xuống để làm những điều nguy hiểm với yêu cầu GET (hoặc trong Page_Load mà không kiểm tra IsPostback), hoặc vô hiệu hóa ViewStateMAC.

1

Bạn có thể sử dụng sự phản chiếu để lấy các phương pháp MVC được sử dụng để đặt cookie và nhập biểu mẫu khớp được sử dụng để xác thực MVC. Bằng cách đó bạn có thể có một hành động MVC với các thuộc tính [AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken] mà bạn có thể đăng bài từ một trang WebForms được tạo ra.

Xem câu trả lời này: Using an MVC HtmlHelper from a WebForm

7

Đây là một câu hỏi cũ, nhưng chậm nhất Visual Studio 2012 ASP.NET mẫu cho các hình thức web bao gồm chống CSRF đang nướng vào trang chủ. Nếu bạn không có các mẫu, đây là đoạn code nó tạo ra:

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 
+1

Bài đăng tuyệt vời, nhưng bạn đã bỏ lỡ 3 dòng có 'AntiXsrfTokenKey' và' AntiXsrfUserNameKey' và '_antiXsrfTokenValue' được khai báo. Có thể hữu ích để cập nhật cho một số :-) – EvilDr

+0

@IanIppolito Mã này có xác thực các yêu cầu trực tiếp đến trình xử lý không?Bởi vì tại thời điểm đó tôi nghĩ rằng mã này sẽ không được thực hiện. –

+0

Xin chào, tôi đang sử dụng VS2013 và .Net FrameWork 4.5 để tạo ứng dụng biểu mẫu web ASP.net của tôi, nhưng trang chính của tôi không chứa mã được tạo tự động này, làm cách nào để biết trang web của tôi có an toàn với CSRF không? –

3

C# phiên bản của Ian Ippolito trả lời ở đây:

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) 
    { 

    } 
} 
+0

Có cần thiết phải xác thực với User Identity từ Context không? Trạng thái xem sẽ vẫn ở trạng thái của trang đó trong khi Context tiếp tục giữa các trang. Nếu thay đổi nhận dạng (bằng cách duyệt với nhiều tab) vào thời điểm xác thực được chạy, nó sẽ ném một ngoại lệ vì ViewState sẽ không thay đổi. – Tristan

Các vấn đề liên quan