Proxy authentication required(407) in some network - c#

i tried below code to resolve the proxy authentication issue. But still the issue is persist.
Note: Some networks without using Proxy, it is working fine.
var INI = new IniFile(#"Settings.ini");
String scredUserName = INI.Read("UserName", "Credentials");
String sPassword = INI.Read("Password", "Credentials");
String sAPIKey = INI.Read("APIKey", "Credentials");
string sUserNamePassword = scredUserName + ":" + sPassword;
byte[] byteUserNamePassword = System.Text.ASCIIEncoding.ASCII.GetBytes(sUserNamePassword);
string encodedUserNamePassword = System.Convert.ToBase64String(byteUserNamePassword);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
encodedUserNamePassword);
client.DefaultRequestHeaders.Add("aw-tenant-code", sAPIKey);
String sProxyUserName = INI.Read("UserName", "Proxy Authentication");
String sProxyPassword = INI.Read("Password", "Proxy Authentication");
string sProxyUserNamePassword = sProxyUserName + ":" + sProxyPassword;
byte[] byteProxyUserNamePassword = System.Text.ASCIIEncoding.ASCII.GetBytes(sProxyUserNamePassword);
string encodedProxyUserNamePassword = System.Convert.ToBase64String(byteProxyUserNamePassword);
client.DefaultRequestHeaders.Add("Proxy-Authorization", "Basic " + encodedProxyUserNamePassword);

Posting the answer for my questions:-
I should have passed Proxy credentials along with proxy address.
WebProxy wbProxy = new WebProxy();
Uri newUri = new Uri(sProxyAddress);
wbProxy.Address = newUri;
wbProxy.Credentials = new NetworkCredential(sProxyUserName, sProxyPassword);
client.Proxy = wbProxy;

Related

Including Authentication in the Header of a POST Request using ASP.NET Core

I'm trying to make a request to receive a session Id to integrate with a payment gateway.
var m = System.Text.Encoding.Unicode.GetBytes("merchant." + merchant_Id + ":" + merchant_pass);
var b64Val = Convert.ToBase64String(m);
var SerSession = JsonConvert.SerializeObject(sessionRequest);
var client = new HttpClient();
string _ContentType = "application/json";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
client.DefaultRequestHeaders.Add("Authorization", String.Format("Basic {0}", b64Val));
var _UserAgent = "d-fens HttpClient";
client.DefaultRequestHeaders.Add("User-Agent", _UserAgent);
HttpContent _Body = new StringContent(SerSession);
]_Body.Headers.ContentType = new MediaTypeHeaderValue(_ContentType);
HttpResponseMessage response;
response = await client.PostAsync(api_URL, _Body);
var content = response.Content.ReadAsStringAsync().Result;
return Ok(content);
I am getting (Invalid credentials) and I am sure the credentials I am using are correct. I have tested them in Python and PHP.
try this
var authenticationString = $"{merchant_Id}:{merchant_pass}";
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);

Azure Storage Queue via REST API c# using Shared Key Authentication

