Classic asp not publicly available - asp.net

I need to call a classic asp page from .net, because I need the functionality of the classic asp page within my .net app.
The only way I know how to do that at the moment is like this :
MeetingCentres.Services.ClassicWhyGo.file_get_contents("http://someurl.asp?inputValue=£$%$£"%$£"%$£%)
public static string file_get_contents(string fileName)
{
string sContents = string.Empty;
if (fileName.ToLower().IndexOf("http:") > -1)
{ // URL
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
// Regular Filename
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
return sContents;
}
...but this means that the classic asp page is accessed over http and hence publicly available.
How ever I need to protect this page somehow as sensitive information is returned.
I would prefer to not have this asp page publicly available.
In IIS there doesn't seem to be the ability to make the page available only above the website root, as far as I know?
Otherwise if it must be public was thinking that I may be able to check the ip address of the calling.net app and make sure that it is on the same server.
Is there a better way to do this? or would the above be safe..?

You are able to modify the .asp page?
Do some tests like:
Check if the IP address are the same:
<%
if Request.ServerVariables("REMOTE_ADDR") = "127.0.0.1" then
'Do your stuff
end if
%>
Create a Cookie, store a encoded key and test it and only show the data if the value equals the key.
<%
Response.Cookies("key")=encodedKey
%>
Test the cookie
<%
if Decode(Response.Cookies("key")) = decodedKey then
'Do your stuff
end if
%>
This are just simples ideas.

Related

SSO with Azure ADFS and OWIN

Thank you for providing help. I have a site that can authenticate with Active Directory Federated Services for Single Sign On. Currently, the way my site works is that, by default, when a user hits my site, my code attempts to log then into SSO (I use the OWIN library for this). If the user is not on our network, it fails to authenticate, and they are redirected to my companies login page, where they can provide their company credentials.
I would like to change this behavior, though. Instead, when the user hits my page, if they authenticate, it should continue as normal and they should be redirected to my site. But, if they do not authenticate, I do not want them redirected to our login page. instead, I want them to be redirected back to my site, where my code will determine what they can and cannot do on the site. I then would want to provide a link, so that they could decide to go to the login page.
I want this behavior because the majority of users of this site will not be a part of the companies network and will not be able to authenticate. SO, they should, by default, just see our home page. But, there may be times when a company member might be working from home, so wont be on our network to auto authenticate. In this case, they would then use the link that sends them to the Azure login page.
Here is the code that I am currently using (site is ASP.net, form web page (not MVC)):
Startup.Auth.vb:
Partial Public Class Startup
Dim appSettings = ConfigurationManager.AppSettings
Private realm As String
Private aadInstance As String
Private tenant As String
Private metadata As String
Private authority As String
Public Sub ConfigureAuth(app As IAppBuilder)
Try
Dim appSettings = ConfigurationManager.AppSettings
If (appSettings("releaseVersion") = "DEBUG") Then
realm = ConfigurationManager.AppSettings("test_ida:RPIdentifier")
aadInstance = ConfigurationManager.AppSettings("test_ida:AADInstance")
tenant = ConfigurationManager.AppSettings("test_ida:Tenant")
ElseIf (appSettings("releaseVersion") = "PROD") Then
realm = ConfigurationManager.AppSettings("ida:RPIdentifier")
aadInstance = ConfigurationManager.AppSettings("ida:AADInstance")
tenant = ConfigurationManager.AppSettings("ida:Tenant")
End If
metadata = String.Format("{0}/FederationMetadata/2007-06/FederationMetadata.xml", aadInstance)
authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant)
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
app.UseCookieAuthentication(New CookieAuthenticationOptions())
Dim authOption As WsFederationAuthenticationOptions = New WsFederationAuthenticationOptions()
Dim fn = Function(context)
context.HandleResponse()
context.Response.Redirect("Home/Error?message=" + context.Exception.Message)
Return Task.FromResult(0)
End Function
Dim auth_not As WsFederationAuthenticationNotifications = New WsFederationAuthenticationNotifications() With {
.AuthenticationFailed = fn
}
Dim auth_opt As WsFederationAuthenticationOptions = New WsFederationAuthenticationOptions() With {
.Wtrealm = realm,
.MetadataAddress = metadata,
.Notifications = auth_not
}
If (Not auth_opt.Wtrealm Is Nothing) Then
app.UseWsFederationAuthentication(auth_opt)
Else
End If
Catch ex As Exception
Throw ex
End Try
End Sub
End Class
Then, on my Default.aspx.vb page load event, I do this:
If (Not Request.IsAuthenticated) Then
Try
Dim newAuth As AuthenticationProperties = New AuthenticationProperties()
newAuth.RedirectUri = "/"
HttpContext.Current.GetOwinContext().Authentication.Challenge(newAuth, WsFederationAuthenticationDefaults.AuthenticationType)
Catch ex As Exception
Throw ex
End Try
End If
The problem is, I do not know how to attempt to authenticate the user, determine if they are authenticated, and redirect them accordingly. Any help would be greatly appreciated.
thanks
There is not solid/correct way how to check if anonymous user is inside your network(or I am not aware of one). Possible way is to check IP address (range) users inside your network have publicly on the Internet. This is something you can check with network administrator(s). They may tell you public IP address (range).
Once you know public IP address (range) you can check incoming request to compare if the request is coming from the known reange of IP address (range) inside RedirectToIdentityProvider function.
Dim redirectToIdentityProvider = Function(context)
Dim isCompanyNetworkUser = companyIPAddress == context.Request.RemoteIpAddress
' Or relevant check for range
' Dim isCompanyNetworkUser = (companyIPAddressRangeStart < context.Request.RemoteIpAddress AndAlso companyIPAddressRangeEnd > context.Request.RemoteIpAddress
If Not isCompanyNetworkUser Then
context.State = NotificationResultState.Skipped
context.HandleResponse()
End If
End Function
Dim auth_not As WsFederationAuthenticationNotifications = New WsFederationAuthenticationNotifications() With {
.AuthenticationFailed = fn
.RedirectToIdentityProvider = redirectToIdentityProvider
}
You may want to tweak it a bit as I didn't try it, but may point you to right direction.
Sorry to not providing full code example, but in my opinion :
You may try to bypass the sign-in page prompts, take a look here, which explain you how to :
bypass the sign-in page prompts by adding your company’s existing federated domain name to the end of the Windows Azure Management Portal URL
You may also find usefull information relative to Azure Active Directory Pass-through Authentication which allow that:
When users sign in using Azure AD, this feature validates users' passwords directly against your on-premises Active Directory.
You may also make appear your website as an "application" then added this app to your Azure Active Directory application gallery. then Managing single sign-on for enterprise apps
I found finally that this question may be relative to your question.

"Bypass" login of a php page sending username and password from asp.net

I'm developing an intranet (WRITTEN IN C#) which is going to gather all software applications used in my company. Some of these applications are not internal (so I can't actually see nor manage the source code).
I have to "bypass" a login page of an external application (WRITTEN IN PHP), sending username and password from asp.net (my intranet).
I don't really know HOW to manage this, IF possibile..
I only know that it's expecting a $_POST["l_username"] and a $_POST["l_passowrd"].
I've been looking for a solution for hours now..and still..nothing seems to be working. I read maaany post but there are not useful in my case.
EDIT 1:
public void sendInfo(string url, string data)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = data;
byte[] postBytes = Encoding.ASCII.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
req.AllowAutoRedirect = true;
}
This is the code I've been trying to use when I click on the link (I'm using a LinkButton)..but it is not redirecting me to the page. It's supposed to redirect, logging in using the parameters I give in Data and show me the main page of the external application..any suggestions would be greatly appreciated!
EDIT 2:
I found a code which seems to be working, finally!
You can find it ->HERE<-.
I tried it using a simple Web Form (with a LinkButton) and a class, it works perfectly.
My problem now is that my intranet uses a MasterPage, and when I'm calling the method from a Content Page..nothing happens.
What can I do to have this code working on a Content Page?
You can specify the POST method for WebRequest (more details in this SO answer: curl Request with ASP.NET )
You should build a Request with the ASP.net WebRequest. You know which data to send, so that shouldn't be a problem!
At the end I used this ->code here<- and it worked just fine.
Couldn't understand why it won't work using master and content pages, but I managed without them.

