DEV Community

Tiago Monteiro
Tiago Monteiro

Posted on • Edited on

XSRF-TOKEN

How is it possible to make http request for login in C#?
When I try to make the http request with the POST protocol I cannot obtain the XSRF-TOKEN.
Can anyone help me?

    public class NetworkService : INetworkService
    {
        private readonly HttpClient _webClient;
        private readonly CookieContainer _cookieManager;
        private readonly HttpClientHandler _webHandler;

        public NetworkService(IHttpClientFactory clientFactory)
        {
            _cookieManager = new CookieContainer();
            _webHandler = new HttpClientHandler()
            {
                SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
                MaxAutomaticRedirections = 10,
                UseCookies = true,
                CookieContainer = _cookieManager,
                AllowAutoRedirect = true,
                CheckCertificateRevocationList = true
            };

            _webClient = clientFactory.CreateClient("NetworkServiceClient");
            _webClient.BaseAddress = new Uri("[URL]https://example.com/api[/URL]");
            _webClient.DefaultRequestHeaders.Accept.Clear();
            _webClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public async Task<string> CallApi1(string userId, string accessCode)
        {
            var endpoint = new Uri(_webClient.BaseAddress, "/api1/login");
            var loginInfo = new { userName = username, userPassword = password };
            var contentBody = new StringContent(JsonConvert.SerializeObject(loginInfo), Encoding.UTF8, "application/json");

            HttpResponseMessage result = await _webClient.PostAsync(endpoint, contentBody);
            if (!result.IsSuccessStatusCode)
            {
                Console.WriteLine($"API1 call failed with status code: {result.StatusCode}");
                return null;
            }

            var token = ExtractCookie("XSRF-TOKEN");
            return token;
        }
    }
Enter fullscreen mode Exit fullscreen mode

The code is functioning properly and returns a 200 response, however, I’m not receiving the XSRF Cookie. When I perform the HTTP request in Postman, I do receive the XSRF Cookie. But in C#, it’s not being received.

Top comments (0)