Client side trouble when calling - asp-classic

Please use my previous question as reference. I have marked an answer already.
Question
I'm a .NET developer doing some work for a company that uses Classic ASP. My experience with server side development is VB.NET or C# with some sort of MVC pattern. Consider the following code snippet, I wrote it in an ASP page the company would like to keep and "include" in other pages where this web call would be needed. Kind of like a reusable piece of code. I've left some out for sanity reasons.
//Create ActiveXObject, subscribe to event, and send request
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
xmlDoc.loadXML(xmlHttp.responseText);
debugger;
var JSON = $.xml2json(xmlDoc);
parseResponse(JSON);
}
}
urlToSend = encodeURI(REQUEST);
urlRest += urlToSend
xmlHttp.open("GET", urlRest, false);
xmlHttp.send(null);
After struggling with a variety of security problems, I was glad when this finally worked. I changed a setting in Internet Options to allow scripts to access data from other domains. I presented my solution, but the Company would have to change this setting on every machine for my script to work. Not an ideal solution. What can I do to make this run on the server instead of the client's browsers?
I have a little bit of knowledge of the <% %> syntax, but not much.

This SO Question should help you call the service server side:
Calling REST web services from a classic asp page
To Summarise, use MSXML2.ServerXMLHTTP
Set HttpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
HttpReq.open "GET", "Rest_URI", False
HttpReq.send
And check out these articles:
Integrating ASP.NET XML Web Services with 'Classic' ASP Applications
Consuming XML Web Services in Classic ASP
Consuming a WSDL Webservice from ASP
You will also need a way to parse JSON

Related

Authentication prevents posting to Classic ASP from Web form using WebClient() from Code Behind

I am managing and old web site (site, not application) that is a hybrid of Web Forms and Classic ASP. The Classic ASP is being phased out, but that is probably a year away. Right now, we are dropping the old form of authentication in favor of Windows Authentication in the web.config.
The problem is that I am attempting to post to a Classic page from the code behind of a web form (http://www.blahsiblah.com/index.aspx) and am getting a 401 error.
var webClient = new WebClient();
var urlClassicASP = "http://www.blahsiblah.com/classic.asp";
var responseArray = webClient.UploadValues(urlClassicASP, "POST", nameValueCollection);
This throws "The remote server returned an error: (401) Unauthorized"
My question is, how can I post to the classic page without invoking the authentication of the dotNet side?
There are multiple ways to achieve this
Here is a simple suggestion that I hope helps
.Net
Use 127.0.0.1 (or your internal 192.169 / 10.1* ) IP to post to the page vs the public URL
Add a parameter (call it 'bypassauth' or something unique ) when sending the request to the ASP page
Add a parameter that identifies the user that you have authenticated in the .Net side
ASP
Find the include where the authentication check is happening and in that check, add another condition before returning 401 that checks two things
1) Request is from local/internal IP
2) Has the bypassauth parameter
3) the user id is valid
This way your old ASP code will still continue to work if requested from a browser and expect user to be authenticated however, when sending the request from .net will let you bypass authentication
I'm sure there are other ideas too, but this is just one approach
My solution was to set:
webClient.UseDefaultCredentials = true;

ASP.NET MVC with Forms Auth and WebApi with Basic Auth

I have a WebApi using Basic Auth nicely. And I have an MVC site using Forms Auth nicely. But here's the catch:
Client X has a dedicated database with any number of Contacts and Products. The MVC site is a dedicated site for them (via {clientId} routing), which allows their Contacts to log in (via Forms Auth) and place orders for their products. The Contact must be Form-ly logged in to place an order.
The product orders (need to) hit the WebApi to be recorded in the Client's database.
But since the WebApi uses Basic Auth to validate the Client, not the Contacts who placed the orders, every request comes back is 401 - Unauthorized.
I've checked out ThinkTecture as suggested by a number of posts here on SO, however it doesn't get me what I need because I'm not looking to allow Forms Auth in the WebApi. I don't want to authenticate the Contact from the Client's database in the WebApi, I want to authenticate the Client in the WebApi.
Has anyone come across a similar scenario and am I missing something glaringly obvious? Perhaps I need to implement both Forms and Basic on the site?
The very standard Api call I'm making from the site (where the UserName and Password are the Client's, not the Contact's):
var clientId = new Guid(RouteData.Values["clientId"].ToString());
var baseUrl = ConfigurationManager.AppSettings["ApiBaseAddress"];
var authHeader = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", _shoppingCartSettings.UserName, _shoppingCartSettings.Password)));
var requestUrl = String.Format("api/{0}/inventory", clientId.ToString());
var httpWebRequest = WebRequest.Create(baseUrl + requestUrl);
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authHeader);
httpWebRequest.Method = "GET";
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
try
{
using (var httpWebResponse = httpWebRequest.GetResponse())
{
// we never get here because of a 401
}
}
catch (WebException ex)
{
using (var httpWebResponse = ex.Response)
{
// we always get here
}
}
If I set up a separate test client and make the same call, it works great :/
Is your Web API under the same virtual directory and configuration as the MVC site? It looks like the Forms Auth HTTP module kicks in for your API, which you don't want. As long as you don't plan to call the API directly from the browser, move it to a separate virtual directory that is set up exclusively for basic auth, no forms auth module in the web.config for the API.
Why not have one login for your MVC site that has the ability to submit orders for every Client? It makes sense for your WebAPI to only allow Clients to submit orders for themselves. But I don't think it makes sense to have your MVC site authenticate as different Clients based on the Contact. Your MVC site would have to store the passwords for each Client.
Instead, create one login for the MVC site and give it the ability to submit an order for any Client.
After much banging of head against the not-so-proverbial wall, and a much needed shove by #0leg, I've discovered the cause.
In the Properties of my WebApi project file under Web > Servers, the Visual Studio Development Server was being used with a Virtual Path of "/", whereas my MVC project file was set up to use the Local IIS Web Server. The MVC project also had the Apply server settings to all users (store in project file) option checked.
Setting both to use the local IIS server resolved it.
Upon further contemplation, this now seems logical since they were essentially running on different servers.
Posting this for posterity's sake.

