2009-08-24 39 views
16

私は.NET Webformsサイトを持っています。現在、Webformサイト内に別のアプリケーションとして存在するMVCアプリケーションに投稿する必要があります。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

Webフォームは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; 
} 

ViewStateUserKey will not helpシナリオがあります。主に、GETリクエスト(またはIsPostbackをチェックせずにPage_Load)で危険な作業をするか、ViewStateMACを無効にすることに沸きます。

1

リフレクションを使用すると、MVC検証に使用されるCookieと一致するフォーム入力を設定するために使用されるMVCメソッドを使用できます。そうすれば、[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]属性を持つMVCアクションをWebForms生成ページから投稿できます。

この回答を参照してください:Using an MVC HtmlHelper from a WebForm

7

は、これは古い質問ですが、Webフォーム用の最新のVisual Studio 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 Webフォームアプリケーションを作成していますが、マスターページにこの自動生成コードは含まれていません。 –

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を使用して検証する必要がありますか? Contextがページ間を移動している間は、ビューの状態はそのページの状態にとどまります。 IDが変更されると(複数のタブでブラウズすることにより)、検証が実行されるまでにViewStateは変更されないため、例外がスローされます。 – Tristan

関連する問題