2009-08-24 15 views
16

Webform 사이트에 별도의 응용 프로그램으로 현재 앉아있는 MVC 응용 프로그램에 게시해야하는 .NET Webforms 사이트가 있습니다.WebForms에서 AntiForgeryToken 생성

Webform 응용 프로그램은 일부 중요한 값을 MVC 응용 프로그램에 POST해야합니다.

내 WebForms 응용 프로그램에 AntiForgeryToken()을 생성하여 양식 게시와 함께 전달할 수 있습니까?

그렇지 않으면 누구든지 MVC의 AntiForgeryValidation과 비슷한 작업을 수행 할 수있는 다른 위조 방지 위조 코드를 알고 있습니다.

답변

8

직접 구현하는 것은 그리 어렵지 않습니다.

  • GUID를 생성
  • 를 처리의 시작에서 숨겨진 필드
  • 또한
  • (일부 변조 방지 보호, 후자의 경우) 세션이나 쿠키에 넣어
  • 에 넣어 양식은 필드와 저장된 토큰을 비교합니다.

(당신이 MVC의 구현을 보면, 아주 조금 더 거기에있다. 몇 가지 헬퍼 메소드는 당신이 필요로하는 모두이다.)

+1

모든 코드는이 작업을 수행하는 방법을 보여? –

+2

@ShekharPankaj [OWASP .NET 보안 속임수 시트] (https://www.owasp.org/index.php/.NET_Security_Cheat_Sheet#ASP.NET_Web_Forms_Guidance)를 참조하십시오. 통합하기 전에 (즉, 사용자를 보호하는 것, 무엇보다 사용자를 보호하지 않는 것) (http://security.stackexchange.com/q/59470)을 이해해야합니다. – tne

2

웹폼은 Page.ViewStateUserKey에 꽤 유사한 아날로그있다. setting that to a per-user value (대부분 HttpSessionState.SessionId)을 선택하면 WebForms는 the MAC check의 일부로 ViewState 의 유효성을 검사합니다.

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

1 시나리오 곳 ViewStateUserKey will not help있다. 주로 GET 요청 (또는 IsPostback을 확인하지 않고 Page_Load)을 사용하여 위험한 일을하거나 ViewStateMAC를 사용하지 않도록 설정합니다.

1

리플렉션을 사용하면 MVC 유효성 검사에 사용되는 쿠키 및 일치하는 양식 입력을 설정하는 데 사용되는 MVC 메소드를 사용할 수 있습니다. 그렇게하면 웹 폼 생성 페이지에서 게시 할 수있는 [AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken] 특성을 사용하여 MVC 작업을 수행 할 수 있습니다.

이 대답을 참조하십시오 : Using an MVC HtmlHelper from a WebForm

7

이 오래된 질문은,하지만 웹 양식에 대한 최신 비주얼 스튜디오 2012 ASP.NET 템플릿은 마스터 페이지에 구운 방지 CSRF 코드가 포함되어 있습니다. 당신은 템플릿이없는 경우, 여기가 생성하는 코드는 다음과 같습니다

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

훌륭한 게시물이지만 'AntiXsrfTokenKey'와'AntiXsrfUserNameKey' 및'_antiXsrfTokenValue'가 선언 된 3 줄을 놓쳤습니다. 일부를 업데이트하는 데 유용 할 수 있습니다 :-) – EvilDr

+0

@IanIppolito이 코드는 처리기로 직접 전달되는 요청의 유효성을 검사합니까?그 당시 나는이 코드가 실행되지 않을 것이라고 생각하기 때문에. –

+0

안녕하세요, 선생님, VS2013 및 .Net FrameWork 4.5를 사용하여 ASP.net 웹 양식 앱을 만들었지 만 마스터 페이지에이 자동 생성 코드가 포함되어 있지 않습니다. 내 사이트가 CSRF로부터 안전한 지 어떻게 알 수 있습니까? –

3

여기 이안이 폴리 토 응답의 C# 버전 :

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

컨텍스트에서 사용자 ID로 유효성을 검사해야합니까? 컨텍스트가 페이지 사이를 이동하는 동안 뷰 상태는 해당 페이지의 상태로 유지됩니다. ID가 변경되면 (여러 탭으로 탐색하여) 유효성 검사가 실행될 때까지 ViewState가 변경되지 않으므로 예외가 발생합니다. – Tristan

관련 문제