How to POST Data to another web application (cross domain) - c#

Please consider the following scenario,
There are two web applications App1 & App2. A user would submit his information on App1 though a form. On click of a specific button/link on App1, the same data should be posted to a page on App2 and the user should also be redirected to the same page on App2.
I would like some help in finding out the best way to implement this functionality.
One of the approaches that I have already tried out is by creating a temporary HTML form at runtime, setting the action attribute of the form to the App2 Page and get the form posted by using javascript submit. The data can then be fetched on App2 page by using the response.form object.
This approach works well, but i was still wondering if there is any other way to implement the required functionality.
I would really appriciate if you can give some insights on using RESTful webservices to implement this, or else, using some HttpModule to intercept requests at App1 and modify redirect response to app2 or any other approach that you might find fit for the purpose.
Edit:
Using querystring isnt an option for me.

I've had a need to do similar things with feed agregation and building rss feeds from web page content on different domains.
User Gets app1 page, fills in details and submits then on the server for app1 I have a method that looks like this ...
HTMLDocument FetchURL( string url )
{
WebClient wc = new WebClient();
string remoteContent = wc.DownloadString(url);
// mshtml api is very weird but lets just say you have to do things this way ...
HtmlDocument doc = new HTMLDocument();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
doc2.write(new object[] { remoteContent });
return (HTMLDocument)doc2;
}
This function does 2 things of use ...
It gets the page of content at "url"
It parses that content in to a HTMLDocument object
Once you have this function you can then call it passing it the url to the remote page and get back a html doucment.
The functions in the HTMLDocument object will allow you to do javascript like dom queries such as :
docObject.GetElementById("id");
I then have different functions that do different things with this object based on the page / site i'm returning data from.
There is however one fatal flaw here ...
This is likely to work really well with sites that don't change much in structure and are built by code but not so well on less dynamic sites.
With stackoverflow for example its easy to pull out a question and the accepted answer for that question so I could use this code to pull and publish content from here on my own web site.
However ...
This is not going to help you for user / login related details as this sort of information is not shared to generally everyone.
It's bit like me going and trying this to link facebook profiles to my own website, I would have to go through some form of api that asked the user to authenticate their details before making the request.
simply pulling a web page based on a url only will give the other site no authentication information unless that site accepts the user login details in the quesrystring and you already have them.
You may however be able to chain requests by ripping apart my sample method, requesting the login page parsing the results, filling in the form, then posting back using the same web client instance to login then requesting the url.
The idea being that you would have a form that asks the user to put in their login details for the remote site on your site then you go and find their profile page based on that.
This would be best farmed out to a class rather than just a simple method like i have here.
In my case though i was only after something simple (the bbc top 40 uk charts) which i pulled information from not only the bbc but places like amazon, google, and youtube, then i built a page :)
It's neat but serves no functional purpose other than pulling all your other fave sources of info on to 1 page.

If you are already committed to using javascript, then why not an ajax post, and change the window.location based on the response?

You can use HttpServerUtility.Transfer this will preserve your form contents and transfer the user to the new page.
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer.aspx

I have built something like what you are describing, and I found that using a <form> tag to POST to app2 is the most reliable way... basically, the way you found that worked well.

If App2 is residing on a different domain, it's usually best to create your own interface for the submission, and have that interface handle the posting from App1 to App2.
(Browser) -> Submits form to App1 ->
(App1) -> validate input
-> stores local info
-> creates an HttpRequest/POST object
-> posts to App2
(App2) -> handles the post
<- returns the response
-> confirms the results of App2
<- returns the results to the browser.
In essense, you want to control and proxy requests from your Applications domain to any outside interfaces as much as possible.

Note: I'm answering my own question
just to have a correct answers marked
against it. All the suggestions
provided by various members here are
correct in their own way, but they
were not apt for my requirements.
Hence, I cant accept any of them as
correct.
The way I have Implemented is by creating a custom control which would have a configurable property containing the URL to post data and another one accepting a dictionary object as the data input to be posted.
This control would internally create a HTML form with action attribute set to the URL specified by the user and have the data feilds created out of the dictionary object. This form would then be posted on the button click event on the page hosting this control.

Related

AngularJS - Get url in Server side in Application_BeginRequest

I am building an angularJs app and need to have application_beginrequest where I need to get current url in the browser.
E.g. localhost:60607/#/login : need to get /login
localhost:60607/#/activity : need to get /activity
Also whenever user hits a refresh or when page loads again and goes into beginrequest it should have the same response.
I tried with context.Request.Path but it gives "/" only.
bookmarks are not sent by browser to server, bookmarks are used for navigating inside the page. You have to get book mark using javascript and send it using different parameter to get that bookmark value at server side.
Data after "#" symbol is supposed to be client side only (usually browsers strip away those pieces, application servers usually ignore them).
If your intent is to provide users the ability to refresh the page using Angular you can:
Provide isomorphic behavior (load the page server side) but if you are using Angular JS ver 1.x is not as simple as you imagine
Provide double routing behavior (*):
avoid using the "#" symbol for url and provide user simple url like /login or /activity
manage your route client side using angular as you are supposed to do already
manage your route server side and provide the right view when requested
you can try to centralize the view management providing them using a controller instead of static content
Using the second approach is probably simpler, but you will find that:
keeping the view state is possible only for simple views (the things get complex quite quickly we introducing multiple UI element state)
to manage the double routing you have to find a compromise between client/server