I am trying to call Azure Storage queue using REST API, but I am getting an error
The MAC signature found in the HTTP request
'UCiypkoySXueF4scXt+EqQESf5VXmAVLJUA93+3W10M=' is not the same as any
computed signature. The server used following string to sign: 'POST
text/plain
My C# Code is
var Client = new HttpClient();
var RequestDateString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
if (Client.DefaultRequestHeaders.Contains("x-ms-date"))
Client.DefaultRequestHeaders.Remove("x-ms-date");
Client.DefaultRequestHeaders.Add("x-ms-date", RequestDateString);
var StorageAccountName = "storaxxxxxxxsnd";
var StorageKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==";
String urlPath = String.Format("{0}/messages", "splitator");
Uri uri = new Uri(string.Format("https://{0}.queue.core.windows.net/", StorageAccountName) + urlPath);
if (Client.DefaultRequestHeaders.Contains("Authorization"))
Client.DefaultRequestHeaders.Remove("Authorization");
var canonicalizedStringToBuild = string.Format("{0}\n{1}", RequestDateString, $"/{StorageAccountName}/{uri.AbsolutePath.TrimStart('/')}");
string signature;
using (var hmac = new HMACSHA256(Convert.FromBase64String(StorageKey)))
{
byte[] dataToHmac = Encoding.UTF8.GetBytes(canonicalizedStringToBuild);
signature = Convert.ToBase64String(hmac.ComputeHash(dataToHmac));
}
string authorizationHeader = string.Format($"{StorageAccountName}:" + signature);
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedKey", authorizationHeader);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
if (Client.DefaultRequestHeaders.Contains("x-ms-version"))
Client.DefaultRequestHeaders.Remove("x-ms-version");
Client.DefaultRequestHeaders.Add("x-ms-version", "2015-12-11");
// if (httpMethod == HttpMethod.Delete || httpMethod == HttpMethod.Put)
// {
// if (Client.DefaultRequestHeaders.Contains("If-Match"))
// Client.DefaultRequestHeaders.Remove("If-Match");
// Currently I'm not using optimistic concurrency :-(
try
{
//Client.DefaultRequestHeaders.Add("If-Match", "*");
var stringContent = new StringContent("TESTAUTH", Encoding.UTF8, "text/plain");
var response= Client.PostAsync(uri, stringContent);
var resu=response.Result;
}
catch(Exception ex)
{
}
I am not sure what I am missing. I tried various combination but its failing.
I tried Microsoft recommended stringToSign formula too
I tried using canonical headers too
string signature;
var stringTosign = "POST\n" + "\n" + "\n" + "1024" + "\n" + "\n" + "text/plain\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + dateInRfc1123Format + "/xxxxxx/splitator/messages";
var hmac = new HMACSHA256(Convert.FromBase64String(accountKey));
var headerval= accountName + ":" + Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringTosign)));
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedKey", headerval);
Client.DefaultRequestHeaders.Accept.Clear();
I fixed the issue in your code, and now it's working. Please give it a try:
namespace ConsoleApp25
{
class Program
{
static void Main(string[] args)
{
var Client = new HttpClient();
var StorageAccountName = "yy1";
var StorageKey = "xxxx";
var apiversion = "2020-02-10";
var queue_name = "myqueue2";
String urlPath = String.Format("{0}/messages", queue_name);
Uri uri = new Uri(string.Format("https://{0}.queue.core.windows.net/{1}", StorageAccountName, urlPath));
//define a message to send
string raw_message = "TESTAUTH is ok";
//to send the message to the queue storage, the raw message must be formatted as below
string queue_message = $"<QueueMessage><MessageText>{raw_message}</MessageText></QueueMessage>";
//define the content type
string content_type = "text/plain; charset=utf-8";
//define date
var RequestDateString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
string StringToSign = String.Format("POST\n"
+ "\n" // content encoding
+ "\n" // content language
+ queue_message.Length + "\n" // content length
+ "\n" // content md5
+ content_type +"\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + RequestDateString + "\nx-ms-version:" + apiversion + "\n" // headers
+ "/{0}/{1}/{2}", StorageAccountName, queue_name, "messages"); //url
string auth = SignThis(StringToSign, StorageKey, StorageAccountName);
//define authorization header
if (Client.DefaultRequestHeaders.Contains("Authorization"))
Client.DefaultRequestHeaders.Remove("Authorization");
Client.DefaultRequestHeaders.Add("Authorization", auth);
Client.DefaultRequestHeaders.Accept.Clear();
//define x-ms-version header
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
if (Client.DefaultRequestHeaders.Contains("x-ms-version"))
Client.DefaultRequestHeaders.Remove("x-ms-version");
Client.DefaultRequestHeaders.Add("x-ms-version", apiversion);
//define the x-ms-date header
if (Client.DefaultRequestHeaders.Contains("x-ms-date"))
Client.DefaultRequestHeaders.Remove("x-ms-date");
Client.DefaultRequestHeaders.Add("x-ms-date", RequestDateString);
try
{
var stringContent = new StringContent(queue_message, Encoding.UTF8, "text/plain");
var response = Client.PostAsync(uri, stringContent);
var resu = response.Result;
}
catch (Exception ex)
{
}
Console.WriteLine("**completed**");
Console.ReadLine();
}
private static String SignThis(String StringToSign, string Key, string Account)
{
String signature = string.Empty;
byte[] unicodeKey = Convert.FromBase64String(Key);
using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(StringToSign);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String authorizationHeader = String.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
Account,
signature);
return authorizationHeader;
}
}
}
And if you don't want to generate the shared key since it's not easy, you can use sas token for authentication in the rest api.

