Missing credential from request in OOB application - silverlight

I'm writing a simple Silverlight application in which I have the following code, which I think is pretty standard:
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
var request = new WebClient();
var cred = new NetworkCredential(Server.UserName, Server.Password);
request.Credentials = cred;
request.UseDefaultCredentials = false;
request.DownloadStringCompleted += TestServerCompleted;
var uri = new Uri(Server.GetRequestUrl(Methods.ping));
request.DownloadStringAsync(uri);
Yet when I view the request in Fiddler, no credentials are added to the headers. What am I missing? Shouldn't there be an "Authorization: Basic ..." header in there?

Try with something like this.
HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.UseDefaultCredentials = false;
req.Credentials = ew NetworkCredential(Server.UserName, Server.Passwor
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
return req;
req.BeginGetResponse((IAsyncResult asynchronousResultResponse) =>
{
try
{
HttpWebRequest requestResponse = (HttpWebRequest)asynchronousResultResponse.AsyncState;
HttpWebResponse response = (HttpWebResponse)requestResponse.EndGetResponse(asynchronousResultResponse);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
//Your response is here in responseString
streamResponse.Close();
streamRead.Close();
response.Close();
}
catch (Exception e)
{
Callback(null, e);
}
}, webRequest);
I Hope it can help, even 2 months later...

Related

MSAL TokenAcquisition from the token stored in the file

I have saved initial usertakencache in a file. Now when I want to acquire the AcquireTokenSilent, I dont know how to use that saved token cache because all the documentation I find are used on the basis of cache but not for other memory formats.
I have searched on number of microsoft MSAL repos but they do not provide any help with the solution.
IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();
AuthenticationResult result = null;
StreamReader sr = new StreamReader("D:\\Test.txt");
string line = sr.ReadLine();
var accounts = await app.GetAccountsAsync();
string[] scopes = { "Mail.Read" };
try
{
// try to get token silently
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync().ConfigureAwait(false);
}
catch (MsalUiRequiredException)
{
ViewBag.Relogin = "true";
return View();
}
catch (Exception eee)
{
ViewBag.Error = "An error has occurred. Details: " + eee.Message;
return View();
}
if (result != null)
{
// Use the token to read email
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
HttpResponseMessage hrm = await hc.GetAsync("https://graph.microsoft.com/v1.0/me/messages");
string rez = await hrm.Content.ReadAsStringAsync();
ViewBag.Message = rez;
}

I am trying to send a request from anroid emulator. But the application is not giving proper output and breaking on client.sendasync

{
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")
};
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost(delibirately written)/Token");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
var response = await client.SendAsync(request);
var jwt = await response.Content.ReadAsStringAsync();
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(jwt);
var accessToken = jwtDynamic.Value<string>("access_token");
var accessExpires = jwtDynamic.Value<DateTime>(".expires");
Settings.AccessTokenExpiration = accessExpires;
Debug.WriteLine(jwt);
return accessToken;
}
I was getting exception first and then i used try catch and then i found out that application is breaking at client.async.

Post data to web API

I've been trying to send data to a web API VIA post. But it doesn't seem to be sending it.
Here's how I do it.
var baseAddress = "http://192.168.0.103/vchatapi/api/Images?gsmNumber=" + profileNumberLbl.Content + "&content=" + base64 + "&contentType=image/" + contentType;
var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
This code works with get:
var baseAddress = "http://192.168.0.103/vchatapi/api/SendSMSVerificationCode?gsmNumber=" + areCode + mobile + "&udid=123456";
var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "GET";
try
{
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
verificationCode = verificationCode.FromJson(content);
if (!verificationCode.Equals(""))
{
MessageBox.Show(this, "Verification Code: " + verificationCode);
verificationTextBox.IsEnabled = true;
areaCodeCB.IsEnabled = false;
mobileNumberTB.IsEnabled = false;
}
else
{
MessageBox.Show(this, "Invalid Number");
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message);
}
Any ideas? Thanks!
Since you are doing a POST, you would be sending the content in the body of the request. You would need to get hold of the request's stream and write data to it. The following answer post has a very concise example:
https://stackoverflow.com/a/2551006/1184056

Facebook Photo Upload in C#?

