Question: Xamarin csrf-token missing or incorrect using HttpClient

Question

Xamarin csrf-token missing or incorrect using HttpClient

Answers 0
Added at 2017-01-03 22:01
Tags
Question

I'm trying to run a post request with my Xamarin app. My backend is a Django app which allows all cross origin:

CORS_ORIGIN_ALLOW_ALL = True

There is no problem when I try to POST, PUT, GET, PATCH, DELETE with my Angular2 app, but when I try with my Xamarin app, my backend returns this error:

csrf token missing or incorrect

My Xamarin c# code looks like that:

namespace Services
{
    public static class Authentication
    {
        public static async Task<string> Login(string email, string password)
        {
            var loginModel = new LoginModel() { email = email, password = password };
            Uri uri = new Uri(Environment.server_url + "rest-auth/login/");
            var json = JsonConvert.SerializeObject(loginModel);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = null;
            using (var client = new HttpClient())
            {
                response = await client.PostAsync(uri, content);
            }
            return await response.Content.ReadAsStringAsync();
        }
    }

    public class LoginModel
    {
        public LoginModel()
        {
        }
        public string email;
        public string password;

    }
}

As you can see, there is no csrf-token added to the header because a don't know how to get this token with Xamarin.

I've tried some random code like this one:

client.DefaultRequestHeaders.Add("x-csrf-token", "Fetch");

Or this one, with a random token just to see:

client.DefaultRequestHeaders.Add("x-csrf-token", "IYTN3eZvkah5vh4y0mEOzCHbbKPcutV4DiSKsbEnlgmuNkdu4jumYdaHYJqUT57n");

But as expected, it doesn't helps.

I've tried to get the token via a get request but the response doesn't contains any token.

Any idea ?

I'm using the last version of Xamarin Forms (2.3.3.175).

Answers to

Xamarin csrf-token missing or incorrect using HttpClient

Source Show
◀ Wstecz