添加到 WCF 服务输出之前
我正在使用 ASP.NET 4 WCF 服务进行一些数据事务。为了防止 CSRF(跨站点请求伪造),我想在输出中添加一些数据。关于如何执行此操作有什么建议吗?
[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; }
}
I'm using ASP.NET 4 WCF Services for some data transactions. To prevent CSRF (Cross-site request forgery) I'd like to prepend some data to the output. Any suggestions on how to do this?
[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; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您避免在可能更改状态的 WCF 操作上使用 HTTP GET 方法。据我所知,当前的浏览器不允许使用 JSON 内容类型执行跨站点 POST 请求 - 因此这应该可以防止 CSRF 攻击。
为了提高安全性,您可以检查 HTTP Referrer 标头以查看服务调用是否源自允许的站点。
I will suggest you to avoid using HTTP GET method on WCF operations that can change the state. To my knowledge, current browsers does not allow to do cross site POST requests with JSON content type - so this should prevent CSRF attacks.
For more security, you can check the HTTP Referrer header to see if the service calls are originated from the allowed site(s).