xamarin.forms ,Foursqaure api response is not displaying but works in postman and foursqaure site after providing api key ?where im wrong - api

private async Task GetresultAsync()
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://api.foursquare.com/v3/places/search?ll=15.3494005,75.142583&query=shops&fields=geocodes,categories,name,hours,fsq_id,price,rating,stats,location"),
Headers =
{
{ "Accept", "application/json" },
{ "Authorization", "fsq322aNlTt3+PuRKw5js/ndngtry/XxNV0Q70yzKjDTQn0="
},
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Debug.WriteLine(body);
}
Please any suggestions? I'm very new to xamarin and I'm getting data in postman but not getting result in xamarin using
RESTCLIENT OR HTTPCLIENT for( foursqaure places api for v3) where am I wrong?

Related

Asp.net core web api put request returning error

The following is working in Postman but not when a request is sent via Xamarin, is there something obvious that I am missing. My get request is working fine but I can't seem to 'put' data.
Core Api
[HttpPut("{id}")]
public async Task<IActionResult> PutTickets(int id, [FromBody] WorkTickets workTickets)
{
if (id != workTickets.Id)
{
return BadRequest();
}
_context.Entry(workTickets).State = EntityState.Modified;
await _context.SaveChangesAsync();
return NoContent();
}
Data
private async void UploadLocalTickets()
{
try
{
WorkTickets workTickets = new WorkTickets()
{
Id = 4426,
ActualWorkActivity = "test",
};
HttpClient client = new HttpClient();
await DisplayAlert("Got Here", "Before Cloud", "OK");
var json = JsonConvert.SerializeObject(workTickets);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var result = await client.PutAsync("https://xxxx.azurewebsites.net/api/apitickets/" + 4426, content);
await DisplayAlert("Got Here", result.StatusCode.ToString(), "OK");
}
catch
{
await DisplayAlert("Error", "Caught", "OK");
}
}
Error is internal server error

Forward request made to Azure function to another endpoint

I need to forward a HttpRequest made to an Azure function (through proxies.json) to a different endpoint. The request needs to be forwarded with query strings and headers intact. I need to modify the response body before sending it back to the original caller.
Proxies.json
"Transactions.BatchImport.Settlements": {
"matchCondition": {
"methods": [ "GET" ],
"route": "/transactions/v1/getsettlementsbyid/{batchId}"
},
"backendUri": "http://localhost/api/storebox/settlements/{batchId}"
},
Psudocode of desired functionality
[FunctionName(nameof(GetStoreboxSettlements))]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "GET", Route = "storebox/settlements/{batchId}")]
HttpRequest request, string batchId)
{
var response = ForwardRequest(request, $"www.anotherEndpoint.com/{batchId}");
response.Body = TransformBody(response.Body);
return new OkObjectResult(response);
}
Alternative solutions are welcome.
If anyone is interested, this is how I solved the problem:
Proxies.json
"Transactions.BatchImport.Settlements": {
"matchCondition": {
"methods": [ "GET" ],
"route": "/transactions/v1/getsettlementsbyid/{batchId}"
},
"backendUri": "http://localhost/api/v1/settlements/{batchId}"
},
Function code
[FunctionName(nameof(GetStoreboxSettlementsProxy))]
public async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "GET", Route = "v1/settlements/{batchId?}")]
HttpRequest request)
{
var baseUri = _environment.Get(Constants.Api.Endpoint);
var requestUri = new UriBuilder(baseUri)
{
Path = $"{request.Path}",
Query = request.QueryString.Value,
}.Uri;
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.Headers.Authorization = AuthenticationHeaderValue.Parse(request.Headers["Authorization"]);
httpRequestMessage.RequestUri = requestUri;
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);
try
{
response = await _httpClient.SendAsync(httpRequestMessage);
response.EnsureSuccessStatusCode();
var json = response.Content.ReadAsStringAsync().Result;
var storeBoxTransactionData = JsonConvert.DeserializeObject<StoreBoxTransactionData>(json);
if (storeBoxTransactionData.TotalSize > 0)
{
//Transform storebox settlement data
var transformedStoreBoxData = _processStoreBoxSettlementService.Process(storeBoxTransactionData);
response.Content = new StringContent(JsonConvert.SerializeObject(transformedStoreBoxData), Encoding.UTF8, "application/json");
return response;
}
}
catch (Exception e)
{
_logger.LogError($"Failed to get settlements {e}");
}
return response;
}

