C#:即使在使用httpclient发送CSRF令牌后也获得403 [英] C#: Getting 403 even after sending CSRF token using httpclient

查看:129
本文介绍了C#:即使在使用httpclient发送CSRF令牌后也获得403的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从我的 UWP 应用中将有效负载发布到我们的后端系统.为此,我首先要执行GET来获取CSRF令牌,然后将其添加到POST请求的标头中.发布时,我仍然收到403 Forbidden错误.

I am trying to post a payload to our backend system from my UWP app. For which I am first doing a GET to fetch the CSRF token and then adding that to the header of the POST request. While posting, I am still getting the 403 Forbidden error.

我通过执行单独的GET和POST请求并将从GET获取的CSRF令牌提供给POST标头,来与"Insomnia" REST客户端进行交叉测试.

I am cross-testing this with 'Insomnia' REST client by doing a separate GET and POST requests and feeding the CSRF token fetched from the GET to the POST header and it is working just fine.

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

I am new to C#, so please excuse the bad coding standards.

获取令牌

    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 ==缓存控制:无存储,无缓存sap-metadata-last-modified:Fri,01 Sep 2017 10:57:07 GMT数据服务版本:2.0set-cookie:sap-usercontext = sap-client = 100;路径=/,MYSAPSSO2 = AjQxMDMBABhTAFMARQBOAEcAVQBQAFQAQQAgACAAIAACAAYxADAAMAADABBHAFcAMQAgACAAIAAgACAABAAYMgAwADEANwAwADkAMAAxADIAMAA0ADkABQAEAAAACAYAAlgACQACRQD%2fAPswgfgGCSqGSIb3DQEHAqCB6jCB5wIBATELMAkGBSsOAwIaBQAwCwYJKoZIhvcNAQcBMYHHMIHEAgEBMBkwDjEMMAoGA1UEAxMDR1cxAgcgFAMoIAMBMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xNzA5MDEyMDQ5MzhaMCMGCSqGSIb3DQEJBDEWBBRP7sl8St9p53T9Sfu58sTb3jTNFjAJBgcqhkjOOAQDBC8wLQIVALIiQKECoPjhBihxA7OXoDOEGy3YAhQroXwahnTKR0A7du7u5zwj1Q0cgg%3D%3D;路径=/;domain = .mindsetconsulting.com,SAP_SESSIONID_GW1_100 = u1BKLug0BNWYM0-zg_JWTBEihxmPVxHnvTMKDkBCwEk%3d;路径=/访问控制允许凭证:true访问控制允许标题:*access-control-allow-origin:* .google.com访问控制允许方法:*} 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;
            }
        }
    }

我收到以下答复

  • 响应{状态代码:403,原因短语:禁止",版本:1.1,内容:System.Net.Http.StreamContent,标头:{x-csrf-token:必填set-cookie:sap-usercontext = sap-client = 100;路径=/的Set-Cookie:MYSAPSSO2 = AjQxMDMBABhTAFMARQBOAEcAVQBQAFQAQQAgACAAIAACAAYxADAAMAADABBHAFcAMQAgACAAIAAgACAABAAYMgAwADEANwAwADkAMAAxADIAMAAzADgABQAEAAAACAYAAlgACQACRQD%2fAPswgfgGCSqGSIb3DQEHAqCB6jCB5wIBATELMAkGBSsOAwIaBQAwCwYJKoZIhvcNAQcBMYHHMIHEAgEBMBkwDjEMMAoGA1UEAxMDR1cxAgcgFAMoIAMBMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xNzA5MDEyMDM4MTBaMCMGCSqGSIb3DQEJBDEWBBRSJQHrlPcSnxYjzSrqJ%2frOgo%2fg2TAJBgcqhkjOOAQDBC8wLQIUXjXws4bw63uLdWR%21NB9r9XUCD54CFQCH6y91A%21uKMzyfZEo7pvxjXys6zg%3D%3D;路径=/;domain = .mindsetconsulting.comset-cookie:SAP_SESSIONID_GW1_100 = Zvfe5ueHO1md7_ybPcLEcnem3m6PVRHnvP4KDkBCwEk%3d;路径=/访问控制允许凭证:true访问控制允许标题:*access-control-allow-origin:* .google.com访问控制允许方法:*内容长度:28内容类型:文本/纯文本;字符集= utf-8}} System.Net.Http.HttpResponseMessage

推荐答案

我发现了问题.我必须将cookie连同csrf令牌一起收集,并在实际的POST方法中应用这些cookie.那行得通.

I found the issue. I had to collect the cookies along with the csrf token and apply those cookies in the actual POST method. That worked.

在GET之后获取cookie

Getting the cookies after the GET

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

然后将cookie添加到POST

And then adding the cookies to the POST

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

这篇关于C#:即使在使用httpclient发送CSRF令牌后也获得403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