C#: How to GET an image from an API with credentials? - c#

I'm trying to make an API call using the simplest way possible:
<img src="http://IP-ADDRESS-TO-API/api/call/camera=1">
<img src="http://IP-ADDRESS-TO-API/api/call/camera=2">
IN CHROME: (the above code will pull the first image, but not the second almost every time)
IN EXPLORER: (the above code will only pull the first image AFTER prompting the user for the username and password)
The 'IP-ADDRESS-TO-API' is actually not the same IP or domain as where I'm calling it from. If I call the address from an AJAX call, I get a No 'Access-Control-Allow-Origin' header error.
I'm attempting to call this via C# to see if it can bypass this with the proper header sent in. Is there anyway to call this API call while passing in a username and password?
I've looked at examples of doing this via WebRequest but sadly, I can't see any methods of passing in credentials via the call itself. This as well as actually returning a proper image back to the DOM. Can anyone help?

Have you looked at the Credentials property of the System.Net.HttpWebRequest object?

Related

What is the purpose of th HTTP GET method in forms?

As far as I understand, the GET method asks the server to send something to the client's browser. I set up a HTTPListener in C# and when I access http://localhost:1330/form.html the request I get from the client is: GET /form.html which means that the client is saying "Hey server, I need the HTML code to display that page in the browser", which makes sense.
If I set a <form> with method=POST in form.html, the input fields values are located in the request body which is in context.Request.InputStream in C# which looks similar to this: input_name1=value&input_name2=value2&input_name3=value3... and the URL remains /form.html.
This also makes sense. The client says: "Hey server, take this data that was written in the HTML <input> elements" and the server uses it, maybe storing it in a database or computing something and send it back to the client.
Now if I set the form method to GET, the URL is modified to: /form.html?input_name1=value&input_name2=value2&input_name3=value3 and the context.Request.InputStream remains blank which is the opposite of the POST, in which the InputStream contained the data and the URL had no queries. For me, the GET method in forms doesn't make any sense. Why do we need to get the data from the form client side, send it to the server and then getting it back to client unmodified? Why do I send the data from the browser to C# and then sending it back to browser, if I can just get it client side using simple JavaScript?
In the moment the browser makes the GET request with the queries to the server, the client browser already has that data, so why does it ask the server to give it if it is already at the client's browser?
Generally speaking, an HTTP GET method is used to receive data from the server, while an HTTP POST is used to modify data or add data to a resource.
For example, think about a search form. There may be some fields on the form used to filter the results, such as SearchTerm, Start/EndDate, Category, Location, IsActive, etc, etc. You're requesting the results from the server, but not modifying any of the data. Those fields will be added to the GET request by the client so the server can filter and return the results you requested.
From the MDN article Sending form data:
Each time you want to reach a resource on the Web, the browser sends a
request to a URL. An HTTP request consists of two parts: a header that
contains a set of global metadata about the browser's capabilities,
and a body that can contain information necessary for the server to
process the specific request.
GET requests do not have a request body, so the parameters are added to the URL (this is defined in the HTTP spec, if you're interested).
The GET method is the method used by the browser to ask the server to
send back a given resource: "Hey server, I want to get this resource."
In this case, the browser sends an empty body. Because the body is
empty, if a form is sent using this method the data sent to the server
is appended to the URL.
An HTTP POST method uses the request body to add the parameters. Typically in a POST you will be adding a resource, or modifying an existing resource.
The POST method is a little different. It's the method the browser
uses to talk to the server when asking for a response that takes into
account the data provided in the body of the HTTP request: "Hey
server, take a look at this data and send me back an appropriate
result." If a form is sent using this method, the data is appended to
the body of the HTTP request.
There are plenty of resources online to learn about the HTTP protocol and HTTP verbs/methods. The MDN articles An overview of HTTP, Sending form data, and HTTP request methods should provide some good introductory reading material.

MVC HttpGet and HttpPost

Recently I have attended a training in mvc. The trainer said that - As per the security concerns we have to use HttpPost instead of HttpGet. Always use HttpPost.
Can anyone explain - what is the security issue when we use HttpGet?
When transmitting data over secure connection (https) body of the post request is encrypted and practically undreadable, you can only see address where data is going but not the data itself. Get on the other hand has no body and data has to be transmitted in either query string or as a path parameter. While it is true that query string does get encrypted as well, due to request logging on the server and browser it is possible to get hold of that data.
Anyone can insert image on public forum or stackoverflow with link to your web-site. Then happens next:
Browser looks at url in image tag
Browser find cookies corresponding to domain in url
Browser sends request to url with cookies of user
Your server performs action
Browser tries to parse response as image and fails
Browser renders error instead of image
But if you mark your action as Http Post only then this scenario isn't applicable for 90% of sites. But you should also consider that if hacker can create a form on other web-site then he still can make browser to perform request. So you need CSRF. Well, browsers made a lot to prevent cross-site requests, but it's still possible in some scenarios.

Pass data to a URL on a different web server without the QueryString

I've got an .ashx handler which, upon finishing processing will redirect to a success or error page, based on how the processing went. The handler is in my site, but the success or error pages might not be (this is something the user can configure).
Is there any way that I can pass the error details to the error page without putting it in the query string?
I've tried:
Adding a custom header that contains the error details, but since I'm using a Response.Redirect, the headers get cleared
Using Server.Transfer, instead of Response.Redirect, but this will not work for URLs not in my site
I know that I can pass data in the query string, but in some cases the data I need to pass might be too long for the query string. Do I have any other options?
Essentially, no. The only way to pass additional data in a GET request (i.e. a redirect) is to pass it in the query string.
The important thing to realise is that this is not a limitation of WebForms, this is just how HTTP works. If you're redirecting to another page that's outside of your site (and thus don't have the option of cookies/session data), you're going to have to send information directly in the request and that means using a query string.
Things like Server.Transfer and Response.Redirect are just abstractions over a simple HTTP request; no framework feature can defy how HTTP actually works.
You do, of course, have all kinds of options as to what you pass in the query string, but you're going to have to pass something. If you really want to shorten the URL, maybe you can pass an error code and expose an API that will let the receiving page fetch further information:
Store transaction information (or detailed error messages) in a database with an ID.
Pass the ID in the query string.
Expose a web method or similar API to allow the receiving page to request additional information.
There are plenty of hacky ways you could create the illusion of passing data in a redirect outside of a form post (such as returning a page containing a form and Javascript to immediately do a cross-domain form post) but the query string is the proper way of passing data in a GET request, so why try to hack around it?
If you must perform a redirect, you will need to pass some kind of information in the Query String, because that's how browser redirects work. You can be creative about how you pass it, though.
You could pass an error code, and have the consuming system know what various error codes mean.
You could pass a token, and have the consuming system know how to ask your system about the error information for the given token behind-the-scenes.
Also, if you have any flexibility around whether it's actually performing a redirect, you could use an AJAX request in the first place, and send back some kind of JSON object that the browser's javascript could interpret and send via a POST parameter or something like that.
A redirect is executed by most browsers as a GET, which means you'd have to put the data in the query string.
One trick (posted in two other answers) to do a "redirect" as a POST is to turn the response into a form that POSTs itself to the target site:
Response.Clear();
StringBuilder sb = new StringBuilder();
sb.Append("<html>");
sb.AppendFormat(#"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>",postbackUrl);
<!-- POST values go here -->
sb.AppendFormat("<input type='hidden' name='id' value='{0}'>", id);
sb.Append("</form>");
sb.Append("</body>");
sb.Append("</html>");
Response.Write(sb.ToString());
Response.End();
But I would read the comments on both to understand the limitations.
Basically there are two usual HTTP ways to send some data - GET and POST.
When you redirect to another URL with additional parameters, you make the client browser to send the GET request to the target server. Technically, your server responds to the browser with specific HTTP error code 307 + the URL to go (including the GET parameters).
Alternatively, you may want/need to make a POST request to the target URL. In that case you should respond with a simple HTML form, which consists of several hidden fields pre-filled with certain values. The form's action should point the target URL, method should be "POST", and of course your HTML should include javascript, which automatically submits the form once the document is loaded. This way the client browser would send the POST request instead of the GET one.

How to change the URL in the browser URL Bar

I am using server.transfer() method in my asp.net application to redirect the response. But I am running into the problem that it sets the previous page url (from where the original request for page was generated) at the browser url bar. I want to change the url in the browser. is it even possible??
I looked into it and i know that the Request has a url property but its read only. does any one know a way to change the url in the request?
Use Response.Redirect(); instead of server.transfer(); and it redirects in the browser.
If you can't do taht, you could use pushState (at least where it's aviable) to change the URL, but it seems a bit of a overkill...
The best way is clearly to change
server.transfer();
to
Response.Redirect();
EDIT
as you want to have the maximum performance, you could should use Response.Redirect with two parameters, and set the second to true.
so instead of
server.transfer(url);
you should have
to
Response.Redirect(url, true);
That causes the current request to abort and force a instant redirect.
Description
You can't change the Url of the Current request because it is already running.
I think you want to do a redirect.
The Redirect method causes the browser to redirect the client to a different URL.
Sample
Response.Redirect("<theNewUrl>");
Update
If you want to change the Url in the Browsers Address Bar without doing a requestion read this:
Can I change the URL string in the address bar using javascript
More Information
MSDN - Response.Redirect Method
Server.Transfer() is just changeing which content you send back.
Response.Redirect() is what you need to tell the browser to go to a new page
You cannot change the URL of a request - it would make no sense, the URL is what your client (the browser) has asked for.
No, you cannot change the URL in the browser like that. That would be a pretty massive security hole if you were able to do that. http://EvilDomain.com would be able to seamlessly masquerade as http://YourOnlineBank.com and no one would be any the wiser.

POST data to a Flex/Flash (mxml) application

I have Flex application requiring to filter users depending on there database groups. Depending on which group they are, the're is a config.xml file that is use to populate the swf.
Here is how I figure how to do this :
1. The client comes to a .aspx page with a form requiring a username and a password.
2. On the server side I confirm the user credential
3. Once the username/password is valid I redirect to the mxml file with the config.xml file in the html headers (post).
My problem comes when I need to get the post data from the http request. Let's say I have this code :
<mx:Application initialize="init()">
<mx:Script>
<![CDATA[
private function init():void
{
// get the post data here
}
/* More code here */
]]>
</mx:Script>
</mx:Application>
How do I get the post data on the init() function.
Thank you.
For those that would be interested, I've found some ressources on the Adobe Flex 3 Ressource center.
Basically there is no current way to pass data with the POST method. You can either add the parameters at the end of you swf url (GET method) as shown here : http://livedocs.adobe.com/flex/3/html/help.html?content=deep_linking_5.html#245869
The other way is to embed them in the page with the flashVars method shown here : http://livedocs.adobe.com/flex/3/html/help.html?content=passingarguments_3.html#229997
If you still wonder, how I'll manage to do this if you run to in the same situation. Here is my idea (feel free to share if you have different vision) :
1.User logs in login.aspx
2.Depending on the credentials of the users the server side code modify the index.html file to embed the correct xml file in the flash object.
3.With the FlashVars method, I get back the xml file path and job done!
If you ever run in a similar situation and need help contact me.
I don't think it's possible to get the POST data, but others might have a way. An alternative solution would be:
User logs in: login.aspx
User directed to Flash content: content.html embedding content.swf
Flash requests config.xml from server: content.swf makes HTTP request for config.xml.aspx
Server provides user's configuration in config.xml.aspx
In your init() function, you'd make the URLLoader request to get the configuration, and you'd do the configuration in the Event.COMPLETE handler.
Another possibility is to use HTTP cookies--not handled natively by Flash, but you can get to them via Javascript--see this CookieUtil class.

Categories