Find out Cookie in Flutter

I use Flutter to make a HTTP-Post to a website to login. If I only send the data to login, the response of the HTTP-Post shows, that I`m not logged in. I tried to find out the cookie the Website sends. I did it with the software Postman. If I add the same cookie, I got at Postman, the HTTP-Post with Flutter works and the response shows, that Im logged in. After a while, the value of the cookie switched and the HTTP-Post via Flutter doent work.
How can I get the information about the actual value of the cookie from the website?
The code looks like this:
Future initiate() async {
ByteData bytes = await rootBundle.load('assets/Certificates/test.crt');
SecurityContext clientContext = new SecurityContext()
..setTrustedCertificatesBytes(bytes.buffer.asUint8List());
var client = new HttpClient(context: clientContext);
IOClient ioClient = new IOClient(client);
var form = <String, String>{
'user':'testuser',
'pass':'testpass',
'logintype':'login',
'pid':'128',
'submit':'Anmelden',
'tx_felogin_pi1[noredirect]':'0'
};
print(form);
var ris = await ioClient.get("https://www.test.de/login");
print(ris.headers);
http.Response res = await ioClient.post("https://www.test.de/login",body:form, headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded", "Cookie": "fe_typo_user=12345"}, encoding: Encoding.getByName("utf-8"));
ioClient.close();
client.close();
print(res.body.length);
return res.body.contains("logout");
}
This is how I get cookie:
static Future<String> login(String username, String password) async {
var url = _session._getUrl('/auth/login');
var map = new Map<String, dynamic>();
map['username'] = username;
map['password'] = password;
final response = await http.post(url, body: map);
var jsonResponse = convert.jsonDecode(response.body);
var cookies = response.headers['set-cookie'];
if (cookies != null) {
var csrf = _session._getCSRF(cookies);
LocalStorage.instance.setString('CSRF', csrf);
print(csrf);
}
return jsonResponse['msg'];
}

How to get Location in Response Header use HttpResponseMessage in windows phone

I want get Location in Response Header but i can't see this in Response. How to get this. Please help me.
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
FormUrlEncodedContent postData = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("background","1"),
new KeyValuePair<string,string>("line1","Content1"),
new KeyValuePair<string,string>("line2","Content2")
});
HttpResponseMessage response = await client.PostAsync("URL", postData);
string rp = await response.Content.ReadAsStringAsync();

Microsoft Owin UseJwt

I am having a difficult time using UseJwtBearerAuthentication Method, I am using Microsoft Azure ACS to obtain a token (using a service identity). The JWT token returns fine to my test program. In the test program the token is sent to a MVC WebAPI 2. (The WAAD authentication works fine when token is obtained from Azure Active Directory)
public partial class Startup
{
private const string Issuer = "https://bluebeam-us-east.accesscontrol.windows.net/";
public void ConfigureAuth(IAppBuilder app)
{
string CertificateThumbprint = "99B25E3E31FCD24F669C260A743FBD508D21FE30";
var audience = ConfigurationManager.AppSettings["ida:Audience"];
app.UseErrorPage(new ErrorPageOptions()
{
ShowEnvironment = true,
ShowCookies = false,
ShowSourceCode = true,
});
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = audience ,
Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
});
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new X509CertificateSecurityTokenProvider(Issuer, X509CertificateHelper.FindByThumbprint(StoreName.My,StoreLocation.LocalMachine,CertificateThumbprint).First())
},
});
}
The Code to get Token from ACS is as follows:
private async void GetJwtToken()
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(IdP.Authority);
var content = new FormUrlEncodedContent(new Dictionary<String, String>
{
{"grant_type","client_credentials"},
{"client_id", IdP.UserName},
{"client_secret", IdP.Password},
{"scope", IdP.Resource}
});
var response = await client.PostAsync("v2/OAuth2-13", content);
response.EnsureSuccessStatusCode();
var jwtdata = await response.Content.ReadAsStringAsync();
var jwt = JsonConvert.DeserializeObject<Token>(jwtdata);
AccessToken = jwt.access_token;
TokenType = jwt.token_type;
long expire;
if (long.TryParse(jwt.expires_in, out expire))
{
ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(expire);
}
Authorization = AccessToken;
}
}
catch (HttpRequestException re)
{
Response = re.Message;
}
}
The code to request a Resource (WebAPI):
private async void WebApiRequestCall()
{
try
{
ConfigureSsl();
using (var client = new HttpClient())
{
client.BaseAddress = _baseAddress;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (!String.IsNullOrWhiteSpace(Authorization))
client.DefaultRequestHeaders.Add("Authorization", Authorization);
var response = await client.GetAsync(WebApiRequest);
response.EnsureSuccessStatusCode();
Response = await response.Content.ReadAsStringAsync();
}
}
catch (HttpRequestException e)
{
Response = e.Message;
}
}
The decoded Token (using google token decoder looks as follows)
Header
{
"x5t": "mbJePjH80k9mnCYKdD-9UI0h_jA",
"alg": "RS256",
"typ": "JWT"
}
Claims
{
"identityprovider": "https://bluebeam-us-east.accesscontrol.windows.net/",
"iss": "https://bluebeam-us-east.accesscontrol.windows.net/",
"http://schemas.microsoft.com/identity/claims/identityprovider": "revu",
"exp": 1406957036,
"nbf": 1406956676,
"aud": "https://bluebeam.com/Bluebeam.Licensing.WebApi/"
}
So I have the following questions:
1) Is using JwtBearerToken the correct method to use to decode decode JWT token from ACS
2) Is there any tracing facilities in Owin that can provide whats going on in the authentication pipeline?
I am using Microsoft Own 3.0-rc1.
It seems that I had an error in my code where I was not setting the correct "bearer header" for OWIN when sending the client request to WebAPI.
After Receiving the JWT Token from ACS, I needed to set the Authorization correctly
private async void GetJwtToken()
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(IdP.Authority);
var content = new FormUrlEncodedContent(new Dictionary<String, String>
{
{"grant_type","client_credentials"},
{"client_id", IdP.UserName},
{"client_secret", IdP.Password},
{"scope", IdP.Resource}
});
var response = await client.PostAsync("v2/OAuth2-13", content);
response.EnsureSuccessStatusCode();
var jwtdata = await response.Content.ReadAsStringAsync();
var jwt = JsonConvert.DeserializeObject<Token>(jwtdata);
IdP.AccessToken = jwt.access_token;
IdP.TokenType = jwt.token_type;
long expire;
if (long.TryParse(jwt.expires_in, out expire))
{
IdP.ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(expire);
}
// Ensure that Correct Authorization Header for Owin
Authorization = String.Format("{0} {1}", "Bearer", IdP.AccessToken);**
}
}
catch (HttpRequestException re)
{
Response = re.Message;
}
}
We also need support for symmetric key on the WebAPI, based upon how ACS sends the token
public void ConfigureAuth(IAppBuilder app)
{
var thumbPrint = ConfigurationManager.AppSettings["ida:Thumbprint"];
var audience = ConfigurationManager.AppSettings["ida:Audience"];
var trustedTokenPolicyKey = ConfigurationManager.AppSettings["ida:SymmetricKey"];
app.UseErrorPage(new ErrorPageOptions()
{
ShowEnvironment = true,
ShowCookies = false,
ShowSourceCode = true,
});
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions()
{
AllowedAudiences = new[] {audience},
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new X509CertificateSecurityTokenProvider(Issuer,
X509CertificateHelper.FindByThumbprint(StoreName.My, StoreLocation.LocalMachine, thumbPrint)
.First()),
new SymmetricKeyIssuerSecurityTokenProvider(Issuer, trustedTokenPolicyKey),
},
});
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = audience,
Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
});
}