Getting Bad Request when requesting JWT in web API from Xamarin Forms

Multi tool use
Getting Bad Request when requesting JWT in web API from Xamarin Forms
So I made a web API that authenticates with JSON Web Tokens, however, I haven't been able to authenticate using the HttpClient from my xamarin forms application. The odd thing is that I can connect without any problem on a console application that I made for testing, and both the console application and the xamarin forms app use almost exactly the same code.
The code in the console app is like this:
public static async Task<AutenticacionModel> PostCredentialsAsync(string UserName, string Password)
{
HttpClient cliente = new HttpClient();
cliente.BaseAddress = new Uri("http://172.25.1.53:9891");
HttpResponseMessage response = new HttpResponseMessage();
string _result = String.Empty;
try
{
string Path = cliente.BaseAddress + "oauth/secreto";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Path);
string autenticacion = "username=" + UserName + "&password=" + Password + "&grant_type=password";
request.Content = new StringContent(autenticacion, Encoding.UTF8, "application/x-www-form-urlencoded");
response = await cliente.SendAsync(request);
response.EnsureSuccessStatusCode();
_result = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
// something to do
}
return response.Content != null ? JsonConvert.DeserializeObject<AutenticacionModel>(_result) : new AutenticacionModel();
}
And the code in the Xamarin Forms:
public async Task<AutenticacionDTO> GetUsuario(string email, string clave)
{
string JSONAutenticacion;
HttpResponseMessage response = new HttpResponseMessage();
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(GlobalSetting.UrlWebApi);
string Path = client.BaseAddress + "oauth/secreto";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Path);
string autenticacion = "username=" + email + "&password=" + clave + "&grant_type=password";
request.Content = new StringContent(autenticacion, Encoding.UTF8, "application/x-www-form-urlencoded");
response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
JSONAutenticacion = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
string sss = ex.ToString();
return null;
}
return response.Content != null ? JsonConvert.DeserializeObject<AutenticacionDTO>(JSONAutenticacion) : new AutenticacionDTO();
}
When I use postman to connect to the web API that I have hosted in my local IIS, there's no problem, same with the console application. But whenever I try to connect with the Xamarin Forms App I get a 400 Bad Request response.
The code that makes the Jwt work goes like this:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = "*";
context.Response.Headers.Add("Access-Control-Allow-Origin", new { allowedOrigin });
Seguridad _Seguridad = new fovissste.bll.Seguridad();
LoginDTO Usuario = _Seguridad.Login(context.UserName, context.Password).FirstOrDefault();
if (Usuario == null)
{
context.SetError("invalid_grant", "Usuario o contraseña incorrectos");
return;
}
ClaimsIdentity oauthIdentity = new ClaimsIdentity(new ApplicationUser(context.UserName, "JWT"), new { new Claim(ClaimTypes.Role, "Publico") });
var ticket = await Task.Run(() => new AuthenticationTicket(oauthIdentity, null));
context.Validated(ticket);
}
Can anybody help? Is this an issue with Xamarin Forms? I truly require some comments because I honestly can't see what I'm missing. I've read other posts in this site that suggest that it can be an issue of enabling remote requests on IIS or a CORS issue but I think that's handled in this line: context.Response.Headers.Add("Access-Control-Allow-Origin", new { allowedOrigin });
context.Response.Headers.Add("Access-Control-Allow-Origin", new { allowedOrigin });
@GeraldVersluis I had the same idea, but I couldnt configure fiddler to capture my requests, at least I put a filter that indicates "Show only the following hosts" : localhost:9891; but the sessions aren't captured in fiddler
– gerardo flores
Jul 3 at 18:03
Are you running from an emulator or device? In case of a device you should set the device's proxy to your machine where Fiddler is running. On an emulator it normally should just work unless you're using HTTPS
– Gerald Versluis
Jul 3 at 18:06
@GeraldVersluis I'm running from device. Thank you I'll research how to set the proxy in the Android
– gerardo flores
Jul 3 at 18:54
However, it's working now. I don't know exactly what I changed, I simply copied/pasted the code from the console application. Could it have been network related?
– gerardo flores
Jul 3 at 18:55
1 Answer
1
Try the following code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://172.25.1.53:9891");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string autenticacion = "?username=" + email + "&password=" + clave + "&grant_type=password";
HttpResponseMessage response = await client.PostAsync(client.BaseAddress + "oauth/secreto", new StringContent(autenticacion, Encoding.UTF8, "application/x-www-form-urlencoded"));
response.EnsureSuccessStatusCode();
string JSONAutenticacion = await response.Content.ReadAsStringAsync();
}
What is the value of Path
after this line?
Path
string Path = client.BaseAddress + "oauth/secreto";
Also try to add this line before using (var client...
:
using (var client...
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
Changed
HttpResponseMessage response = await client.PostAsync(client.BaseAddress + autenticacion, new StringContent(autenticacion));
to
HttpResponseMessage response = await client.PostAsync(client.BaseAddress + "oauth/secreto", new StringContent(autenticacion, Encoding.UTF8, "application/x-www-form-urlencoded"));
didn't work. I must send the request as "application/x-www-form-urlencoded"
– gerardo flores
Jul 3 at 18:04
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Strange, all code seems the same. Try using a tool like Fiddler or Charles to see what is going over the line in each case. That might help figuring out what is going on.
– Gerald Versluis
Jul 3 at 6:21