2013-10-23 71 views
0

我知道我錯過了某些東西,但它不工作,我不知道什麼是錯的。這是自定義防僞屬性。防僞驗證不起作用

[AttributeUsage(AttributeTargets.Class)] 
public class ValidateAntiForgeryTokenOnAllPosts : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     var request = filterContext.HttpContext.Request; 

     // Only validate POSTs 
     if (request.HttpMethod == WebRequestMethods.Http.Post) 
     { 
      // Ajax POSTs and normal form posts have to be treated differently when it comes 
      // to validating the AntiForgeryToken 
      if (request.IsAjaxRequest()) 
      { 
       var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName]; 

       var cookieValue = antiForgeryCookie != null 
        ? antiForgeryCookie.Value 
        : null; 

       AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]); 
      } 
      else 
      { 
       new ValidateAntiForgeryTokenAttribute() 
        .OnAuthorization(filterContext); 
      } 
     } 
    } 
} 

我送從Ajax請求的令牌。

console.log(JSON.stringify(data)); 
    return $.ajax({ 
     url: url, 
     type: "post", 
     cache: false, 
     contentType: "application/JSON; charset=utf-8", 
     crossDomain: true, 
     data: JSON.stringify(data), 
     dataType: "json", 
     beforeSend: function (xhr) { 
      xhr.setRequestHeader("Accept", "application/json, text/json, */*"); 
      xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); 
      xhr.setRequestHeader("Authorization", "__RequestVerificationToken token=\"FuHCLyY46\""); 
     } 

而在Asp主頁我已經把隱藏的領域。

<form id="form1" runat="server"> 

<div> 
    <input type="hidden" name="__RequestVerificationToken" value="FuHCLyY46"/> 

</div> 

</form> 

但它不工作。請確定我在做什麼錯?

回答

0

你沒有這正是你正試圖在這裏找到一個__RequestVerificationToken請求頭:

AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]); 

您發送實際的頭被稱爲Authorization。所以,你可以使用一個專用的頭,將發送令牌值:

xhr.setRequestHeader("AntiForgeryToken", "FuHCLyY46"); 

然後:

AntiForgery.Validate(cookieValue, request.Headers["AntiForgeryToken"]); 
+0

我筋疲力盡申請反僞造在我的情況。實際上我是在使用asp頁面(不是Rajor)的項目中實現安全性。我不知道如何在asp窗體中實現它。 – vivek

0

爲什麼你不使用默認的框架防僞造行爲過濾器和相對的HTML幫助? 不打框架:)

更多信息關於CSRF here