Using URI with HTTPS - https

I wrote a program on UWP that stores text in a .txt file which is then voiced to the client. This worked really well when using an HTTP URI but now that site uses HTTPS the program crashes with the error:
System.Net.Http.HttpRequestException: 'Response status code does not indicate success: 401 ().'
The line that it crashes on is:
Byte[] bytes = await cli.GetByteArrayAsync(uriBing);
If I change the link to HTTP the program works fine again. Does anyone know how I can fix this please? Or is it just not possible?
var uriBing = new Uri(#"https://mydomain/net/hal2001/Actions/HALSpeak/speak.txt");
//set storageFolder as the location of the local app storage folder.
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
//Create a local file to be used to write the URL file to.
StorageFile sampleFile2 = await storageFolder.CreateFileAsync("status2.txt", CreationCollisionOption.ReplaceExisting);
//Write to local file the value stored in the URL file so they match.
var cli = new HttpClient();
Byte[] bytes = await cli.GetByteArrayAsync(uriBing);
If Have tried the following but still not happy.
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new System.Net.NetworkCredential("username", "pass");
HttpClient cli = new HttpClient(handler);
I checked the IIS server application > SSL Settings and SSL Settings is set to 'Require SSL' with client certificates set to Accept.

Related

Secure FTP Download not working in UWP

I tried using BackgroundDownloader class to download file from secure FTP server, but it doesn't download and also didn't throw any exception.
The below GetResponseInformation() is returning null.
I'm providing input URL as below:
ftp://username:password#hostIP/test.pdf
Code below:
Uri uri = new Uri(ftpUrlBox.Text.Trim());
StorageFile storageFile = await pickedFolder.CreateFileAsync("DownloadedFile.pdf", CreationCollisionOption.ReplaceExisting);
BackgroundDownloader backgroundDownloader = new BackgroundDownloader();
DownloadOperation downloadOperation = backgroundDownloader.CreateDownload(uri, storageFile);
ftpBar.Visibility = Visibility.Visible;
await downloadOperation.StartAsync();
ftpBar.Visibility = Visibility.Collapsed;
ResponseInformation responseInformation = downloadOperation.GetResponseInformation();
ftpStatusText.Text = responseInformation != null ? responseInformation.StatusCode.ToString() : string.Empty;
Kindly help how to download and upload from and to secure FTP server in UWP.
Note: If I use some 3rd party nuget library, FTP(S) download is working. But not with above UWP code.

Downloading a file from Azure Storage to client using Angular2 with .NET Web Api 2

I am trying to download a 1GB file from blob storage into the client. I used before Memory Stream and I get OutOfMemory exception.
now I am trying to open a read stream from the blob and send it directly to the client.
[HttpGet]
[ResponseType(typeof(HttpResponseMessage))]
public async Task<HttpResponseMessage> DownloadAsync(string file)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = await blob.OpenReadAsync("container", file);
result.Content = new StreamContent(stream);
return result;
}
The file is downloaded correctly, but the problem is: The code download the complete stream in the client, then the client sees the downloaded file.
I wanted the client to see the file as being downloaded, so the user knows that he is downloading something. Not just blocking the request and wait till it finished.
I am using FileSaver in Angular2:
this.controller.download('data.zip').subscribe(
data => {
FileSaver.saveAs(data, 'data.zip');
});
Has anybody an idea how to fix it?
Thank you!
To fix it you'd need to use the following javascript code instead:
var fileUri = "http://localhost:56676/api/blobfile"; //replace with your web api endpoint
var link = document.createElement('a');
document.body.appendChild(link);
link.href = fileUri;
link.click();
And then in your backend, make it like so:
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = await blob.OpenReadAsync("container", file);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "data.zip"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
I had the same problem.
The Solution I sorted out was -
First thing, the expected behaviour can occur only when client tries to download the file from blob and usually I prefer downloading the file from the client itself.
As in your case, try to get file blob uri and do some operations as below to open file in browser using Angular Router or simply window.location.href.
window.location.href = “https://*/filename.xlsx”
This worked for me.

Flutter: Copy image file from url to firebase