RESTful Call in C# using basic authentication returning error message

I am trying to call a Restful service on OSB. My code is:
string url = _httpGetText + "&$filter=" + filter;
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
ServicePointManager.SecurityProtocol =
SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12;
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("CLLORptngAppIdDev:DPJZuogiYEo5"));
WebResponse response;
try
{
response = request.GetResponse();
List<HistoryRequest> histroyRequestList = LoadHistoryRequest(response);
return histroyRequestList;
}
catch(Exception ex)
{
string msg = ex.Message;
}
The message in the catch is: The remote server returned an error: (500) Internal Server Error.
On the serer side I see this message
<responseSelectedForConsumingProxyService>
<soap-env:Body
xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
<soap-env:Body>
<soap-env:Fault>
<faultcode>Server</faultcode>
<faultstring>This is an Oracle Service Bus generated fault.
[OSB-386420 - A web service security error ocurred while producing security header]
[RouteNode_XXXXXXXXXXXXV_1_0request-pipeline]
[instanceid - *********************************************;]
</faultstring>
</soap-env:Fault>
</soap-env:Body>
</soap-env:Body>
</responseSelectedForConsumingProxyService>
As a result of comments I have also tried the following options with the exact same results:
request.Headers["Authorization"] = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("UTF-8").GetBytes("<ID>:<Pssword>"));
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("<ID>:<Pssword>"));
request.Headers.Add("Authorization", "Basic " + encoded);
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("UTF-8").GetBytes("<ID>:<Pssword>"));
request.Headers.Add("Authorization", "Basic " + encoded);
I came up with the following code that works:
public List<HistoryRequest> GetHistoryRequestList()
{
Configuration roamingConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string OSBBaseUri = ConfigurationManager.AppSettings["OSBUrl"];
string OSBGetEndPoint = ConfigurationManager.AppSettings["OSBEndPoint"];
string MSDCallerId = ConfigurationManager.AppSettings["AppId"];
string Encoding = "iso-8859-1";
string Osbpw = HistoryCrypto.Decrypt(ConfigurationManager.AppSettings["CipherPass"], ConfigurationManager.AppSettings["CryptoKey"]);
CredentialCache credentialCache = new CredentialCache
{
{
new Uri(OSBBaseUri),
"NTLM",
new NetworkCredential()
{
UserName = "<UserName>",
Password = Osbpw,
Domain = ConfigurationManager.AppSettings["Domain"]
}
}
};
HttpMessageHandler handler = new HttpClientHandler()
{
Credentials = credentialCache
};
var _httpClient = new HttpClient(handler)
{
BaseAddress = new Uri(OSBBaseUri),
Timeout = new TimeSpan(0, 2, 0),
};
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("HTTP_Referrer/HistoryRequestProcess"));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("MSCRMCallerID/"+ MSDCallerId));
HttpContent httpContent = new StringContent("{\"operationssubtypecode\":\"HREQ\"} ", System.Text.Encoding.UTF8, "application/json");
var method = new HttpMethod("GET");
var message = new HttpRequestMessage(method, OSBGetEndPoint)
{
Content = httpContent
};
message.Headers.Add("HTTP_Referrer", "HistoryRequestProcess");
message.Headers.Add("MSCRMCallerID", MSDCallerId);
HttpResponseMessage response = _httpClient.GetAsync(OSBGetEndPoint).Result;
string content = string.Empty;
using (StreamReader stream = new StreamReader(response.Content.ReadAsStreamAsync().Result, System.Text.Encoding.GetEncoding(Encoding)))
{
content = stream.ReadToEnd();
}
return LoadHistoryRequest(content);
}

