0

I'm coding a Xamarin cross-platform mobile app. The server is a SpringMVC server which uses JWT Tokens to authenticate against each of the endpoints/webservices. So basically when I'm doing a request to a webservice for first time, before I need to hit a /authorize POST endpoint sending my email and password, the endpoint response will contain in the "Cookie" header an authenticaton token which comes as "AUTH_TOKEN={MD5-String}". Once I got the token I send the request to the endpoint, let's say /feed. But my problem is that I cannot figure out the way of setting the "Cookie" header in the C# HttpClient. I tried everything but the endpoing just keeps responding with the login screen html instead of the actual JSON response. I tried the same steps in Postman and other REST clients and It worked. So It means that I'm doing something wrong. Here's my code:

public class RestService : IRestService
{
    HttpClient client;
    HttpClientHandler handler;
    CookieContainer cookies;
    string authToken;

    public List<Feed> FeedItems { get; private set; }

    public RestService()
    {
        cookies = new CookieContainer();
        handler = new HttpClientHandler();
        handler.UseCookies = true; //Otherwise It'll not use the cookies container!!
        handler.CookieContainer = cookies;
        client = new HttpClient(handler);
        client.MaxResponseContentBufferSize = 256000;
    }

    public async Task<List<Role>> GetFeedDataAsync()
    {
        //Request credentials
        //Credentials validation
        var credentials = new HalliganCredential()
        {
            email = Constants.Username,
            password = Constants.Password
        };
        var jsonCredentials = JsonConvert.SerializeObject(credentials);
        var jsonCredentialsContent = new StringContent(jsonCredentials, Encoding.UTF8, "application/json");
        var authorizeUri = new Uri(Constants.AuthorizeEndpoint);
        var authorizeResponse = await client.PostAsync(authorizeUri, jsonCredentialsContent);
        if (authorizeResponse.IsSuccessStatusCode)
        {
            //If authentication went OK
            IEnumerable<Cookie> responseCookies = cookies.GetCookies(authorizeUri).Cast<Cookie>();
            foreach (Cookie cookie in responseCookies)
            {
                if (cookie.Name.Equals("AUTH-TOKEN"))
                {
                    authToken = cookie.Value;
                }
            }
        }
        else
        {
            //Authentication failed throw error
            throw new HttpRequestException("Authentication failed");
        }


        FeedItems = new List<Feed>();

        //Making the GET request
        var uri = new Uri(string.Format(Constants.FeedEnpoint, string.Empty));
        try
        {
            cookies.Add(uri, new Cookie("Cookie", string.Format("AUTH_TOKEN={0}", authToken)));
            client.DefaultRequestHeaders.Add("Cookie", string.Format("AUTH_TOKEN={0}", authToken));
            handler.CookieContainer.Add(uri, new Cookie("Cookie", string.Format("AUTH_TOKEN={0}", authToken)));

            var response = await client.GetAsync(uri);
            response.EnsureSuccessStatusCode();
            //Credentials validation
            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                FeedItems = JsonConvert.DeserializeObject<List<Feed>>(content);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(@"ERROR {0}", ex.Message);
        }


        return FeedItems;
    }
}

When I reach the line var content = await response.Content.ReadAsStringAsync(); the response is an HTML string instead of the actual JSON response.

I tried with several other key values for the header, although "Cookie" is the one that worked on Postman.

I tried with "Set-Cookie", "set-cookie", "Set-Cookie", setting the header as "AUTH_TOKEN". I tried all this convinations in different places like adding them in the cookie CookieContainer, in the handler CookieContainer and in the client.DefaultRequestHeaders.

I tried setting on and off the handler.UseCookies = true; //Otherwise It'll not use the cookies container!! line.

Any help will be welcome!

UPDATE