Redirect links with a fragment (#) - asp.net

I have a website that contains links in different places, each link takes the user to a specific document.
Those links are hard-coded, which makes every update to the site very difficult.
Recently the documents were updated and we would like to update each old link with the corresponding new one.
For example
(http://www.domain.com/OnlineDoc/default.aspx#ItemID=3551)
needs to be updated to
(http://domain.docfactory.com/#!doc/Toolkits/Item1-Administration-Doc)
Each item document is determined using the ItemID.
What I'm trying to do is programmatically redirect each old link to it's corresponding new one.
I've tried to use the URL Rewrite module but it seems like it's ignoring everything after the "#", that is important because it determines which document we need to direct to.
My questions are:
Would the URL Rewrite module work? (having a fragment with "#")
If not, would the Http module work?
I'm trying to find a way to easily update the links, without going to each web app HTML and do it manually.
The fragment isn't sent to the server. It's accessible only to the browser. So you need a solution which involves the client-side.
But you can use the URL Rewrite Module in combination with client-side scripting in OnlineDoc/default.aspx that puts the fragment in the path or query part of the URL using a temporary client-side redirect. This makes the document item ID visible to the URL Rewrite Module, which can perform a permanent server-side redirect to the correct URL.
To clarify:
User requests /OnlineDoc/default.aspx#ItemID=123
Client-side scripting on this page issues a "temporary client-side redirect" (in actuality, just an automatic navigation) to /OnlineDoc/default.aspx?ItemID=123
User automatically requests /OnlineDoc/default.aspx?ItemID=123
URL Rewrite Module intercepts requests, and responds with a permanent redirect to docfactory.com/#!doc/Toolkits/Item1-Administration-Doc
User automatically requests docfactory.com/#!doc/Toolkits/Item1-Administration-Doc
The first redirect is temporary because you cannot make permanent redirects with client-side scripting. The second redirect is permanent because the new URL should always replace the old one.
The overall experience for users using this method could be a bit unexpected though, since users going to OnlineDoc will get redirected up to twice before they reach the intended document. Most users probably won't notice the second redirect, but the first will likely be noticable, if only slightly.

Transfer instead of redirect to login in forms authentication

I give to google a sitemap with all my pages, when the crawler tries to access them he gets redirected to the login page.
In the login page I write an explanation of what the page does so the crawler can see that each page is different.
The problem now is that the bot is clever enough as to recognize that it is a redirect:
URLs not followed
When we tested a sample of URLs from your Sitemap, we found that some URLs redirect to other locations. We recommend that your Sitemap contain URLs that point to the final destination (the redirect target) instead of redirecting to another URL.
HTTP Error: 302
If instead of using a redirect in RedirectToLoginPage(String), Microsoft had used a Server.Transfer, google would never find out it is actually the same page.
Any Ideas?
As Carl said, if access to your content requires a log in, then there isn't a whole lot you can do.
However, if you can separate out a "teaser" of each content page and have a link to "read more" from those pages that requires a login, then you'll be good to go.
The teaser page should have enough searchable text that google will be able to successfully include it in search results.
There are a number of sites that do just this. You search for something, click on the link to go to their site. Once there you can see maybe two paragraphs worth of information. If you want more a link takes you to a login / register page.
Okey I found a not elegant solution, but it suits my needs:
http://forums.asp.net/t/1358997.aspx
""For now, I found a workaround: I capture the End-request event and see if the status code is "302 redirected"; if it is, I'll just alter the address from there and do whatever I need to do. Not the most elegant solution (and requires more processing for every page request; not just login redirects), but at least it works.""

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.

How to secure AJAX request in ASP.NET?

I am developing an application in which I am displaying products in a grid. In the grid there is a column which have a disable/enable icon and on click of that icon I am firing a request through AJAX to my page manageProduct.aspx for enabling/disabling that particular product.
In my ajax request I am passing productID as parameter, so the final ajax query is as
http://example.com/manageProduct.aspx?id=234
Now, if someone (professional hacker or web developer) can get this URL (which is easy to get from my javascript files), then he can make a script which will run as a loop and will disable all my products.
So, I want to know that is there any mechanism, technique or method using which if someone tries to execute that page directly then, it will return an error (a proper message "You're not authorized or something") else if the page is executed from the desired page, like where I am displaying product list, then it will ecxecute properly.
Basically I wnat to secure my AJAX requests, so taht no one can directly execute them.
In PHP:
In php my colleague secure this PHP pages by checking the refrer of the page. as below:
$back_link = $_SERVER['HTTP_REFERER'];
if ($back_link =='')
{
echo 'You are not authorized to execute this page';
}
else
{
//coding
}
Please tell me how to the same or any other different but secure techique in ASP.NET (C#), I am using jQUERY in my app for making ajax requests.
Thanks
Forget about using the referer - it is trivial to forge. There is no way to reliably tell if a request is being made directly or as a response to something else.
If you want to stop unauthorised people from having an effect on the system by requesting a URL, then you need something smarter then that to determine their authorisation level (probably a password system implemented with HTTP Basic Auth or Cookies).
Whatever you do, don't rely on http headers like 'HTTP_REFERER', as they can be easily spoofed.
You need to check in your service that your user is logged in. Writing a good secure login system isn't easy either but that is what you need to do, or use the built in "forms authentication".
Also, do not use sequential product id's, use uniqueidentifiers, you can still have an integer product id for display but for all other uses like the one you describe you will want to use the product uniqueidentifier/guid.

Categories