How to add two authorization headers in HttpClient - xamarin.forms

I need to add two header of Authorization in HttpClient as below:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwToken);
But it seems the last one will override the first one.
I need the Basic and Bearer token. Bearer token for me to pass through the Proxy server which host the SAP WebService, the Basic token for the SAP server. In this case, what I should do?
Update:
How to compose 2 HttpRequestMessage?
string webServiceUrl = "https://adfs.xxx.xxx/";
string strURL = "https://xxx.xxx.xxx/";
HttpResponseMessage responseMessage;
HttpClient client = new HttpClient();
//--1st HttpRequestMessage
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, strURL);
tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
HttpContent httpContent = new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("grant_type", "xxx"),
new KeyValuePair<string, string>("client_id", "xxx"),
new KeyValuePair<string, string>("scope", "xxx"),
new KeyValuePair<string, string>("assertion", Base64Assertion)
});
tokenRequest.Content = httpContent;
var tokenResponseMessage = await client.SendAsync(tokenRequest);
var token = await tokenResponseMessage.Content.ReadAsStringAsync();
//-- 2nd HttpRequestMessage
var serviceRequest = new HttpRequestMessage(HttpMethod.Get, webServiceUrl);
serviceRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var serviceResponseMessage = await client.SendAsync(serviceRequest);

In this case, what I should do?
You will need two separate clients, each with their own default authorization header,
client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
client2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwToken);
or one client with no default and the authorization set per request.
For example
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, authServerUrl);
tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
var httpContent = new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("grant_type", "xxx"),
new KeyValuePair<string, string>("client_id", "xxx"),
new KeyValuePair<string, string>("scope", "xxx"),
new KeyValuePair<string, string>("assertion",Base64Assertion)
});
tokenRequest.Content = httpContent;
var tokenResponseMessage = await client.SendAsync(tokenRequest);
var token = await responseMessage.Content.ReadAsStringAsync();
var serviceRequest = new HttpRequestMessage(HttpMethod.Get, webServiceUrl);
serviceRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var serviceResponseMessage = await client.SendAsync(serviceRequest);
//...

It has to do more with HTTP.Its not possible to send through multiple Authentication headers

Related

How can I pass header and parameter with HttpClient in .NET Core

This is my code using the RestSharp library:
var client = new RestClient("https://example.com/api");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer token...");
request.AddHeader("Content-Type", "text/plain");
request.AddParameter("text/plain", "{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}", ParameterType.RequestBody);
IRestResponse response = await client.ExecuteAsync(request);
// Console.WriteLine(response.Content);
// var res = response.Content;
How can I convert it to HttpClient using best practices?
You can use this:
var client = new HttpClient()
{
BaseAddress = new Uri("https://example.com"),
Timeout = TimeSpan.FromMinutes(5) //default is 90 seconds
};
client.DefaultRequestHeaders.Add("Authorization", "Bearer token...");
var body = new StringContent("{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}",Encoding.UTF8, "text/plain");
var response = await client.PostAsync("api", body);
var responseString = await response.Content.ReadAsStringAsync();
And for using the HttpClient in the right way I highly recommend to see this link.

Search code in azure devops projects with REST api