I am trying to upload an photo to Facebook from a Windows Phone Silverlight application using the Facebook Graph API but I am getting an error: (#324) Requires upload file. Can anyone see anything wrong in my code?
internal void PublishPhoto(System.IO.MemoryStream stream, string message, string accessToken)
{
var requestUriString = string.Format(
CultureInfo.InvariantCulture,
"https://graph.facebook.com/{0}/photos?access_token={1}&message={2}",
"me",
accessToken,
message);
var webRequest = WebRequest.CreateHttp(requestUriString);
webRequest.Method = "POST";
var boundary = "7db3d9202a1";
webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
webRequest.BeginGetRequestStream(new AsyncCallback(delegate (IAsyncResult result)
{
GetRequestStream(stream, boundary, result);
BeginGetResponse(webRequest);
}), webRequest);
}
private static void GetRequestStream(System.IO.MemoryStream imageStream, string boundary, IAsyncResult result)
{
var webRequest2 = result.AsyncState as HttpWebRequest;
using (var requestStream = webRequest2.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.WriteLine("--{0}\r", boundary);
writer.WriteLine("Content-Disposition: form-data; filename=\"sketch.jpg\"\r");
writer.WriteLine("Content-Type: image/jpg\r");
byte[] buffer = imageStream.GetBuffer();
requestStream.Write(buffer, 0, buffer.Length);
writer.WriteLine("\r");
writer.WriteLine("--{0}--\r", boundary);
}
imageStream.Close();
}
}
private static void BeginGetResponse(HttpWebRequest webRequest)
{
webRequest.BeginGetResponse(new AsyncCallback(delegate(IAsyncResult result2)
{
var webRequest2 = result2.AsyncState as HttpWebRequest;
try
{
using (var response = webRequest2.EndGetResponse(result2))
{
using (var responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
System.Diagnostics.Debug.WriteLine(reader.ReadToEnd());
}
}
}
}
catch (WebException we)
{
System.Diagnostics.Debug.WriteLine(we.Message);
using (var responseStream = we.Response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
var errorJson = reader.ReadToEnd();
var response = Newtonsoft.Json.JsonConvert.DeserializeObject<FacebookErrorResponse>(errorJson);
System.Diagnostics.Debug.WriteLine("Could not upload image to Facebook: {0}", response.Error.Message);
}
}
}
}), webRequest);
}
}
Try specifying a name of "source" as well as a filename in the Content-Disposition header, i.e.
writer.WriteLine("Content-Disposition: form-data; name=\"source\"; filename=\"sketch.jpg\"\r");
Ok, I was wrong the first time around, but now I have it.
The first problem, which we already took care of above, was that you were missing the "--" before each boundary and the "--" after the last boundary in the POST body.
The second problem is that you're not leaving a blank line after the MIME headers before writing the image content.
The third problem is that you're not flushing the writer before writing the image data to its underlying stream (unless silverlight on a phone is different from normal .NET in auto-flushing StreamWriters).
To sum up, this should work:
writer.WriteLine("--{0}\r", boundary);
writer.WriteLine("Content-Disposition: form-data; filename=\"sketch.jpg\"\r");
writer.WriteLine("Content-Type: image/jpg\r");
writer.WriteLine("\r");
writer.Flush();
byte[] buffer = imageStream.GetBuffer();
requestStream.Write(buffer, 0, buffer.Length);
writer.WriteLine("\r");
writer.WriteLine("--{0}--\r", boundary);

Silverlight HTTP POST

I am just trying to perform an http post on http://www.test.com/test.asp?test1=3. Here is the code I have been trying to use:
private void pif_test_conn()
{
Uri url = new Uri("http://www.test.com/test.asp?test1=3", UriKind.Absolute);
if (httpResult == true)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
}
return ;
}
private void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
MessageBox.Show("Using HttpWebRequest: " + resultString, "Found", MessageBoxButton.OK);
}
}
When I execute this code my program triggers the Application_UnhandledException event. Not sure what I am doing wrong.
Are you trying to post to another host? That behavior could lead to XSS security problems, so that isnt available.
string responseValue = "";
AutoResetEvent syncRequest = new AutoResetEvent(false);
Uri address = new Uri(HtmlPage.Document.DocumentUri, "/sample.aspx");
WebRequest request = WebRequest.Create(address);
request.Method = "POST";
request.BeginGetRequestStream(getRequestResult =>
{
// Send packet data
using (Stream post = request.EndGetRequestStream(getRequestResult))
{
post.Write(buffer, 0, buffer.Length);
post.Close();
}
// wait for server response
request.BeginGetResponse(getResponseResult =>
{
WebResponse response = request.EndGetResponse(getResponseResult);
responseValue=new StreamReader(response.GetResponseStream()).ReadToEnd();
syncRequest.Set();
}, null);
}, null);
syncRequest.WaitOne();
MessageBox.Show(
"Using WebRequest: " + responseValue,
"Found", MessageBoxButton.OK);
HTH
You can only send HTTP requests to the domain that your app comes from.
This restriction prevents XSS attacks.
With regard to Rubens' answer,
If you leave in the SyncRequest.WaitOne() call, the call deadlocks, at least in Silverlight 4.0.
In order to send an HTTP POST, you need to write the POST data to the request by calling the BeginGetRequestStream method.
This is probably why you're getting an exception; please tell us what exception you're geting for a more specific answer.

Resources