I am developing webservice which calls REST service and as per requirement I need to set cookie in the request header. EVen if I set everything , it gives me "401 Unauthorized message" as response.
var request = (HttpWebRequest)HttpWebRequest.Create("https://TESTRestAPI/service/1/sub");
request.Headers.Add("Authorization", "Basic" + Encoded);
request.Method = "GET";
request.ContentType = "application/json";
var response = (WebResponse)request.GetResponse();
So far I tried this :-
1. request.Headers["Cookie"] = "BasicAuth=fromTest";
2. request.CookieContainer = new CookieContainer();
Uri target = new Uri("https://TESTRestAPI/service/1/sub"););
Cookie ck = new Cookie("BasicAuth","fromTest") { Domain = target.Host };
This is first time I am calling REST service, any help appreciated.
this code is to authenticate an http request by using basic authentication, with some Username and Password
byte[] credentialBuffer = new UTF8Encoding().GetBytes(username + ":" + password);
string authToken = Convert.ToBase64String(credentialBuffer);
string authHeaderValue = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Basic {0}", authToken);
HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create("https://TESTRestAPI/service/1/sub");
request.Headers.Add(HttpRequestHeader.Authorization, authHeaderValue);
Additionaly, if it is required that the request contains some cookie with some name and some value, Id' use your code number 2.
CookieContainer requestCookieContainer = new CookieContainer();
Cookie requiredCookie = new Cookie("BasicAuth", "fromTest");
requiredCookie.Domain = "https://TESTRestAPI/service/1/sub";
requiredCookieContainer.Add(requiredCookie);
request.CookieContainer = requestCookieContainer;
If your application runs on IIS, the config file may need some lines. I think basic authentication is disabled by default, as it isn't too much safe.
<system.webServer>
<security>
<authentication>
<basicAuthentication enabled="true"/>
</authentication>
</security>
</system.webServer>
Related
I have a CLR function getting data from cookie authorized website. The first request gets a login cookies and the second request gets xml data I need. The problem is in that I am always getting 401 unauthorized on a second request when run it from SQL Server as a function. The testing console app using the same DLL is working fine. Looks like the second request has no cookies but I checked in exception the amount of cookie container of the second request, it is not empty.
String encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(UserName + ":" + Password));
try
{
HttpWebRequest loginrequest = (HttpWebRequest)WebRequest.Create(string.Format("{0}", BaseOrdersAddress));
CookieContainer logincookies = new CookieContainer();
loginrequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + encoded);
loginrequest.AllowAutoRedirect = false;
loginrequest.CookieContainer = logincookies;
loginrequest.Method = WebRequestMethods.Http.Get;
HttpWebResponse loginresponse = (HttpWebResponse)loginrequest.GetResponse();
loginresponse.Close();
if (loginresponse.StatusCode == HttpStatusCode.Found)
{
location = loginresponse.Headers[HttpResponseHeader.Location];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(location);
request.CookieContainer = logincookies;
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response1 = request.GetResponse() as HttpWebResponse;
var xresult = new XmlSerializer(typeof(Local_Response));
r = (Local_Response)xresult.Deserialize(response1.GetResponseStream());
}
Solved.
The problem was in using HttpWebRequest.CookieContainer, don't know why but it does not work while running as a CLR function, no cookies are sent. Have to do it manually adding HttpRequestHeader.Cookie to request headers collection.
Don't forget, your SQLCLR code executes in the context of SQL Server. I see you have a username, password in the code - what does that do and where is the username/password retrieved from. My bet is that there is something wrong with this based on what I said earlier.
I'm trying to send curl request passing some headers and authentication info.
All information i want to send went successfully but I'm stuck with how to send the api key that should be used instead of the normal username/password manner.
when I use online curl websites to send the curl request, I put : after the api key and then everything works perfectly.
And this is what i want to do in C# using HttpWebRequest
This is the code I'm using in order to do that:
string credentials = String.Format("{0}:{1}", "API_KEY", "GivenApiKey: ");
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.website.com/test");
httpWebRequest.ReadWriteTimeout = 100000;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.UserAgent = "GivenUserAgent";
httpWebRequest.Credentials = new NetworkCredential("Authorization", authorization);
please any help?
You should put the Authorization in a Header so:
httpWebRequest.Headers["Authorization"] = "Bearer " + apikey;
Depending on the server you are contacting, you'll have to determine the input. In my case Bearer should be placed before the apikey.
As most servers use the following setup for authorization:
Authorization: <type> <credentials>
I am developing ASP.net application which consumes REST services with ASP.Net Web API. I am trying to use Basic authentication for my website. I plan to use it with SSL once I complete Basic authentication.
Currently on Login button click I am sending Auth header using Base64 encoding of username and password as shown below:
string responseData = string.Empty;
string authToken = string.Empty;
string loginInstance = url;
// Create request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
String username = txtUserName.Text;
String password = txtPassword.Text;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
String resultData = reader.ReadToEnd();
bool result = false;
result = Convert.ToBoolean(resultData);
return result;
I assume I will need to send authentication header to all of those web api requests that needs to be secure and pass through authentciation.
Is there a way to attach authentication header to every request that I send or even to a set of requests?
Please note: most of the Web API requests are invoked through JQuery.
Also please let me know if this is not recommended approach of implementation.
Regards,
Abhilash
Have you try like this :
WebRequest request = (HttpWebRequest)WebRequest.Create("https://yoururl");
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
basic http authentication in asp.net web api using message handlers.
http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers/
Can you try with below code inplace of "request.Headers.Add("Authorization", "Basic " + encoded);" .
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " +
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
I believe you can just add
request.PreAuthenticare = true
You may look for HttpWebRequest.Credentials Property.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Credentials = CredentialCache.DefaultCredentials;
Above example contains the credentials of the currently logged on user.
"The Credentials property can be either a NetworkCredential, in which case the user, password, and domain information contained in the NetworkCredential object is used to authenticate the request, or it can be a CredentialCache".
MSDN Reference
I would like to know why my asp.net application will not add the header to my post when it is named 'Authorization' but will work fine when I change one character, say "Authorizations". In documentation for other sites they always use the name "Authorization" so I would like to as well and at this point I just want to under stand why.
I have read a few topics about this but have not found any logical reason why.
Here is my code below:
string fileName = "c:\\xyz.xml";
string uri = "http://myserver/Default.aspx";
req = WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "text/xml";
byte[] authBytes = Encoding.UTF8.GetBytes("DDSServices:jCole2011".ToCharArray());
req.Headers.Add("Authorization", "BASIC " + Convert.ToBase64String(authBytes) );
req.Headers.Add("test", "test");
UTF8Encoding encoder = new UTF8Encoding();
byte[] data = encoder.GetBytes(this.GetTextFromXMLFile(fileName));
req.ContentLength = data.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
req.Headers.Add("Authorization", "BASIC" + Convert.ToBase64String(authBytes));
System.Net.WebResponse response = req.GetResponse();
System.IO.StreamReader reader = new StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
The other annoying this is when i add the watched variable through fiddler it works fine.
I was ran into a question how to add Authentication/Credentials to the headers. I found the solution in the following way.
string _auth = string.Format("{0}:{1}", "myUser","myPwd");
string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth));
string _cred = string.Format("{0} {1}", "Basic", _enc);
req.Headers[HttpRequestHeader.Authorization] = _cred;
Which gave me those headers I want (pasted Wireshark descriptions),
Authorization: Basic bXlVc2VyOm15UHdk\r\n
Credentials: myUser:myPwd
For HTTP Basic Authorization, you should be using the Credentials property.
req.Credentials = new NetworkCredential("DDSServices", "jCole2011");
This should do what you want. Rather than setting the Authorization header.
NetworkCredential is a good solution but the site you are calling has to handle an unauthorized with a 401 AND a WWW-Authenticate header in the response.
Client:
request.Credentials = new CredentialCache {{aUri, "Basic", new NetworkCredential(aUserName, aPassword)}};
Server:
Response.ClearContent();
Response.StatusCode = 401;
Response.AddHeader("WWW-Authenticate", "Basic");
Response.End();
This will result in 2 hits to the server. The initial call will go to the server without credentials. When the server responds with a 401 AND the WWW-Authenticate header (with the type of authentication required), the request will be resent with the credentials in the request.
I want to request reports from a third party and they require "Basic Access Authentication" via POST:
Your client application must use Basic Access Authentication
to send the user name and password.
Can someone point me in the right direction?
Edit: I did see this post but there are two answers and I'm not sure if thats what I need to do or which one is the preferred method.
Assuming you use a WebRequest, you attach a CredentialCache to your request:
NetworkCredential nc = new NetworkCredential("user", "password");
CredentialCache cc = new CredentialCache();
cc.Add("www.site.com", 443, "Basic", nc);
WebRequest request = WebRequest.Create("https://www.site.com");
request.Credentials = cc;
request.PreAuthenticate = true;
request.Method = "POST";
// fill in other request properties here, like content
WebResponse respose = request.GetResponse();
The basic gist is like this:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
request.Credentials = new NetworkCredential(username, password);
but sometimes there are issues with using request credentials, the alternative is add the authentication data in request headers
string authInfo = username + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
for more details see this blog post
http://charlie.cu.cc/2012/05/how-use-basic-http-authentication-c-web-request/