C#:使用httpclient

时间:2017-09-01 20:44:45

标签: c# uwp csrf dotnet-httpclient

我正在尝试通过 UWP 应用将有效负载发布到我们的后端系统。为此,我首先进行GET以获取CSRF令牌,然后将其添加到POST请求的标头中。发帖时,我仍然收到403 Forbidden错误。

我通过执行单独的GET和POST请求并将从GET获取的CSRF令牌提供给POST标头来对'Insomnia'REST客户端进行交叉测试,并且它正常工作。

我是C#的新手,所以请原谅糟糕的编码标准。

获取令牌

    public async Task<string> GetCSRF()
    {
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
                                                                                                                    System.Text.Encoding.ASCII.GetBytes(
                                                                                                                            string.Format("{0}:{1}", userName.Text.ToUpper(), SAPpassword.Password))));
            httpClient.DefaultRequestHeaders.Add("X-CSRF-TOKEN", "fetch");
            HttpResponseMessage response = await httpClient.GetAsync(new Uri(_URI));
            response.EnsureSuccessStatusCode();
            if (response.Content == null)
                return null;
            String csrfToken = response.Headers.GetValues("X-CSRF-TOKEN").FirstOrDefault();
            return csrfToken;
        }
    }

我使用csrf令牌

收到了以下标题
  
      
  • response.Headers {x-csrf-token:w1Id2Kn1r0d6EItk6vEi0g ==   cache-control:no-store,no-cache   sap-metadata-last-modified:星期五,01九月2017 10:57:07 GMT   dataserviceversion:2.0   set-cookie:sap-usercontext = sap-client = 100;路径= /,MYSAPSSO2 = AjQxMDMBABhTAFMARQBOAEcAVQBQAFQAQQAgACAAIAACAAYxADAAMAADABBHAFcAMQAgACAAIAAgACAABAAYMgAwADEANwAwADkAMAAxADIAMAA0ADkABQAEAAAACAYAAlgACQACRQD%2fAPswgfgGCSqGSIb3DQEHAqCB6jCB5wIBATELMAkGBSsOAwIaBQAwCwYJKoZIhvcNAQcBMYHHMIHEAgEBMBkwDjEMMAoGA1UEAxMDR1cxAgcgFAMoIAMBMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xNzA5MDEyMDQ5MzhaMCMGCSqGSIb3DQEJBDEWBBRP7sl8St9p53T9Sfu58sTb3jTNFjAJBgcqhkjOOAQDBC8wLQIVALIiQKECoPjhBihxA7OXoDOEGy3YAhQroXwahnTKR0A7du7u5zwj1Q0cgg%3D%3D;路径= /; domain = .mindsetconsulting.com,SAP_SESSIONID_GW1_100 = u1BKLug0BNWYM0-zg_JWTBEihxmPVxHnvTMKDkBCwEk%3d;路径= /   access-control-allow-credentials:true   access-control-allow-headers:*   access-control-allow-origin:* .google.com   access-control-allow-methods:*   System.Net.Http.Headers.HttpResponseHeaders
  •   

使用令牌发布有效内容

        public async Task<string> SendChannelToSAP(UserStorage userStorage, string csrf)
    {
        string payloadJson;
        string jsonResponse;
        HttpResponseMessage response;
        HttpContent content;

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                                                            "Basic", Convert.ToBase64String(
                                                                System.Text.Encoding.ASCII.GetBytes(
                                                                     string.Format("{0}:{1}", userName.Text.ToUpper(), SAPpassword.Password))));


            payloadJson = JsonConvert.SerializeObject(userStorage);
            content     = new StringContent(payloadJson);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            client.DefaultRequestHeaders.Add("x-csrf-token", csrf);
            try
            {
                response = await client.PostAsync(_URI, content);
                if (response.IsSuccessStatusCode)
                {
                    jsonResponse = await response.Content.ReadAsStringAsync();
                    return jsonResponse;
                    //do something with json response here                    
                }
                else
                {
                    return null;
                }

            }
            catch (Exception e)
            {
                string error = e.GetBaseException().ToString();
                //Could not connect to server
                return null;
            }
        }
    }

我收到以下回复

  
      
  • response {StatusCode:403,ReasonPhrase:'Forbidden',Version:1.1,Content:System.Net.Http.StreamContent,Headers:   {   x-csrf-token:必需   set-cookie:sap-usercontext = sap-client = 100;路径= /   的Set-Cookie:MYSAPSSO2 = AjQxMDMBABhTAFMARQBOAEcAVQBQAFQAQQAgACAAIAACAAYxADAAMAADABBHAFcAMQAgACAAIAAgACAABAAYMgAwADEANwAwADkAMAAxADIAMAAzADgABQAEAAAACAYAAlgACQACRQD%2fAPswgfgGCSqGSIb3DQEHAqCB6jCB5wIBATELMAkGBSsOAwIaBQAwCwYJKoZIhvcNAQcBMYHHMIHEAgEBMBkwDjEMMAoGA1UEAxMDR1cxAgcgFAMoIAMBMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xNzA5MDEyMDM4MTBaMCMGCSqGSIb3DQEJBDEWBBRSJQHrlPcSnxYjzSrqJ%2frOgo%2fg2TAJBgcqhkjOOAQDBC8wLQIUXjXws4bw63uLdWR%21NB9r9XUCD54CFQCH6y91A%21uKMzyfZEo7pvxjXys6zg%3D%3D;路径= /;域= .mindsetconsulting.com   set-cookie:SAP_SESSIONID_GW1_100 = Zvfe5ueHO1md7_ybPcLEcnem3m6PVRHnvP4KDkBCwEk%3d;路径= /   access-control-allow-credentials:true   access-control-allow-headers:*   access-control-allow-origin:* .google.com   access-control-allow-methods:*   内容长度:28   content-type:text / plain;字符集= utf-8的   System.Net.Http.HttpResponseMessage
  •   

1 个答案:

答案 0 :(得分:1)

我发现了这个问题。我必须收集cookie和csrf令牌,并在实际的POST方法中应用这些cookie。那很有效。

获取GET后的cookie

                    Uri uri = new Uri(_URI);
                    _responseCookies = cookies.GetCookies(uri).Cast<Cookie>();

然后将cookie添加到POST

        CookieContainer cookieContainer = new CookieContainer();
        foreach (var cookie in _responseCookies)
        {
            cookieContainer.Add(new Uri(_URI), cookie);
        }
HttpClientHandler handler = new HttpClientHandler() { CookieContainer = cookieContainer };