Provide Credentials for BackgroundTransferRequest (WP8) - c#

When I am using HttpWebRequest I use the following code to set the Credentials
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToCall);
request.Method = "GET";
request.Credentials = new NetworkCredential(username, pass);
How do I do the same when I am using BackgroundTransferService in Windows Phone 8.
For reference I am using the following.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202955%28v=vs.105%29.aspx
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202959%28v=vs.105%29.aspx
*Edit:
The authentication method is Digest
This is what I get in the Authorization Header when I use my browser to download the file.
Digest username="adf", realm="bcd", nonce="XXXXXXXXX", uri="/ans/1268e52399.txt", algorithm=MD5, response="XXXXXXXXXXXXXXX", qop=auth, nc=00000001, cnonce="XXXXXXXXXXXX"

Unfortunately this isn't supported on the BackgroundTranserService. One possible solution might be to manually create a header for your request like below:
var credentials = new UTF8Encoding().GetBytes(username + ":" +password);
var transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Headers["Authorization"] ="Basic " + convert.ToBase64String(credentials);
Unfortunately I'm unable to test this at the minute, give it a try and let me know how you get on.

Related

MSSQL CLR function webreqest 401 unauthorized

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.

How to send authentication header in ASP.Net for set of web request

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

REST C# Get List Items

I am completely new to REST API.
I would like to retrieve ListItems in xml format from an external site in C#.
I have got the username and password for the site (which uses Mixed authentication by the way).
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create("https://<site>/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/atom+xml";
//endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
endpointRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("<domain>\\<username>:<password>"));
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
I am using this piece of code that I found on MSDN.
Would anybody please be kind enough to tell me how do I get an access token?
Why am I getting 403 Forbidden error?
I think you can better use the NetworkCredential class:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("testuser", "testpass");
request.Credentials = credentials;
No need to send the Authorization header
When I have to use REST API I use Tiny.RestClient 1
In your case you have to write the call like that :
var client = new TinyRestClient(new HttpClient(), "https://<site>/_api/");
client.GetRequest("web/lists")
Hopes that help.
WithBasicAuthentication("username", "password").
ExecuteAsync();

ASP.NET Equivalent to this cURL command

I'm working with the Twilio API and it provides examples in PHP and Ruby. I'm working on a site to send text messages through the API that's coded in ASP.NET MVC 3, and using my limited knowledge of the WebRequest object, I was able to translate this:
curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/AC4840da0d7************f98b20b084/SMS/Messages.xml' \
-d 'From=%2B14155992671' \
-u AC4840da0d7************f98b20b084:f7fc2**************75342
Into this:
var request =
WebRequest.Create(MessageApiString + "?From=+14*********1&To=" + Phone + "&Body=" + smsCampaign.Message);
var user = "AC4840da0d7************f98b20b084";
var pass = "f7fc2**************75342";
string credentials = String.Format("{0}:{1}", user, pass);
request.Headers.Add("Authorization", credentials);
var result = request.GetResponse();
But it's not authenticating, I'm getting a 401 from their API. What is the equivalent C# to the cURL -u command?
Update
var request =
WebRequest.Create(MessageApiString + "?From=+14155992671&To=" + Phone + "&Body=" + smsCampaign.Message);
var cc = new CredentialCache();
cc.Add(new Uri(MessageApiString), "NTLM", new NetworkCredential("AC4840da0d7************f98b20b084", "f7fc2**************75342"));
request.Credentials = cc;
request.Method = "POST";
var result = request.GetResponse();
Still getting 401. Any ideas?
Update 2
Alright, thanks to the answers below I was able to get through to the api, but now I'm getting a 400 Bad Request. Is there a cleaner way to build a query string to pass this data along? The three fields are From, To, and Body.
Try including
request.Method = "POST";
and
request.Credentials = new NetworkCredential("username", "password");
The -u option in Curl is to specify a username and password for Server Authentication.
For C# this is set using the WebRequest.Credentials property.

Using uTorrent Web API via .NET

I'm trying to get list of torrents from uTorrent using Web API. Getting required token goes O.K.:
WebClient client = new WebClient() { Credentials = new NetworkCredential(UserName, pass) };
StreamReader Reader = new StreamReader(client.OpenRead("http://localhost:" + port + "/gui/token.html"));
string token = Reader.ReadToEnd();
token = token.Split('>')[2].Split('<')[0];
// token is now something like 3LemfrO_-A-SNBXlnQ2QcQWTYydx7qOqKb1W1S54JJW74Ly3EYGgu0xQSU4AAAAA
But when I try to use it to get list of torrents:
Reader = new StreamReader(client.OpenRead("http://localhost:" + port + "/gui/?list=1&token=" + token));
all I get is "Error 400 Bad request".
I've tried to get token manually. In browser page "http://localhost:30303/gui/?list=1&token=3LemfrO_-A-SNBXlnQ2QcQWTYydx7qOqKb1W1S54JJW74Ly3EYGgu0xQSU4AAAAA" opens as it should, but in C# with the same link without any variables I still get error 400.
The interesting part is that if switch off token authentication WebClient load page perfectly with and without
"&token=3LemfrO_-A-SNBXlnQ2QcQWTYydx7qOqKb1W1S54JJW74Ly3EYGgu0xQSU4AAAAA"
but token auth enabled by default, so my and any app should use it.
And yes, WebRequest/HttpWebRequest didn't help also.
P.S. sorry for my English, I was never able to make it work right
you have to save the cookie from the request
Classes.CookieAwareWebClient client = new Classes.CookieAwareWebClient() { Credentials = new NetworkCredential("shehab", "shehab") };
StreamReader Reader = new StreamReader(client.OpenRead("http://localhost:" + "8080" + "/gui/token.html"));
string token = HtmlRemoval.StripTagsRegexCompiled(Reader.ReadToEnd());
MessageBox.Show(token);
Reader = new StreamReader(client.OpenRead("http://localhost:" + "8080" + "/gui/?list=1&token=" + token));
MessageBox.Show(Reader.ReadToEnd());
and for the cookie aware class go to the following link(Using CookieContainer with WebClient class) as web client doesn't support cookies.
You should save cookies from request
WebRequest request = WebRequest.Create("http://localhost:" + port + "/gui/token.html");
CookieContainer cookies = new CookieContainer();
(request as HttpWebRequest).CookieContainer = cookies;
And then use it in every other request to uTorrent when using the same token:
request = WebRequest.Create("http://localhost:" + port + "/gui/?list=1&token=" + token);
(request as HttpWebRequest).CookieContainer = cookies;
I have a simple 3-step suggestion:
When you use your browser with the token, use Fiddler2 to analyze the HTTP traffic between the server and browser.
Open up your C# app and use Fiddler2 to analyze the HTTP traffic between the server and your app.
Compare the HTTP requests and responses for the browser with the requests and responses for the C# app. If you see a significant difference, there is a good chance that could be the problem.

Categories