2011-12-12 21 views
0

我正在使用ASP.NET 4 WCF服务进行某些数据事务。为了防止CSRF(跨站请求伪造),我想在输出中添加一些数据。有关如何做到这一点的任何建议?前置到WCF服务输出

[ServiceContract] 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 
public class TestService : ServiceBase 
{ 
    [WebGet(
     ResponseFormat = WebMessageFormat.Json, 
     UriTemplate = "/test.json") 
    ] 
    public MyResponse Test() 
    { 
     MyResponse resp; 
     try 
     { 
      Response.Write("for(;;){}"); // <-- Fix needed 
      resp = new MyResponse(); 
     } 
     catch (Exception ex) 
     { 
      AjaxException aex = new AjaxException() { 
       message = string.Format("Test failed. Exception: {0}.", ex.Message) 
      }; 
      throw new WebFaultException<AjaxException>(aex, HttpStatusCode.InternalServerError); 
     } 
     return resp; 
    } 
} 

[DataContract] 
public class MyResponse { 
    public MyResponse() { } 
    [DataMember()] 
    public long time = ServiceUtility.Convert(DateTime.Now); 
    [DataMember()] 
    public string secret { get; set; } 
} 

回答

1

我会建议你避免在可以改变状态的WCF操作上使用HTTP GET方法。据我所知,目前的浏览器不允许使用JSON内容类型进行跨站点POST请求 - 所以这应该可以防止CSRF攻击。

为了更安全起见,您可以检查HTTP Referrer头以查看服务调用是否源自允许的站点。