i'm trying to access a WebAPI which is using ValidateAntiForgeryToken. My WebAPI Method is this (a simple one), which is inside a User Controller (just for a test):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Test(String field)
{
String result = String.Empty;
if (ModelState.IsValid)
{
HtmlSanitizer sanitizer = new HtmlSanitizer();
try
{
result = sanitizer.Sanitize(field);
}
catch (Exception ex)
{
result = ex.Message;
throw;
}
}
return Json(result);
}
With Ajax, i can access it with ease:
$.ajax({
url: '/User/Test',
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: {
field: self.textField(),
__RequestVerificationToken: $("input[name='__RequestVerificationToken']").val(),
},
success: function(e) {
self.textField(e)
self.divField(e);
},
error: function(e) {
console.log(e.error());
},
});
But, until now, i can't access this webapi with httpclient on xamarin. This is my code:
private async void DoTestWebApi()
{
try
{
HttpClient clientPage = new HttpClient()
{
BaseAddress = new Uri("https://localhost:44356/user")
};
var pageWithToken = await clientPage.GetAsync(clientPage.BaseAddress);
String verificationToken = GetVerificationToken(await pageWithToken.Content.ReadAsStringAsync());
HttpClient client = new HttpClient()
{
BaseAddress = new Uri("https://localhost:44356/user/test/")
};
HttpRequestMessage message = new HttpRequestMessage()
{
RequestUri = new Uri("https://localhost:44356/user/test/"),
Method = HttpMethod.Post
};
message.Headers.Add("__RequestVerificationToken", verificationToken);
String field = "teste";
//StringContent content = new StringContent("field=test", Encoding.UTF8, "application/x-www-form-urlencoded");
StringContent content = new StringContent("__RequestVerificationToken=" + verificationToken + ",field=test", Encoding.UTF8, "application/x-www-form-urlencoded");
// this doesn't work
//client.DefaultRequestHeaders.Add("__RequestVerificationToken", verificationToken);
var response2 = await client.SendAsync(message);
if (response2.IsSuccessStatusCode)
{
var t = response2.Content.ReadAsStringAsync();
if (true)
{
// just to check if t has value
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
Honestly, i don't know what else i could do to pass my anti forgery token inside the message. It works perfectly in ajax, i pass it inside the data content, but in xamarin it doesn't work. All the code is executed inside the same localhost. If i remove the [ValidateAntiForgeryToken], it works.
What am i missing?
Edit:
Ok, so now i'm sending with cookies, but is not hitting the method again. This is my update:
HttpClient clientPage = new HttpClient()
{
BaseAddress = new Uri("https://localhost:44356/user")
};
var pageWithToken = await clientPage.GetAsync(clientPage.BaseAddress);
String verificationToken = GetVerificationToken(await pageWithToken.Content.ReadAsStringAsync());
List<KeyValuePair<String, String>> cookiesInfo = new List<KeyValuePair<String, String>>();
foreach (var item in pageWithToken.Headers)
{
cookiesInfo.Add(new KeyValuePair<String, String>(item.Key, item.Value.ToString()));
}
cookiesInfo.Add(new KeyValuePair<string, string>("field", "value"));
cookiesInfo.Add(new KeyValuePair<string, string>("__RequestVerificationToken", verificationToken));
CookieContainer cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
{
using (var client = new HttpClient(handler) { BaseAddress = new Uri("https://localhost:44356/user") })
{
var content = new FormUrlEncodedContent(cookiesInfo);
cookieContainer.Add(client.BaseAddress, new Cookie("__RequestVerificationToken", verificationToken));
foreach (var item in cookiesInfo)
{
cookieContainer.Add(client.BaseAddress, new Cookie(item.Key, item.Value));
}
var result = client.PostAsync(new Uri("https://localhost:44356/user/test"), content).Result;
result.EnsureSuccessStatusCode();
}
};
This is driving me nuts... Ok the test is in localhost but soon this app will be in Azure, and this is a pre-requisite...
Edit: GetVerificationToken Method:
private string GetVerificationToken(String verificationToken)
{
if (verificationToken != null && verificationToken.Length > 0)
{
verificationToken = verificationToken.Substring(verificationToken.IndexOf("__RequestVerificationToken"));
verificationToken = verificationToken.Substring(verificationToken.IndexOf("value=\"") + 7);
verificationToken = verificationToken.Substring(0, verificationToken.IndexOf("\""));
}
return verificationToken;
}