How to manitain session values during HttpWebRequest?

In my code I'm sending a HttpWebRequest to a page in my website.
When request sends to this page, It doesn't maintain the Session values.
Below is the code, from where I'm generating the web request:
Public Overloads Shared Function ReadURL(ByVal sUrl As String) As String
Dim sBody As String
Dim oResponse As HttpWebResponse
Dim oRequest As HttpWebRequest
Dim oCookies As New CookieContainer
oRequest = WebRequest.Create("http://localhost:64802/inventory/purchase_order.aspx?id=5654")
oRequest.CookieContainer = oCookies
oResponse = oRequest.GetResponse()
Dim oReader As New StreamReader(oResponse.GetResponseStream())
sBody = oReader.ReadToEnd
oReader.Close()
oResponse.Close()
Return sBody
End Function
Below is the code written on Page_Load of Purchaseorder.aspx.vb:
iDomains_ID = Session("Domains_ID")
iLogin_ID = Session("Login_ID")
sPage = Request.Path
If Request.QueryString.Count > 0 Then sPage &= "?" & Request.QueryString.ToString()
sPage = shared01.Encrypt(sPage, Application("PK"))
If Not User.Identity.IsAuthenticated Or iLogin_ID = 0 Then
Response.Redirect("/login.aspx?page=" & sPage)
Exit Sub
End If
Above code doesn't gets the session values and it redirects to the login page.
So, how i can maintain the session on both pages during HttpWebRequest.
Looking for your replies.
EDIT
I've tried to use CookieContainer class as you can see in above code. But it doesn't work at all.
As an alternative, assuming the calling and called pages are in the same application, you could use the Server.Execute method to load the content of the page without making a separate request to the site:
Public Overloads Function ReadURL(ByVal sUrl As String) As String
Using writer As New StringWriter()
Server.Execute("~/inventory/purchase_order.aspx?id=5654", writer, False)
Return writer.ToString()
End Using
End Function
If I've understood you correctly, you're making a request from one page in your site to another, and you want to send the cookies from the current HttpRequest with your WebRequest?
In that case, you'll need to manually copy the cookies to the CookieContainer:
For Each key As String In Request.Cookies.AllKeys
Dim sourceCookie As HttpCookie = Request.Cookies(key)
Dim destCookie As New Cookie(sourceCookie.Name, sourceCookie.Value, sourceCookie.Path, "localhost")
destCookie.Expires = sourceCookie.Expires
destCookie.HttpOnly = sourceCookie.HttpOnly
destCookie.Secure = sourceCookie.Secure
oCookies.Add(destCookie)
Next
NB: You'll either need to make the ReadUrl function non-Shared, or pass the current HttpRequest as a parameter.
You'll also need to make sure the calling page has EnableSessionState="false" in the <%# Page ... %> directive, otherwise the page you're calling will hang trying to obtain the session lock.
Your code seems like you will need to make a request and a post. The first request will redirect you to your login page. The second will be a request where you post to the login page, which will start the session and (?) store information into the session variables. That post (to the login page) will then redirect you to the page you want.
I used code in this example http://www.codeproject.com/Articles/145122/Fetching-ASP-NET-authenticated-page-with-HTTPWebRe (I tweaked it a bit) to write an application to do this.

