I'm implementing JWT Auth with Xamarin forms. Now auth looks working from server side and I'm trying to test if it is working as expected on client side. My server app is running on local machine but emulator already configured to send traffic to my domain.
Here is my Xamarin.Forms Test method sending Request for testing:
async Task Test()
{
try
{
var token = await SecureStorage.GetAsync("access_token");
string url = "https://example.com:44330/account/testauth";
using (var httppClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(url),
Headers =
{
{ "Authorization", $"Bearer {token}" }
}
};
var response = await httppClient.SendAsync(request);
string respStr = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
//Do something
}
}
}
catch (Exception ex)
{
//handle exception
}
}
After sending a request I'm getting an error Failed to connect to example.com/52.202.22.6:44330.
What configuration could be missed considering that WebAuthenticator.AuthenticateAsync works fine for the same domain?
Related
im trying to send a HTTP POST request from xamarin forms app to a webservice API on ASP.NET MVC, However, when i do it, i get status code 500 back from the server. I suspect it has something to do with the values in sending to API but i have not been able to figure it out.
Anyhelp is much appeciated
here is the
WEB API CODE
public void LogInFromMobile([FromBody] List<Creds> detail)
{
......
}
here is the
XAMARIN-FORMS APP CODE
public async void Button_Clicked(object sender, EventArgs e)
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Creds cr = new Creds();
cr.username = user.Text;
cr.password = pass.Text;
List<Creds> cred = new List<Creds>();
cred.Add(cr);
string url = #"http://IPHERE/LoginWebService.asmx/LogInFromMobile";
string json = JsonConvert.SerializeObject(cred);
HttpContent content = new StringContent(json);
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
await DisplayAlert("Alert", "Success", "Ok");
return;
}
else
{
await DisplayAlert("Alert", "Error", "Ok");
return;
}
}
}
catch(Exception ex)
{
await DisplayAlert("", ex.Message, "ok");
}
}
Hi I applied AppPurchase on my app that is using xamarin forms and my app is sending fine the Google Receipt on my Server(azure).
But getting StatusCode: 400, BadRequest error when sending the Apple Receipt.
Here is my code:
public async Task<PurchaseResult> PurchaseAsync(AppleReceipt receipt)
{
switch (Device.RuntimePlatform)
{
case Device.iOS:
devicePlatform = "ios";
break;
case Device.Android:
devicePlatform = "android";
break;
}
client.DefaultRequestHeaders.Add("deviceplatform", devicePlatform);
client.DefaultRequestHeaders.Add("serviceid", serviceId);
InitializeApiClientUser(true);
client.BaseAddress = new Uri($"{Constants.ApiUrl}purchaseapple{codePrefix}{Constants.ApiKey}");
var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
HttpResponseMessage response = await client.PostAsJsonAsync(client.BaseAddress, receipt);
CocoSharpControlUI.DisplayAlert("RESPONSE", response.ToString());
client = new HttpClient();
return JsonConvert.DeserializeObject<PurchaseResult>(await response.Content.ReadAsStringAsync());
}
I have implemented the code for generating access token.I am able to get the token from default Token End Point Path(https://localhost:44312/token) when trying to get it from Postman.
However I want to implement Login Controller which internally should call the default token end point and send the response.
public async Task<IHttpActionResult> Login(UserModel userModel)
{
HttpResponseMessage response;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:44312/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("cache-control", "no-cache");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
userModel.grant_type = "password";
var parameters = new Dictionary<string, string> { { "username", userModel.UserName }, { "password", userModel.Password }, { "grant_type", "password" } };
var encodedContent = new FormUrlEncodedContent(parameters);
response = client.PostAsync("/token", encodedContent).Result;
}
return Ok(response);
}
I get an httpstatus OK response but not the access token. Any guidance in solving the issue would be helpful.
Hello i'm doing an xamarin.form application and i'm implementing the twitter login using oauth.
I have problem to get the request_token folowing the link:
https://dev.twitter.com/oauth/reference/post/oauth/request_token
using restsharp.portable for the request POST i arrive at this point:
public async void GetTwitterToken()
{
try
{
TwitterLogin tw = new TwitterLogin();
RestClient client = new RestClient("https://api.twitter.com");
RestRequest request = new RestRequest("/oauth/request_token", Method.POST);
client.Authenticator = OAuth1Authenticator.ForRequestToken(tw.oauth_consumer_key, tw.oauth_consumer_secret);
IRestResponse response = await client.Execute(request);
}
catch (Exception e)
{
}
}
Parameter "response" it's ok but i'don't know how to parse to get token (it's not json).
i have seen this example:
public void GetRequestToken()
{
var client = new RestClient("https://api.twitter.com"); // Note NO /1
client.Authenticator = OAuth1Authenticator.ForRequestToken(
_consumerKey,
_consumerSecret,
"http://markashleybell.com" // Value for the oauth_callback parameter
);
var request = new RestRequest("/oauth/request_token", Method.POST);
var response = client.Execute(request);
var qs = HttpUtility.ParseQueryString(response.Content);
_token = qs["oauth_token"];
_tokenSecret = qs["oauth_token_secret"];
}
But i don't have HttpUtility.ParseQueryString(response.Content) whith xamarin.form framework
I'm working on MediaFire Api for i'm using rest api for authenthecation when i use this url for in Chrome poster and fifefox poster using 'GET' request Response is coming and i implemneted the same trough code to get response but throwing an exception like
Specified value has invalid HTTP Header characters.
Parameter name: name.
requestUrl = https://www.mediafire.com/api/1.1/user/get_session_token.php? email=windowsphone654321#gmail.com&password=123456AaAa&application_id=42403&signature=506fbb1e62c51c20e50425022e3bca7dabfecca3&token_version=2
HttpClient httpClient = new HttpClient();
var res = await httpClient.GetStringAsync(requestUrl);
public async Task SendHttpClientRequest( Uri uri )
{
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync( uri );
response.EnsureSuccessStatusCode();
string responseBody = string.Empty;
responseBody = await response.Content.ReadAsStringAsync();
}
catch ( HttpRequestException e )
{
Debug.WriteLine( "\nException Message :{0} ", e.Message );
}
}