Jenkins returns (403) Forbidden when createItem in C#

I am trying to create a task with the Jenkins API.
The user has permissions but there is no way.
The error that throwing is 403.
public void CreateJobWihtXmlTemplateAndRazorRemplaceWhitAutoritazion()
{
var configData = File.ReadAllText(configCobol);
byte[] credentialBuffer = new UTF8Encoding().GetBytes("user" + ":" +"pass");
var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(credentialBuffer));
webClient.UseDefaultCredentials = true;
webClient.Proxy.Credentials = CredentialCache.DefaultCredentials;
var jenkinsJobData = FactoryDataProvider.CreateJenkinsJobData();
var result = Razor.Parse(configData, jenkinsJobData);
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(result);
const string FORMAT = "http://{0}:{1}/createItem?name={2}";
var path =
string.Format(
FORMAT,
"someserver.example.com",
"8080",
jenkinsJobData.ProjectName);
webClient.Headers["content-type"] = " application/xml";
string response = webClient.UploadString(
path,
"POST",
result
);
Assert.AreEqual(HttpStatusCode.OK, HttpStatusCode.OK);
}
Uncheck "Prevent Cross Site Request Forgery exploits"

500 px api with C# throwing 500 Internal Server Error

I am trying to implement 500px API with C#. I am able to authenticate user with 500px API but I am unable to get the access_token in exchange of response_token which leaves my third step of Oauth 1.0 incomplete. I am able to authorize user and get oauth_token and oauth_verifier but when I use this oauth_token for making following request :-
https://api.500px.com/v1/oauth/access_token
500 Internal Server Error along with the following screen gets thrown
I have debugged my code like thousand times, tried different ways to form URL, added various parameters to the request but no help. I am very badly stuck as almost no information is available on 500px developer website or on web for using this api in C#. I have reached a dead-end!
Following is my code:-
1.]For requesting token and authorizing user :-
string normalizedUrl;
string normalizedRequestParameters;
OAuth.OAuthBase myOAuth = new OAuth.OAuthBase();
try
{
Uri uri = new Uri("https://api.500px.com/v1/oauth/request_token");
string consumerKey = "u26X4av9ydNPd7kteT7bunfcdjHqVttYWIDOC1lA";
string consumerSecret = "73iaFPqCR4xkH3dgYIcPauTqhI6tMHWChDivnOP7";
string timeStamp = myOAuth.GenerateTimeStamp();
string nonce = myOAuth.GenerateNonce();
myOAuth.includeVersion = true;
string signature = myOAuth.GenerateSignature(uri, consumerKey, consumerSecret,
"", "", "GET", timeStamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
string authorizationUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Uri signInUrl = new Uri(authorizationUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(signInUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stIn = new StreamReader(response.GetResponseStream());
string responseString = stIn.ReadToEnd();
stIn.Close();
//oauth_token=cf40227bb7ede4d6e56ff790324761b3&oauth_token_secret=0bcb59dff2c1d095739c86c534fc62d7ed224fecfe8744d48c9c95f36211382f
if (responseString.Contains("oauth_token=") && responseString.Contains("oauth_token_secret="))
{
String RespToken = responseString.Split('&')[0].Replace("oauth_token=", "");
String RespSecret = responseString.Split('&')[1].Replace("oauth_token_secret=", "");
uri = new Uri("https://api.500px.com/v1/oauth/authorize");
timeStamp = myOAuth.GenerateTimeStamp();
nonce = myOAuth.GenerateNonce();
myOAuth.includeVersion = true;
signature = myOAuth.GenerateSignature(uri, consumerKey, consumerSecret, RespToken
, RespSecret, "GET", timeStamp, nonce, OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
Console.WriteLine("Signature=="+signature);
authorizationUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Uri signInUrl1 = new Uri(authorizationUrl);
webBrowser1.Navigate(signInUrl1);
}
2.]After User clicks on Authorise this application for getting access_token:-
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string parameters;
string normalizedUrl;
string normalizedRequestParameters;
string consumerKey = "u26X4av9ydNPd7kteT7bunfcdjHqVttYWIDOC1lA";
string consumerSecret = "73iaFPqCR4xkH3dgYIcPauTqhI6tMHWChDivnOP7";
OAuth.OAuthBase myOAuth = new OAuth.OAuthBase();
try
{
if (e.Url.ToString().Contains("https://www.xyz.com/"))
{
String url = (e.Url.ToString()).Replace("https://www.xyz.com/?","");
if( url.Contains("oauth_token="))
{
string OAuthToken = url.Split('&')[0].Replace("oauth_token=", "");
var uri = "https://api.500px.com/v1/oauth/access_token";
OAuthBase oAuth = new OAuthBase();
var nonce = oAuth.GenerateNonce();
var timeStamp = oAuth.GenerateTimeStamp();
var signature = oAuth.GenerateSignature(new Uri(uri), consumerKey, consumerSecret,
OAuthToken, String.Empty, "POST", timeStamp, nonce,
OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
signature = HttpUtility.UrlEncode(signature);
var requestUri = normalizedUrl + "?" + "oauth_callback=https://www.xyz.com" +"?"+ normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
Console.WriteLine(requestUri);
var request = (HttpWebRequest)WebRequest.Create(requestUri.ToString());
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/json";
// request.ContentType = "application / x - www - form - urlencoded";
//request.Credentials = CredentialCache.DefaultCredentials;
//request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var accessToken = reader.ReadToEnd();
}
}
catch(Exception ex)
{
Console.Writeln(ex.toString());
}
}
Now following is the line where my code is breaking:-
var response = request.GetResponse();
Completely at my wits end on this issue, not able to get to the root of it. Any help any directions will be highly appreciated. Any suggestions would be of great help!!
Thanks a ton in advance!
Here's what to do:
Use GET rather than POST (POST may work; I've not tried it and have had little success with 500px and POSTing)
Include the oauth_verifier you received during the authorisation step in the query URL
Sign the entire query using your consumer key and request token secret (returned in step 1)
Code snippet which should return "oauth_token=...&oauth_token_secret=..." in the HTTP reply body.
Make sure your OAuth implementation doesn't strip out any parameters beginning with "oauth_"! Mine was and it was stripping out the oauth_verifier parameter which is required by 500px.
OAuth.OAuthBase oauth = new OAuth.OAuthBase();
string strUrl = "";
string strParams = "";
string signature = oauth.GenerateSignature(new Uri(API_URL + "oauth/access_token?oauth_verifier=" + this.oauthVerifier),
this.consumerKey, this.consumerSecret, this.oauthToken, this.requestTokenSecret,
"GET", oauth.GenerateTimeStamp(), oauth.GenerateNonce(),
OAuth.OAuthBase.SignatureTypes.HMACSHA1,
out strUrl, out strParams);
string authorizationUrl = strUrl + "?" + strParams + "&oauth_signature=" + System.Web.HttpUtility.UrlEncode(signature);
Debug.WriteLine("url>" + authorizationUrl);
Response reply = SendGetRequest(authorizationUrl);
if (reply.Success)
{
Debug.WriteLine("access_token>" + reply.Content);

Categories