Jquery.Get ashx page

JS method
$.post('http://localhost:21067/HandlerServices/Product/ProductHandler.ashx', 'action=productlist', function (data) { console.log(data); console.log('hi') });
This ashx code is working but i recive nothing in response
This is ashx.cs code
context.Response.ContentType = "text/plain";
if (!string.IsNullOrEmpty(context.Request.QueryString["action"]))
{
string action = context.Request.QueryString["action"];
switch (action.ToLower())
{
case "productlist":
context.Response.Write("ersoy");
break;
}
}
I have query 1.9.0 version. In response tag not appeare anything.
Before i used it many times but now i cant understand where is the bug.
You are violating the same origin policy restriction that's built in browsers. Your ASP.NET MVC application containing this javascript file is hosted on http://localhost:2197 but you are attempting to perform an AJAX request to http://localhost:21067 which cannot work.
There are some workarounds such as using JSONP (works only with GET requests) or CORS (works only in modern browsers that support it). If for some reason you cannot use some of those techniques you could have a server side controller action inside your ASP.NET MVC application which will perform the actual call to the remote domain and act as a bridge between the 2. Then from your client script you will send the AJAX request to your own domain.

ASP.Net custom authentication with existing server

We have an existing user licensing server that is running via PHP. It allows for creation of users, checking if the provided username and password is valid, and updating a user.
We are creating a new ASP.Net website and want it to use this existing user PHP scripts/database to restrict access to portions of the ASP.Net website. Also there are web services that use the same login and password via basic authentication that we need to access as well from the ASP.Net server.
I am looking for a way for .Net to use the remote PHP scripts to validate login. And I need a way for the users login id and password to be available so I can use them to communicate with those existing web services from the ASP.Net server on their behalf.
Does anyone know how to go about getting this sort of thing done. Or any good tutorials or blogs?
Thanks!
It's possible to run PHP and ASP.NET on the same server, and even in the same web application. You can also create .NET code that runs before and/or after each PHP request (with an HttpModule).
PHP under IIS just has a separate HttpHandler that invokes the cgi-bin process.
If you want to call a PHP page from an ASP.NET page, one approach is to use Server.Execute() -- although web services would certainly be cleaner from an architectural perspective.
Beyond that, for the actual authentication/authorization part of your question, the approach depends on the specifics of your implementation. You can certainly do things like share cookies between PHP and .aspx.
unfortunatly they are different languages and php scripts cannot be used in an asp.net site. You would have to recreate your classes(scripts) but what you can do is use your existing database if its in mysql or any other. That's the best you would be able to do as far as I know.
If those PHP web services respect some industry standard such as SOAP for example, you can simply consume them by generating strongly typed client proxies. If not, well, then you still have the good old WebClient which allows you to send HTTP requests and read responses. It's as simple as:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "username", "john" },
{ "pwd", "secret" },
};
var result = client.UploadValues("http://foo.com/login.php", values);
// TODO: do something with the result returned by the PHP script
}
Have you tried using stored procedures instead of PHP scripts? That way you don't have to write multiple instances of the same code and it can be used in .NET and PHP.

How to prove the application working on web farm?

I have created a application that is the custom session mode and session bridge between asp and asp.net application. Now, I need to prove that is working or not. So, I have created an asp.net page. In this page, I had written this code.
System.Diagnostics.Process.GetCurrentProcess.Id
This produces worker process id. I can prove the application working on web farm due to changing worker process. But I don't know how to produce worker process id from classic asp. Please tell me. How can I get worker process id from classic asp?
Have you considered setting a custom HTTP Response Header on each of the IIS servers in the web farm then displaying the value on the page? Like so:
HttpContext.Current.Response.Headers["X-ServerName"]
Where X-ServerName is the custom HTTP Response Header on each of the IIS Servers.
EDIT:
Sorry, for Classic ASP you can try using javascript in the page to get the header.
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);

Resources