C#post使用csrf令牌

时间:2014-11-02 07:48:21

标签: c# xml odata httpwebrequest csrf

我正在尝试使用C#抓取x-csrf-token发布XML数据。

能够使用get方法获取令牌,当我尝试发布时,我收到403错误 如果我错了,请帮助我

string Token = "";
public string Postdata = "<?xml version='1.0' encoding='utf-8'?> <entry xml:base='http://server:8000/sap/opu/odata/sap/ZCUST_TESTING_SRV/' xmlns='http://www.w3.org/2005/Atom' xmlns:m='http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' xmlns:d='http://schemas.microsoft.com/ado/2007/08/dataservices'> <content type='application/xml'><m:properties><d:Kunnr>55556697</d:Kunnr><d:Land1>abi</d:Land1><d:Name1>abh</d:Name1><d:Name2>chaitanya</d:Name2><d:Ort01>kennedy</d:Ort01><d:Pstlz>500060</d:Pstlz><d:EStatus>X</d:EStatus></m:properties></content></entry>";
public string URL = "http://server:8000/sap/opu/odata/sap/ZCUST_TESTING_SRV/post_cust";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Credentials = new NetworkCredential("username","password");
request.ContentType = "application/atom+xml";
request.Accept = "application/xml,application/atom+xml";
request.Method = "GET";
request.Headers["x-csrf-token"] = "Fetch";
HttpWebResponse responseH = (HttpWebResponse)request.GetResponse();
Token = responseH.Headers["x-csrf-token"];
//xcookies = responseH.Headers["set-cookie"];
responseH.Close();

// Here I'm creating Post Method ...
string requestString = HttpUtility.UrlPathEncode(data); //XMLDoc is the XML data string being submitted.
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(Postdata);
HttpWebRequest request_post = (HttpWebRequest)WebRequest.Create(URL);
request_post.Credentials = new NetworkCredential("username", "password");
request_post.Method = "POST";
request_post.ContentType = "application/xml";
request_post.Accept = "application/xml";
request_post.Headers["x-csrf-token"] = Token;
request_post.ContentLength = byteArray.Length;
request_post.KeepAlive = false;
Stream dataStream1 = request_post.GetRequestStream();
dataStream1.Write(byteArray, 0, byteArray.Length);
dataStream1.Close();
HttpWebResponse response1 = (HttpWebResponse)request_post.GetResponse();
dataStream1 = response1.GetResponseStream();
StreamReader reader1 = new StreamReader(dataStream1);
string responseFromServer1 = reader1.ReadToEnd();
reader1.Close();
dataStream1.Close();
response1.Close();

1 个答案:

答案 0 :(得分:0)

您的代码无法解决问题。只需发布一些常规提示:

  • 您确定NetworkCredential用户名/密码吗?

  • 尝试查看模拟浏览器是否会产生影响,例如:

    request_post.UserAgent =&#34; Mozilla / 5.0(Windows NT 6.1; WOW64)AppleWebKit / 535.2(KHTML,与Gecko一样)Chrome / 15.0.874.121 Safari / 535.2&#34 ;;

  • 检查您的请求参数和标题是否正确(接受, 的ContentType)

  • 您能否以其他方式成功完成此请求?你想要吗? 模仿网络应用的行为?您可以使用该Web应用程序并查看 使用Fiddler请求和响应数据/标头并确保 所有标题都是正确的(包括cookie)。