ASP.NET redirect not working with invalid URL with UIProcess application block - looking for redirect architecture ideas?

In my global.asax.vb file, I have code to re-write the URL if there is a prefix on the URL. We are introducing a new context in our application. So every page will either be of context hair or saliva.
Before the ASP.NET code (stack) even reaches this Global code, it calls an application block called UIProcess. It's code that Microsoft wrote years ago, and is no longer supported. The UIP block sort of mimics MVC, and you store all views, navigation and controller details inside the web.config. The UIP block is doing a redirect as shown below. Note, they had a known bug that was never fixed (commented out), so I had to recompile it before upgrading from .NET 2.0 to .NET 3.5. That's what I have commented out. That's the only bug I'm aware of.
private void RedirectToNextView(string previousView, ViewSettings viewSettings)
{
try
{
//if (previousView == null)
// HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ApplicationPath + "/" + viewSettings.Type, true);
//else
// HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ApplicationPath + "/" + viewSettings.Type, false);
if (previousView == null)
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ApplicationPath.TrimEnd('/') + viewSettings.Type, true);
else
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ApplicationPath.TrimEnd('/') + viewSettings.Type, false);
}
catch (System.Threading.ThreadAbortException) { }
}
Here is the Global.asax.vb code:
(again this code doesn't matter right now because it's not getting here YET with the exception being thrown)
Sub Application_BeginRequest(ByVal sender As Object, _
ByVal e As EventArgs)
' Fires at the beginning of each request
Dim originalUri As Uri = Request.Url
Dim rewrittenUrl As String = String.Empty
'Rewrite Saliva and Hair Testing urls
Select Case True
Case originalUri.AbsolutePath.StartsWith("/HairTest/")
rewrittenUrl = originalUri.AbsolutePath.Remove(0, 9)
If Not originalUri.Query.Contains("SampleTypeContext=247") Then
rewrittenUrl += "?sampleTypeContext=247"
End If
Case originalUri.AbsolutePath.StartsWith("/SalivaTest/")
rewrittenUrl = originalUri.AbsolutePath.Remove(0, 11)
If Not originalUri.Query.Contains("SampleTypeContext=3301") Then
rewrittenUrl += "?sampleTypeContext=3301"
End If
End Select
If rewrittenUrl <> String.Empty Then
'append the original query if there was one specified
If originalUri.Query <> String.Empty Then
If rewrittenUrl.Contains("?") Then
rewrittenUrl += "&"
Else
rewrittenUrl += "?"
End If
rewrittenUrl += originalUri.Query.Remove(0, 1)
End If
Context.RewritePath(rewrittenUrl)
End If
End Sub
The application is actually causing an exception above, when I try to pre-pend my URL (viewSettings.Type variable above) with "/HairTest" or "/SalivaTest". It causes that System.Threading.ThreadAbortException. I'm thinking because that path doesn't actually exist in our web application, but I'm just guessing. Notice, we're doing a re-write in our global, not a redirect. Our re-write prepends the URL with "/HairTest" or "/SalivaTest".
All of the pages in our web application expect that "SampleTypeContext" parameter if it needs it. If you can think of a way that will work better for this situation, let me know. I'll try to get more details on the exception.
Looking for ideas!! Our architecture approach is still up for discussion if we run into issues with this UIProcess block. We can't just get rid of the UIP block since it's used throughout our application, but I can modify the code above (in my first code snippet) if we need to.
There's no standard way to do this with the UIP block. And Microsoft doesn't maintain it anymore. I overloaded a bunch of the methods in the library to make it work. So that we can append a query string parameter (applicationScope) on each of our UIP redirect calls.
If you need the code, add a comment here, and I'll send you the source.