I tried with one of the suggested solutions but didn't work I tried either with UseCookies in true and false.

         //Making the GET request
        var baseAddress = new Uri("http://app.******.io");
        using (var handler = new HttpClientHandler { UseCookies = true })
        using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
        {
            var message = new HttpRequestMessage(HttpMethod.Get, "/api/v1/feed?api_key=sarasa");
            message.Headers.Add("Cookie", string.Format("AUTH_TOKEN={0}", authToken));
            message.Headers.Add("Cookie", string.Format("AUTH_TOKEN={0};", authToken));
            message.Headers.Add("Set-Cookie", string.Format("AUTH_TOKEN={0}", authToken));
            message.Headers.Add("AUTH_TOKEN", authToken);
            var result = await client.SendAsync(message);
            result.EnsureSuccessStatusCode();
            if (result.IsSuccessStatusCode)
            {
                var content = await result.Content.ReadAsStringAsync();
                FeedItems= JsonConvert.DeserializeObject<List<Feed>>(content);
            }
        }
        return FeedItems;

UPDATE

I tried with the another solution, same results.

var baseAddress = new Uri("http://app.*****.io");
            var cookieContainer = new CookieContainer();
            using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
            using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
            {
                cookieContainer.Add(baseAddress, new Cookie("Cookie", string.Format("AUTH_TOKEN={0}", authToken)));
                cookieContainer.Add(baseAddress, new Cookie("Set-Cookie", string.Format("AUTH_TOKEN={0}", authToken)));
                var result = client.GetAsync("/api/v1/roles?api_key=sarasa").Result;
                result.EnsureSuccessStatusCode();
                if (result.IsSuccessStatusCode)
                {
                    var content = await result.Content.ReadAsStringAsync();
                    RolesItems = JsonConvert.DeserializeObject<List<Role>>(content);
                }
            }

Is there an alternative to HttpClient?

4gus71n
  • 3,717
  • 3
  • 39
  • 66

1 Answers1

0

I finally could set the Cookie header parameter, but I change HttpClient by HttpWebRequest

Getting the Cookies

//Credentials validation
            var credentials = new CompanyCredential()
            {
                Email = Constants.Username,
                Password = Constants.Password
            };
            var jsonCredentials = JsonConvert.SerializeObject(credentials);
            var request = (HttpWebRequest) WebRequest.Create(new Uri(baseAddress, Constants.AuthorizeEndpoint));
            request.ContentType = "application/json";
            request.Method = "POST";
            var requestStream = request.GetRequestStreamAsync().Result;
            var streamWriter = new StreamWriter(requestStream);
            streamWriter.Write(jsonCredentials);
            streamWriter.Flush();
            try
            {
                HttpWebResponse response = (HttpWebResponse) request.GetResponseAsync().Result;
                if (response.StatusCode.Equals(HttpStatusCode.OK))
                {
                    authToken = response.Headers["Set-Cookie"];
                    tokenExpireDate = DateTime.ParseExact(response.Headers["Expires"], "yyyy-MM-dd HH:mm:ss,fff",
                                       System.Globalization.CultureInfo.InvariantCulture);
                }
                else
                {
                    //Authentication failed throw error
                    throw new HttpRequestException("Authentication failed");
                }
            } catch (Exception e)
            {
                Debug.WriteLine(string.Format("Warning: {0}", e.Message));
            }

Setting the Cookies

var request = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress, endpoint));
            SetHeaders(request);
            if (string.IsNullOrEmpty(authToken))
            {
                throw new AuthTokenNullException();
            }
            request.Headers["Cookie"] = authToken;
            request.Method = "GET";
            HttpWebResponse response = request.GetResponseAsync().Result as HttpWebResponse;
            if (!response.StatusCode.Equals(HttpStatusCode.OK))
            {
                throw new HttpRequestException(string.Format("Warning expected response as 200 and got {0}", Convert.ToString(response.StatusCode)));
            }
            var reader = new StreamReader(response.GetResponseStream());
            string stringResponse = reader.ReadToEnd();
            return JsonConvert.DeserializeObject<T>(stringResponse);
4gus71n
  • 3,717
  • 3
  • 39
  • 66