How to use two calls on the same session in flurl

Viewed 73

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

1 Answers

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>();
Related