1

I want to use GetAsync to get a token then to use that token in a POST function. Both Get and Post should be made on same session.

Here is the GET function:

 var result = await SA_BaseUrl
            .AppendPathSegments("ProdOrderConfSet")
            .WithBasicAuth("UserName", "Password")
            .WithHeader("Accept","application/json")
            .WithHeader("X_CSRF_Token", "fetch")
            .GetAsync();

        IReadOnlyNameValueList<string> headers = result.Headers;
        string X_CSRF_Token = headers.FirstOrDefault(h => h.Name == "x-csrf-token").Value;

And Post function:

 var result2 = await SA_BaseUrl
                .AppendPathSegments("ProdOrderConfSet")   
                .WithBasicAuth("UserName", "Password")
                .WithHeader("Accept","application/json")
                .WithHeader("Content-Type", "application/json")
                .WithHeader("X_CSRF_Token", X_CSRF_Token)
                .PostJsonAsync(workStep)
                .ReceiveJson<DANTESAP_ProdWorkStep>();

Running the above code, I am getting:

403 Forbidden, CSRF token validation failed

How can I run the two functions on the same session?

Unfortunately, there is no documentation for the service I am trying to reach. But when I use Postman, it works without any problem. I do not know what is missing (or wrong) in my C# code.

Here is the Get function in order to get the token: Get csrf token

And here is the POST function that uses the extracted csrf token from the GET function: POST using the extracted csrf token

ouflak
  • 2,458
  • 10
  • 44
  • 49
H. Saffour
  • 57
  • 1
  • 1
  • 8
  • What service are you trying to interact with here? Can you link to their documentation? Without that, this question is impossible to answer because there's no standard for how CSRF tokens must be transmitted. – Todd Menier Nov 04 '21 at 00:57

1 Answers1

1

Get the cookies and re-use them:

 var result = await SA_BaseUrl
            .AppendPathSegments("ProdOrderConfSet")
            .WithBasicAuth("UserName", "Password")
            .WithHeader("Accept","application/json")
            .WithHeader("X_CSRF_Token", "fetch")
            .WithCookies(out var jar)
            .GetAsync();

...

var result2 = await SA_BaseUrl
                    .AppendPathSegments("ProdOrderConfSet")   
                    .WithBasicAuth("UserName", "Password")
                    .WithHeader("Accept","application/json")
                    .WithHeader("Content-Type", "application/json")
                    .WithHeader("X_CSRF_Token", X_CSRF_Token)
                    .WithCookies(jar)
                    .PostJsonAsync(workStep)
                .ReceiveJson<DANTESAP_ProdWorkStep>();
ouflak
  • 2,458
  • 10
  • 44
  • 49
H. Saffour
  • 57
  • 1
  • 1
  • 8