XSRF-Token

DataKnight11

Member
Joined
Apr 18, 2024
Messages
18
Location
Portugal
Programming Experience
Beginner
Hello community,

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?



var loginData = new { userName = username, systemCode = password };
var requestBody = new StringContent(JsonConvert.SerializeObject(loginData), Encoding.UTF8, "application/json");



HttpResponseMessage response = await _httpClient.PostAsync(url, requestBody);
Console.WriteLine($"Status Code: {response.StatusCode}");
LogResponseDetails(response);
 
XSRFTOKEN:
public class WebService : IWebService

{

    private readonly HttpClient _client;



    public WebService()

    {

        _client = new HttpClient

        {

            BaseAddress = new Uri("Example Domain")

        };

        SetupHttpClient();

    }



    private void SetupHttpClient()

    {

        _client.DefaultRequestHeaders.Accept.Clear();

        _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        _client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; App/1.0)");

    }



    public async Task<string> LoginAsync(string user, string secret)

    {

        var endpoint = "/login";

        var credentials = new { userName = "UserPlaceholder", systemCode = "SecretPlaceholder" };

        var content = new StringContent(JsonConvert.SerializeObject(credentials), Encoding.UTF8, "application/json");



        HttpResponseMessage response = await _client.PostAsync(endpoint, content);

        if (!response.IsSuccessStatusCode)

        {

            Console.WriteLine($"Login failed with status code: {response.StatusCode}. Response: {await response.Content.ReadAsStringAsync()}");

            return null;

        }



        var cookies = response.Headers.TryGetValues("Set-Cookie", out var values) ? values.ToArray() : new string[0];

        foreach (var cookie in cookies)

        {

            Console.WriteLine($"Set-Cookie: {cookie}");

        }



        var xsrfToken = cookies.SelectMany(c => c.Split(';'))

                               .FirstOrDefault(s => s.Trim().StartsWith("XSRF-TOKEN="))

                               ?.Split('=')[1];



        return xsrfToken;

    }

}

The error persists and I don't understand why. I analyzed the documentation sent but it still doesn't work.
 
If you share the headers sent by Postman, and headers sent by your program, we could provide another pair of eyes to try to spot the difference between them. (We believe you that the responses received by Postman is different from the responses received.)
 
If you share the headers sent by Postman, and headers sent by your program, we could provide another pair of eyes to try to spot the difference between them. (We believe you that the responses received by Postman is different from the responses received.)

Responses

Postman Response: 26 Headers
x-envoy-upstream-service-time 389
server CloudWAF
x-trace-enable false
x-request-id qwjhkjqwhk12829788euw12021237763
x-frame-options SAMEORIGIN
Connection keep-alive, keep-alive
lubanops-gtrace-id l-23837-2893820910928-2879371
x-download-options noopen
x-sampling true
x-parent-id 178293789382721912
x-sysprops-sampling 178293789382721912
x-autotask-sampling 1
date Mon, 22 Apr 2024 15:54:15 GMT
strict-transport-security max-age=99990000; includeSubDomains
lubanops-nenv-id 990
content-security-policy default-src https: data: blob: ws: 'self' 'unsafe-inline' 'unsafe-eval'
x-trace-id 182930123074829739
x-content-type-options nosniff
x-xss-protection 1; mode=block
x-span-id 178293789382721912
xsrf-token iquwieuqow099182309182391uiooiyqwoqyiueagsghdsaggajs172121
set-cookie iquwieuqow099182309182391uiooiyqwoqyiueagsghdsaggajs172121
content-type application/json;charset=UTF-8
Content-Length 68
keep-alive timeout=20
upcase-conversion-headers accessSession


Postman Response: 21 Headers
StatusCode: 200, ReasonPhrase: 'OK'
Server: product
Server: only
Date: Mon, 22 Apr 2024 16:07:35 GMT
Connection: keep-alive
x-envoy-upstream-service-time: 8
x-trace-enable: false
X-Request-ID: h182789371aasdaghsaq7w7621876812
X-Frame-Options: SAMEORIGIN
lubanops-gtrace-id: l-89232-2712673821722-2367472
x-download-options: noopen
x-sampling: true
x-parent-id: 128783971892396727
x-sysprops-sampling: 128783971892396727
x-autotask-sampling: 1
Strict-Transport-Security: max-age=27839802; includeSubDomains
lubanops-nenv-id: 829
Content-Security-Policy: default-src https: data: blob: ws: 'self' 'unsafe-inline' 'unsafe-eval'
x-trace-id: 989102923839201292
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
x-span-id: 1287839718923967271
Set-Cookie: JSESSIONID=87912783781AJGHJ8281HJDJHFD81282; Path=/; HttpOnly
upcase-conversion-headers: accessSession
Content-Type: application/json;charset=UTF-8
Content-Length: 130
 
Those are responses that you are getting back. I was asking about what did Postman send? What did you send?
 
Show us the headers that are sent. There is an obvious difference in the way the server is responding. A server is not psychic. It can only act on the data sent it. So what data is being sent to it by Postman that is different from the data that you are sending using the HttpClient.
 
That is private information, i can't simple display here, what i can tell you is that the URL is the same and the username and password in the body is equal too. The request i gave to you is parsing the username and password in the body and is applying the the exact same url in C#.
 
Okay, let try a different tack. As I recall, current versions of Postman allow you to tell it to generate C# code that mimics what it does for that particular session. Tell it to generate the code, and then run it. If that generated code succeeds, then compare the generated code with your code.

 
Last edited:
Okay, let try a different tack. As I recall, current versions of Postman allow you to tell it to generate C# code that mimics what it does for that particular session. Tell it to generate the code, and then run it. If that generated code succeeds, then compare the generated code with your code.


I already did that and the problem persists.
Take a look.

Postman
Postman:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://example.api");
var content = new StringContent("{\r\n    \"userName\": \"username\",\r\n    \"password\": \"password\"\r\n}\r\n\r\n", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());


C# Solution
C$ Code:
        [FunctionName("TimerTriggerFunction")]
        public async Task Run([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"TimerTriggerFunction executed at: {DateTime.Now}");

            var token = await _webservice.AuthenticateAsync(Constants.APIUser, Constants.APIPassword);
            if (string.IsNullOrEmpty(token))
            {
                log.LogError("Failed to authenticate.");
                return;
            }

            var data = await _webservice.GetDataAsync(token);
            if (data != null)
            {
                log.LogInformation($"Data fetched successfully: {data}");
            }
            else
            {
                log.LogError("Failed to fetch data.");
            }
 
"The problem persists" meaning that the Postman generated code also fails?
 
*sigh* But does that generated code work?

As I said, take the generated code and run it. Does it work? Only if it works, then compare with your code. You are trying to skip the step of testing the generated code and going straight to comparing with your code in post #24.
 
*sigh* But does that generated code work?

As I said, take the generated code and run it. Does it work? Only if it works, then compare with your code. You are trying to skip the step of testing the generated code and going straight to comparing with your code in post #24.

Yes, as i told you, in both situations, the code snip that I take from postman and the code I have in c#, both run with 200 response but don't give the xsrf token. Only when i execute the postman application.
 
Congratulations! What was the missing ingredient?
 

Latest posts

Back
Top Bottom