How to generate HTML email content with asp.net

I want to send emails in HTML format. How can I use asp.net to generate HTML content for emails.
Using output of .aspx page(Tried there was nothing in email body. Must be something in page that can't be used for email)
Using Webcontrol and get web control output and use it as email body.
Using custom http handler so can call handler to get email body.
Can you please suggest what would be the best solution?
Some guide or sample reference would be great if know one.
Thanks for all answers:
I am implementing code below:
string lcUrl = "http://localhost:50771/webform1.aspx";
// *** Establish the request
HttpWebRequest loHttp =
(HttpWebRequest)WebRequest.Create(lcUrl);
// *** Set properties
//loHttp.Timeout = 10000; // 10 secs
loHttp.UserAgent = "Code Web Client";
// *** Retrieve request info headers
HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();
Encoding enc;
try
{
enc = Encoding.GetEncoding(loWebResponse.ContentEncoding);
}
catch
{
enc = Encoding.GetEncoding(1252);
}
StreamReader loResponseStream =
new StreamReader(loWebResponse.GetResponseStream(), enc);
string lcHtml = loResponseStream.ReadToEnd();
loWebResponse.Close();
loResponseStream.Close();
I think the ASPX file will make the most easy to edit mechanism. You can use
var stream = new MemoryStream();
var textWriter = new StreamWriter(stream);
Server.Execute("EmailGenerator.aspx", textWriter);
to capture the output of that page.
I personally don't like any of your options. I would probably do it by using an HTML file (or a template stored in a database) and substituting something like {{name}} with the appropriate parameter.
I did this, essentially we had a page that the user could view, and then they could click a button and send the html on the page in an email. Basically my page was responsible for generating the email. I did this by overriding the Render method, and providing my own stream or using the one passed to us. We did this dpeneding on if we were rendering what the user would see or emailing it.
protected override void Render(HtmlTextWriter writer)
{
if (_altPrintMethod)
{
System.Net.Mail.MailMessage....
mailMsg.Body=RenderHtml(baseUrl);
}
}
protected virtual string RenderHtml(string baseUrl)
{
RemapImageUrl(baseUrl);
StreamWriter sw = new StreamWriter(new MemoryStream());
HtmlTextWriter writer = new HtmlTextWriter(sw);
base.Render(writer);
writer.Flush();
StreamReader sr = new StreamReader(sw.BaseStream);
sr.BaseStream.Position = 0;
return sr.ReadToEnd();
}
One thing to note is you have to make sure all links are fully qualified. You might be able to use the base functionality. this is what I was doing in the RemapImageUrl basically I appended an absolute path on all my image files.

Resources