401 Unauthorized after release site - c#

I have my web api which uses such code to get data from other api and do some operations with it :
var credential = new NetworkCredential("login", "password");
var myCache = new CredentialCache();
myCache.Add(uri, "Negotiate", credential);
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.Credentials = myCache;
var httpClient = new HttpClient(handler);
var response = await httpClient.GetStringAsync(GetEmployeesUrl);
employees = JsonConvert.DeserializeObject<IEnumerable<EmployeeDto>>(response);
When I was debugging this code with IIS Express on my local host it's pretty good works and give me OK response from server. When I tried to deploy my api to real IIS this var response = await httpClient.GetStringAsync(GetEmployeesUrl);always returns 401 Unauthorized error.
Have someone some ideas what it can be? I have used webclient and webrequest they worked on my local machine but answer after deploy on server was the same.

Related

Webservice client

I'm trying to access a soap webservice i .net Core 3.1
I did add the service via Microsoft WCF Web Service Reference Provider (I typed username and password to get access.)
But I have some login issues with it.
If I try a simpel HttpClient it works fine and I get access like this:
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri("http://xxx"), "Negotiate", new NetworkCredential(strUserName, strPassword, strDomain));
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = credentialCache;
var httpClient = new HttpClient(handler);
But with the WCF Web Service Reference I get this error:
One or more errors occurred. (The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate'.)'
var client = new xxClient();
var task = Task.Run(async () => await client.GetContactsFromEmailAsync(_test).ConfigureAwait(false)) ;
Console.WriteLine(task.Result.ToString());
So how do I make my client "Negotiate" ?
Or what else do I need to do?

C# Oracle Rest API, Authentication Issue

I am trying to use Ocacle's Financial REST API and I'm having trouble making it work in C# in VS2019.
I can confirm the restful call works using Postman, so I know my credentials are fine but I must be missing something trying this with in code.
So URL is like so:
http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail
So I stick that in postman, put in my credentials (basic auth) and it works find. In VS I've tried both the RestSharp way and basic HTTPRequest way as follows:
HttpWebRequest r = (HttpWebRequest)WebRequest.Create("/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
r.Method = "GET";
string auth = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("Username" + ":" + "Password"));
r.Headers.Add("Authorization", "Basic" + " " + auth);
r.ContentType = "application/vnd.oracle.adf.resourcecollection+json";
using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
{
int b = 0;
}
RestSharp:
var client = new RestClient("http://MYCLOUDDOMAIN/fscmRestApi/resources/11.13.18.05/ledgerBalances?finder=AccountBalanceFinder;accountCombination=3312-155100-0000-0000-0000-00000,accountingPeriod=Feb-20,currency=USD,ledgerSetName=Ledger US,mode=Detail&fields=LedgerName,PeriodName,Currency,DetailAccountCombination,Scenario,BeginningBalance,PeriodActivity,EndingBalance,AmountType,CurrencyType,ErrorDetail");
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("UserName", "Password");
//Tried authorization this way as well.
//JObject AuthRequest = new JObject();
//AuthRequest.Add("Username", "UserName");
//AuthRequest.Add("Password", "Password");
var request = new RestRequest();
request.Method = Method.GET;
request.RequestFormat = DataFormat.Json;
//request.AddParameter("text/json", AuthRequest.ToString(), ParameterType.RequestBody);
request.AddHeader("Content-Type", "application/vnd.oracle.adf.resourcecollection+json");
request.AddHeader("REST-Framework-Version", "1");
var response = client.Get(request);
No matter what I try I am always 401 not authorized. I suspect its some kind of header thing? I can't see the raw request header in postman
I am new to REST. I am used to using WSDLs soap services.
Try this.
var handler = new HttpClientHandler
{
Credentials = new NetworkCredential("username", "password")
};
using (var client = new HttpClient(handler))
{
var result = await client.GetAsync("url");
}
Good luck!
I figured out what the problem was.
In postman, it was fine with the URL I posted being HTTP but in C# code it was not. I switched the URL to HTTPS and it started working just fine.

Is it possible to use an HTTPClient with Windows authentication within an AWS Lambda function?

Is it possible to specify Windows credentials to HttpClient within an AWS Lambda function?
For example:
var handler = new HttpClientHandler {
Credentials = new NetworkCredential("username", "password", "domain")
};
var httpClient = new HttpClient(handler);
var content = new StringContent("<test>test</test>", Encoding.UTF8, "application/xml");
var response = await httpClient.PostAsync("http://someurl", "content");
The target url returns 401 Unauthorized and it looks like the NetworkCredentials haven't been passed through.
The Lambda has been granted the role AWSLambdaFullAccess.
When executed locally, this code with the same credentials works as expected.

HttpWebRequest error 401 on Pi3 with IoT Core c#

I've used the search funktion before but the Solutions won't help in my case (don't know why). I've written a Code to call a IIS Webservice. The Code will run on my Desktop without any issues. On my Pi3 i will get an
(One or more errors occurred. (The remote server returned an error: (401) Unauthorized.)
error. What I'm doing wrong?
Thx Forward for helping me.
Uri uri = new Uri(Url); //TempUrl is assigned a string beforehand
request = HttpWebRequest.Create(uri);
// Add authentication to request
NetworkCredential c = new NetworkCredential("USER", "PASSWORD","DOMAIN");
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(uri, "NTLM", c);
request.Credentials = c;
Task<WebResponse> x = request.GetResponseAsync();
x.Wait(20000);
response = x.Result;
// Get the response stream into a reader
reader = new StreamReader(response.GetResponseStream());
Got it. I've Change the NetworCredentials as follows:
NetworkCredential c = new NetworkCredential(#"<Domain>\<USER>", "<PASSWORD>");
I don't know why, but it works.

Proxy Basic Authentication in C#: HTTP 407 error

I am working with a proxy that requires authentication, i.e., in a browser if I try to open a page it will immediately ask for credentials. I supplied same credentials in my program but it fails with HTTP 407 error.
Here is my code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
IWebProxy proxy = WebRequest.GetSystemWebProxy();
CredentialCache cc = new CredentialCache();
NetworkCredential nc = new NetworkCredential();
nc.UserName = "userName";
nc.Password = "password";
nc.Domain = "mydomain";
cc.Add("http://20.154.23.100", 8888, "Basic", nc);
proxy.Credentials = cc;
//proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Proxy = proxy;
request.Proxy.Credentials = cc;
request.Credentials = cc;
request.PreAuthenticate = true;
I have tried every possible thing but seem like I am missing something.
Is it something like, I have to make two requests? First with out credentials and once I hear back from server about need for credentials, make same request with credentials?
This method may avoid the need to hard code or configure proxy credentials, which may be desirable.
Put this in your application configuration file - probably app.config. Visual Studio will rename it to yourappname.exe.config on build, and it will end up next to your executable. If you don't have an application configuration file, just add one using Add New Item in Visual Studio.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
</configuration>
I was getting a very similar situation where the HttpWebRequest wasn't picking up the correct proxy details by default and setting the UseDefaultCredentials didn't work either. Forcing the settings in code however worked a treat:
IWebProxy proxy = myWebRequest.Proxy;
if (proxy != null) {
string proxyuri = proxy.GetProxy(myWebRequest.RequestUri).ToString();
myWebRequest.UseDefaultCredentials = true;
myWebRequest.Proxy = new WebProxy(proxyuri, false);
myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
and because this uses the default credentials it should not ask the user for their details.
here is the correct way of using proxy along with creds..
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
IWebProxy proxy = request.Proxy;
if (proxy != null)
{
Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
}
else
{
Console.WriteLine("Proxy is null; no proxy will be used");
}
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri("http://20.154.23.100:8888");
// Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
myProxy.Address = newUri;
// Create a NetworkCredential object and associate it with the
// Proxy property of request object.
myProxy.Credentials = new NetworkCredential("userName", "password");
request.Proxy = myProxy;
Thanks everyone for help... :)
This problem had been bugging me for years the only workaround for me was to ask our networks team to make exceptions on our firewall so that certain URL requests didn't need to be authenticated on the proxy which is not ideal.
Recently I upgraded the project to .NET 4 from 3.5 and the code just started working using the default credentials for the proxy, no hardcoding of credentials etc.
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
I had a similar problem due to a password protected proxy server and couldn't find much in the way of information out there - hopefully this helps someone. I wanted to pick up the credentials as used by the customer's browser. However, the CredentialCache.DefaultCredentials and DefaultNetworkCredentials aren't working when the proxy has it's own username and password even though I had entered these details to ensure thatInternet explorer and Edge had access.
The solution for me in the end was to use a nuget package called "CredentialManagement.Standard" and the below code:
using WebClient webClient = new WebClient();
var request = WebRequest.Create("http://google.co.uk");
var proxy = request.Proxy.GetProxy(new Uri("http://google.co.uk"));
var cmgr = new CredentialManagement.Credential() { Target = proxy.Host };
if (cmgr.Load())
{
var credentials = new NetworkCredential(cmgr.Username, cmgr.Password);
webClient.Proxy.Credentials = credentials;
webClient.Credentials = credentials;
}
This grabs credentials from 'Credentials Manager' - which can be found via Windows - click Start then search for 'Credentials Manager'. Credentials for the proxy that were manually entered when prompted by the browser will be in the Windows Credentials section.
You can use like this, it works!
WebProxy proxy = new WebProxy
{
Address = new Uri(""),
Credentials = new NetworkCredential("", "")
};
HttpClientHandler httpClientHandler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true
};
HttpClient client = new HttpClient(httpClientHandler);
HttpResponseMessage response = await client.PostAsync("...");
try this
var YourURL = "http://yourUrl/";
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = true,
};
Console.WriteLine(YourURL);
HttpClient client = new HttpClient(handler);

Categories