I'm trying to copy a user profile picture from an external service onto my firebase server. So far I have:
final File file = await new File.fromUri(Uri.parse(auth.currentUser.photoUrl)).create();
final StorageReference ref = FirebaseStorage.instance.ref().child("profile_image_${auth.currentUser.uid}.jpg");
final StorageUploadTask uploadTask = ref.put(file);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;
// add user profile picture url to user object
final userReference = FirebaseDatabase.instance
.reference()
.child('users/' + auth.currentUser.uid);
userReference.set({'photoUrl': downloadUrl});
The very top line gives me the error: Unsupported operation: Cannot extract a file path from a https URI
What is the correct way to do this? Should this even be done client-side? (Should I just be passing this url to firebase and use a function to download it server-side?)
File only supports files on a file system.
To load content using HTTP use the http package.
See also https://flutter.io/networking/
var httpClient = createHttpClient();
var response = await httpClient.get(url);
and then get the data from response.body,
or
var response = await httpClient.readBytes(url);
to get it as binary (Uint8List)
See also https://www.dartdocs.org/documentation/http/0.11.3+14/http/Client-class.html

(401) Unauthorized Error When Calling Web API from a Console Application

When I call my WEB API from my Console Application, I encounter:
The remote server returned an error: (401) Unauthorized.
This application runs in Interanet (Windows Authentication)
Uri uri = new Uri("http://myServer/api/main/foo");
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
using (Stream data = client.OpenRead(uri))
{
using (StreamReader sr = new StreamReader(data))
{
string result = sr.ReadToEnd();
Console.WriteLine(result);
}
}
Updated
If I replace
client.Credentials = CredentialCache.DefaultCredentials;
with this line
client.Credentials = new NetworkCredential( username, password);
it works fine but I need the current credential to be set automatically.
Any idea?
Thanks in advance ;)
You use the default windows credentials here
client.Credentials = CredentialCache.DefaultCredentials;
Specify the credential that you want to authenticate using the following code:
var credential = new NetworkCredential(, , );
serverReport.ReportServerCredentials.NetworkCredentials = credential;
following line is the cause of this behaviour :
client.Credentials = CredentialCache.DefaultCredentials;
Actually this line assigns the credentials of the logged in user or the user being impersonated ( which is only possible in web applications ) , so what I believe is that you have to provide credentials explicitly (http://msdn.microsoft.com/en-us/library/system.net.credentialcache(v=vs.110).aspx) , thanks.

WebClient NotFound error but working with HttpWebRequest/Response

In my WinPhone app I'm accessing a REST service.
At the beginnings I was using this code:
WebClient wc = new WebClient();
wc.Credentials = credentials;
wc.Headers["App-Key"] = appKey;
wc.DownloadStringCompleted +=
(o, args) => MessageBox.Show(args.Error == null ? "OK" : "Error");
wc.DownloadStringAsync(uri);
but it suddenly stopped working returning me a "The remote server returned an error: NotFound" error. After a google session and some clicks in the control panel, I didn't get it to work.
I decided to try this other way:
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Credentials = credentials;
request.Headers["App-Key"] = appKey;
request.BeginGetResponse(asResult =>
{
var response = request.EndGetResponse(asResult) as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
Dispatcher.BeginInvoke(
() => MessageBox.Show(response.StatusCode.ToString()));
}, null);
and it works.
I also tried to run the first snipped pointing the URI to google's home page and it works (I had to remove the credentials, of course).
Can anyone explain what's going on?
UPDATE
I managed to get it working by replacing the
wc.Credentials = new NetworkCredentials(username, password);
with
wc.Headers["Authorization"] = "Basic someBase64encodedString";
but i still wonder what happened and which are the differences between the first and the second line.
PS: the test URI is: https://api.pingdom.com/api/2.0/checks but you will need an app-key from them.
When using the Credentials property, the HttpWebRequest implementation will wait the challenge response from server before to send the 'Authorization' header value.
But this can be an issue in some cases, so you have to force Basic authentication by providing directly the Authorization header.
Example when using a REST Client library like Spring.Rest :
RestTemplate template = new RestTemplate("http://example.com");
template.RequestInterceptors.Add(new BasicSigningRequestInterceptor("login", "password"));
string result = template.GetForObject<string>(uri);

Resources