i am trying to search code through some project, i didnt succeed to recieve a proper response.
that what i did:
public async void GetProjects()
{
try
{
var personalaccesstoken = "mypersonalPat";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var httpClient = new HttpClient();
var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>("searchText", "a"));
list.Add(new KeyValuePair<string, string>("$top", "10"));
var content = new FormUrlEncodedContent(list);
var response = await httpClient.PostAsync("https://almsearch.dev.azure.com/myorganization/myproject/_apis/search/codesearchresults?api-version=5.1-preview.1", content);
var res = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
in the response i got 203 status message, in the res i got this (formatted as XML):
Azure DevOps Services | Sign In var __vssPageContext = {"webContext":{"user":{"id":"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa","name":"Anonymous","email":"","uniqueName":"TEAM FOUNDATION\\Anonymous"},"host":{"id":"7d0cc8e9-39e8-4313-9ff3-23ace0f8f4cf","name":"TEAM FOUNDATION","uri":"https://spsprodweu4.vssps.visualstudio.com/","relativeUri":"/","hostType":"deployment","scheme":"https","authority":"spsprodweu4.vssps.visualstudio.com"}},"moduleLoaderConfig":{"baseUrl":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/","paths":{"Profile/Scripts/Resources":"en-US","VSS/Resources":"en-US","Account/Scripts/Resources":"en-US","UserManagement/Scripts/Resources":"en-US","Authentication/Scripts/Resources":"en-US"},"map":{},"contributionPaths":{"VSS":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/VSS","pathType":"default"},"VSS/Resources":{"value":"en-US","pathType":"resource"},"q":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/q","pathType":"default"},"knockout":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/knockout","pathType":"default"},"mousetrap":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/mousetrap","pathType":"default"},"mustache":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/mustache","pathType":"default"},"react":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react.15.3","pathType":"default"},"react-dom":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react-dom.15.3","pathType":"default"},"react-transition-group":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react-transition-group.15.3","pathType":"default"},"jQueryUI":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/jQueryUI","pathType":"default"},"jquery":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/jquery","pathType":"default"},"OfficeFabric":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/OfficeFabric","pathType":"default"},"tslib":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/tslib","pathType":"default"},"#uifabric":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/#uifabric","pathType":"default"},"VSSUI":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/VSSUI","pathType":"default"}},"shim":{"jquery":{"deps":[],"exports":"jQuery"}},"waitSeconds":30},"coreReferences":{"stylesheets":[{"url":"/_static/tfs/M166_20200303.4/_cssbundles/Default/vss-bundle-ext-core-css-vgEHbWqZ4eb0vmOdl2cWjkpPtqcsX1GJCq4DnY78oN3s=","highContrastUrl":null,"isCoreStylesheet":true}],"scripts":[{"identifier":"JQuery","url":"/_static/3rdParty/_scripts/jquery-2.2.4.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"JQueryXDomain","url":"/_static/3rdParty/_scripts/jquery.xdomainrequest.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"Promise","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/promise.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"GlobalScripts","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/global-scripts.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"LoaderFixes","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/pre-loader-shim.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":false},{"identifier":"AMDLoader","url":"/_static/3rdParty/_scripts/require.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"LoaderFixes","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/post-loader-shim.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":false}],"coreScriptsBundle":{"identifier":"CoreBundle","url":"/_public/_Bundling/Content?bundle=vss-bundle-basejs-v9GpWWBnsWqhM23ijhK2HfAqLowTXGUqZLDRsBCZbkfY=","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},"extensionCoreReferences":{"identifier":"CoreBundle","url":"/_public/_Bundling/Content?bundle=vss-bundle-ext-core-vjMBLvR7Lq0Z_oS-OpRMsP9FOHhkdmDXf0mCbsK5c0RI=","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true}},"webAccessConfiguration":{"isHosted":true,"paths":{"rootPath":"/","staticContentRootPath":"/","staticContentVersion":"M166_20200303.4","resourcesPath":"/_static/tfs/M166_20200303.4/_content/","staticRootTfs":"/_static/tfs/M166_20200303.4/","cdnFallbackStaticRootTfs":"/_static/tfs/M166_20200303.4/","staticRoot3rdParty":"/_static/3rdParty/"},"api":{"webApiVersion":"1","areaPrefix":"_","controllerPrefix":""},"mailSettings":{"enabled":false},"registryItems":{}},"microsoftAjaxConfig":{"cultureInfo":{"name":"en-US","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"$","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":1,"PercentNegativePattern":1,"NegativeInfinitySymbol":"-∞","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"∞","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"‰","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"0001-01-01T00:00:00","MaxSupportedDateTime":"9999-12-31T23:59:59.9999999","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, MMMM d, yyyy h:mm:ss tt","LongDatePattern":"dddd, MMMM d, yyyy","LongTimePattern":"h:mm:ss tt","MonthDayPattern":"MMMM d","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH':'mm':'ss 'GMT'","ShortDatePattern":"M/d/yyyy","ShortTimePattern":"h:mm tt","SortableDateTimePattern":"yyyy'-'MM'-'dd'T'HH':'mm':'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy'-'MM'-'dd HH':'mm':'ss'Z'","YearMonthPattern":"MMMM yyyy","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]},"numberShortForm":{"QuantitySymbols":["K","M","B"],"NumberGroupSize":1000,"ThousandSymbol":"K"},"eras":null}},"timeZonesConfiguration":{},"featureAvailability":{"featureStates":{"VisualStudio.Services.Contribution.EnableOnPremUnsecureBrowsers":false,"VisualStudio.Service.WebPlatform.ClientErrorReporting":false,"Microsoft.VisualStudio.Services.Gallery.Client.UseCdnAssetUri":false,"VisualStudio.Services.WebAccess.SubresourceIntegrity":false,"VisualStudio.Services.IdentityPicker.ReactProfileCard":true}},"appInsightsConfiguration":{"enabled":false,"instrumentationKey":"00000000-0000-0000-0000-000000000000","insightsScriptUrl":null},"diagnostics":{"sessionId":"24ec3e5b-2a51-44d0-8738-32e2f2c48c12","activityId":"24ec3e5b-2a51-44d0-8738-32e2f2c48c12","bundlingEnabled":true,"webPlatformVersion":"M166","serviceVersion":"Dev18.M166.1 (build: AzureDevOps_M166_20200320.5)"},"navigation":{"topMostLevel":"deployment","area":"","currentController":"Signin","currentAction":"Index","routeId":"LegacyWebAccessRoute","routeValues":{"controller":"Signin","action":"Index"}},"globalization":{"explicitTheme":"","theme":"Default","culture":"en-US","timezoneOffset":0,"timeZoneId":"UTC"},"serviceInstanceId":"951917ac-a960-4999-8464-e3f0aa25b381","hubsContext":{},"serviceLocations":{"locations":{"951917ac-a960-4999-8464-e3f0aa25b381":{"Application":"https://spsprodweu4.vssps.visualstudio.com/","Deployment":"https://spsprodweu4.vssps.visualstudio.com/"}}}}; var __cultureInfo = __vssPageContext.microsoftAjaxConfig.cultureInfo;
hope someone can tell me the proper way to send the post request.
Try with below script:
try
{
var personalaccesstoken = "{token}";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var httpClient = new HttpClient();
var newcontent = new StringContent("{\"searchText\":\"gradle\",\"$top\":33}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await client.PostAsync("https://almsearch.dev.azure.com/{org}/{project}/_apis/search/codesearchresults?api-version=5.1-preview.1", newcontent))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Result:

Debug HttpClient request

How can i see exactly what the request sent by the HttpClient will contain?
var httpClient = new HttpClient();
var postData = JsonConvert.SerializeObject(
new
{
merchantId = _merchantId,
amount = _amount,
paymentRef = _paymentRef,
customer_ref = _customer_ref,
successUrl = _successUrl,
error_url = _error_url,
currency = _currency,
hash = "fsdfsdfsdf"
});
HttpResponseMessage response = await httpClient.PostAsync(url, new StringContent(postData));

uri is too long when I try to send a base64 using xamarin forms

I am working with xamarin.forms and System.Net.Http;
I am sending a photo using a post function which is this:
public static async Task<String> PostImagemAsync(User user)
{
using (var client = new HttpClient())
{
try
{
var values = new List<KeyValuePair<string, string>>(0);
values.Add(new KeyValuePair<string, string>("email", user.usua_login));
values.Add(new KeyValuePair<string, string>("senha", user.usua_senha));
values.Add(new KeyValuePair<string, string>("foto", user.cont_imagem));
values.Add(new KeyValuePair<string, string>("json", "1"));
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("http://ws.neosuite.com.br/login.asmx/foto", content);
var json = response.Content.ReadAsStringAsync().Result;
json = json.Substring(json.IndexOf('['));
json = json.Substring(0, json.LastIndexOf(']') + 1);
var userImage = JsonConvert.DeserializeObject<List<User>>(json);
return userImage[0].cont_imagem;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
}
My image (foto) is a base64 And it does I get this error when I try to send it:
Invalid URI: The Uri string is too long.
How to solve that?
Without adding your POST content into url, add that to body using following code
var uri = new Uri (string.Format ("http://ws.neosuite.com.br/login.asmx/foto", string.Empty));
var json = JsonConvert.SerializeObject (user);//user object or you can create your own jason here
var content = new StringContent (json, Encoding.UTF8, "application/json");
var response = await client.PostAsync (uri, content);

Asp.net Web Api Authentication and password encryption

I have a autentication with the web api working, but is using the email and password to autenticate, how can i change so that web api uses a username field and password for the autentication?
Another thing, how can i change the encrytion method for the password?
The Autentication is made this away:
public async Task<string> LoginAsync(string username, string password)
{
try
{
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password")
};
Settings.Serverdown = false;
var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.44.22:56479/Token");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(6000);
var response = await client.SendAsync(request);
var jwt = await response.Content.ReadAsStringAsync();
Settings.LoginSucess = response.IsSuccessStatusCode;
Settings.Username = username;
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(jwt);
var accessToken = jwtDynamic.Value<string>("access_token");
Settings.AccessToken = accessToken;
}
catch (Exception e)
{
XFToast.LongMessage("Cant reach the server");
Settings.Serverdown = true;
}
var accessToken2=Settings.AccessToken;
return accessToken2;
}
Thanks

Resources