Inject JavaScript code from asp.net page into html page in another domain - c#

How can I inject a JavaScript code from asp.net page into html page in another domain e.g http://www.codeproject.com/ . how to inject a JavaScript into this html page from my application
I am currently working on making a plugin just like Pinterest when the html page opens from my application it shows a bookmarklet just like Pinterest automatically on the page.
Below is the code I am using to inject JavaScript
public partial class ViewPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string script = "javascript:(function(){var jsdom = document.createElement('script');jsdom.src = 'http://localhost:15064/Script/delete.js';document.body.appendChild(jsdom);})();";
Response.Redirect(Server.UrlEncode(script));
}
}
Below is the Error I get After the execution of above code

Same Original Policy will not allow you to run scripts in someone else's domain.If this did not exist anyone could run scripts in any domain which would be a major security risk.
There are a couple *legal exceptions to this rule which you can read below
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
The only other way to accomplish outside of an agreement with both sides would be a violation of Same Origin and probably illegal.
Xss attacks are pretty common and do what you are describing.

The closest you will probably be able to get is a bookmarklet:
http://www.mattcutts.com/blog/javascript-bookmarklet-basics/
which is basically a shortcut to inline javascript.
An example in the wild is the X-Ray Goggles bookmarklet. You can add it by creating a new bookmark and pasting the location as:
javascript:(function(){var script=document.createElement('script');script.src='https://goggles.webmaker.org/en-US/webxray.js';script.className='webxray';script.setAttribute('data-lang','en-US');script.setAttribute('data-baseuri','https://goggles.webmaker.org/en-US');document.body.appendChild(script);})();
This won't let you inject from your application but it is a way of injecting into a doc from your browser.

Related

Change Page URL Dynamically

I am writing an e-commerce website using DotNetNuke, and I have ran into a problem. For example I have a module on a page that has a URL of mydomain/productType/product-pages. What I would like is to pass a query string to this page with the item number of product (lets say its name is bacon). And when page loads, I would like both the breadcrumbs and URL(at browser) to read mydomain/productType/product-pages/bacon. I have researched how to change the page title, meta description, and all that already and have tested and it works - but just cannot find a way to modify the URL. I don't even know if this is possible. My goal is to not create all the pages for products within DNN, because this will change over time. I'm pretty sure I can create a page within DNN each time page is passed the query string which is a possibility, and another possibility would be have my other module create the link like it should read(just no page created) and DNN would just land on product-pages just add the /bacon? But I would rather just spoof the URL if possible.
Any suggestions or help would be greatly appreciated, and Thanks for reading.
Below is code snippet for changing the title and description:
protected void Page_PreRender(object sender, EventArgs e)
{
string pageName = Request.QueryString["pageName"];
if (!string.IsNullOrEmpty(pageName))
{
Page.Title = pageName;
Page.MetaDescription = "Blah";
Page.MetaKeywords = "Stuff,more stuff";
var url = HttpContext.Current.Request.RawUrl;
//Page.ResolveUrl(url + "/" + pageName);//this didnt work
//below is another way compared to top
//DotNetNuke.Framework.CDefault myPage = new
DotNetNuke.Framework.CDefault();
//myPage = (CDefault)this.Page;
//myPage.Title = "This is the new title";
}
}
The best way to manipulate the URLs for your custom module is by building a Extension URL provider. But you need to reverse your thinking about the problem. You don't want an ugly URL with a querystring argument to change into another URL. Rather, you start with the desired URL path and you want that to resolve or be "written" as the ugly querystring URL under the covers. That's what a Extension URL provider does.
I have a tutorial on DNNHero.com that walks you through it.
https://www.dnnhero.com/video/introduction-and-url-rewriting-basics
Unfortunately, that video is behind a paywall. (IMHO, it is worth the cost even for this one tutorial and code.)
You can also check out the blog:
https://www.dnnsoftware.com/wiki/extension-url-providers#:~:text=An%20Extension%20URL%20Provider%20is,and%20logic%20to%20be%20implemented.

Asp.net 4.5 Custom Attribute Webform

Using a Asp.Net old project, to access webforms I need to create a custom class Attribute that reads users rights like 'Rights.ViewDashboard' or 'Rights.CanEdit' an so. The class code is:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class AuthorizationAttribute : Attribute
{
public AuthorizationAttribute(Rights permission)
{
if (Security.IsAuthorizedTo(permission))
return;
HttpContext.Current.Server.TransferRequest("~", false);
}
}
In the aspx webform I have:
[Authorization(Rights.ViewDashboard)]
public partial class DashboardRisorse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
When the user calls the webform if he haven't specific right the page is not loaded and site is redirected to the default page. But if he make a refresh of the page the code isn't execute, attribute is ignored and the page is loaded. When debugging I see that this attribute is executed only once.
Where is my fault?
I don't need Net Core solution because the project has old assemblies.
Thanks.
Ingd
I am assuming here that you are trying to define custom attribute similar to ActionFilter Attributes in MVC. Unfortunately ASP.Net does not work in the same way.
You have two options
Create an HttpModule and use one of the events available to build your logic
Write the logic you want to execute in Page Load. Use Page.IsPostBack to identify if it is initial load of the page or if the page is being posted back. Write the logic you need within the if.. else if conditions
In case my assumption was incorrect then please provide more details on your query specifically what is it that you are trying to achieve using the Attribute.

Restrict URL to specific database username ASP.NET

I am making a website tool isch with ASP.NET Framework, that lets a user/customer preview their website.
I have a simple database that gathers a SESSION["username"] and creates a with the source to the customer project file.
But if I have multiple users how am I supposed to prevent users from accessing each other's files using the URL? like if the directory for the customer projects is ? "~/Customer/SESSION["username"]/Default.aspx and user1 enters user2 in the directory instead. I will post some content of the page here to make it easier to understand.
Directory of my project
In the Default.aspx page I direct everyone that is not the user "admin". And inside the Default.aspx i have an IFrame that looks like this <iframe id="contentPanel1" runat="server" /> and it gets its src attribute from my Default.aspx.cs that looks like this:
using System;
using System.Web.UI;
namespace MyFeedbackWebsite
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] == null)
{
Response.Redirect("~/login");
}
if ((string)Session["username"] == "admin")
{
Response.Redirect("~/admin");
}
this.contentPanel1.Attributes["src"] = "https://localhost:44350/Customer/" + Session["username"].ToString();
}
}
}
In my Admin.aspx.cs I check if the username = admin and if the user is logged in:
using System;
namespace MyFeedbackWebsite
{
public partial class admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if ((string)Session["username"] == null)
{
Response.Redirect("~/Login");
}
if ((string)Session["username"] != "admin")
{
Response.Redirect("~/Default");
}
}
}
}
And in the /Customer/ Directory I want the customers project to be located. But as I mentioned, if the directory is /Customer/user1/Default.aspxI want the user1 value to match the current session. Thanks beforehand!
Best regards Max
A few observations
Now, I don't know the background of this project you're working on, but it seems you are relatively new to some of the concepts, so I'll just list a few things for you to think about:
If this is a new project I would highly recommend you to stop and instead look at ASP.NET Core or similar. .NET Framework is slowly being replaced by .NET Core, so a new project based on .NET Framework (such as ASP.NET Web Forms) will quickly become outdated (if it isn't already from the start).
If this is just a spare time/personal little project, all good (except for above point) - playing around with it is a good way to learn. If it's a commercial or otherwise serious project, however, I would recommend you to read up on security best practices in web applications. Restricting access to a page using a construct like Session["username"] != "admin" is bad business and very error prone. Take a look here for an example of configuring which users or roles can access which pages.
The problem in question
It's still a little unclear to me what part of your code handles/is run when accessing /Customer/user1/Default.aspx. But I would recommend you, that instead of having the username be part of the URL, you are getting the username from the session in the backend instead, and then serving the proper page matching that username:
User accesses the URL /Customer/Default.aspx
Backend verifies that user is logged in. If not, user is redirected to login page
Backend gets the username from the session and returns the page <username>/Default.aspx (note: this is not a URL, but a file path or something similar that points to the page you are serving - the user never sees this)
Now, the user will not be able to see another user's page because /Customer/user1/Default.aspx is not a valid URL - /Customer/Default.aspx is.

Moving data from one web form to another ASP.NET C#

I am trying to move the content of a textbox on the from StudentRegistration to the form MyProfile by following a tutorial on YouTube. However when I try to reference the StudentRegitration Page in my code, I get the error that the type or namespace cannot be found.
In the tutorial I can see that in their code they have a namespace, however my website does not. Could anyone tell me what to do in order to be able to reference StudentRegistration without getting an error?
I should have stated that I have a website not a web app. I have found that websites do not have a default namespace. How would I go about accessing the StudentRegistration without referencing a namespace?
public partial class MyProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
StudentRegistration LastPage = (StudentRegistration)Context.Handler;
lblEmail.Text = StudentRegistration.STextBoxEm;
}
}
}
Rather than answer your question directly, I'd like to point out another issue with your code that will probably prevent it from working. You should refer to the documentation on the PreviousPage property at: http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage%28v=vs.110%29.aspx
It does NOT work like this:
user visits /StudentRegistration.aspx
user does stuff
user submits the form on /StudentRegistration.aspx
server redirects the user to /MyProfile.aspx
MyProfile class knows that PreviousPage = the class from /StudentRegistration.aspx
Instead, the description from the msdn reference page linked above stipulates that the PreviousPage property only works on this scenario:
user visits /StudentRegistration.aspx
user does some stuff
user submits form on /StudentRegistration.aspx
server transfers request to the MyProfile class
this does not mean that the url has changed to /MyProfile.aspx for the user, this means that the server is going to treat the current request to /StudentRegistration.aspx as if it were actually a request to /MyProfile.aspx
the user ends up seeing the result of what would normally be /MyProfile.aspx on /StudentRegistration.aspx
Now, your code may actually want that, but the fact that you have:
if (PreviousPage != null)
{
StudentRegistration LastPage = (StudentRegistration)Context.Handler;
// this should be
// StudentRegistration LastPage = (StudentRegistration)PreviousPage;
}
makes me think that you have misinterpreted the somewhat misleadingly named PreviousPage property. For a sample of how to persist state across multiple page loads in .NET, I would recommend reading up on SessionState. It has a somewhat complicated name, but does more of what you would want in this scenario:
http://msdn.microsoft.com/en-us/library/ms178581%28v=vs.100%29.aspx
An added bonus is that you do not need to reference one class from another, so you fix your current bug later on. Additionally, even if you did resolve your potential namespace error, the issue that I outlined earlier will cause the value of the text field to be blank if your code is working as I suspect.
You are sending data from a source to a target - e.g. StudentRegistration -> MyProfile
You have options because at the end of the day, it is HTTP. Aside from "persistence" (Session), and the tutorial you are following, a "simpler" way is to use ButtonPostBackUrl.
All it means is that you are POSTing data to the target page. The target page (MyProfile) will have to validate and parse the posted data (Request.Form). This way you don't have to manage things like Session state.

Is it possible to have a single URL that points to two different pages?

I have one url (/settings) that needs to point to two different pages depending on the users security on login. One page is the existing webforms page the other is a new MVC page. Is this even possible?
Additional Info:
When the user is on either page the url needs to say website.com/settings
Solution:
Convinced the PM to change the requirements.
The short answer, yes. You can do this several ways.
Javascript
Model View Controller (Controller)
ASP.NET Web-Forms (Method)
It is often poor practice to do such an event, as it can expose data. It is indeed possible:
Javascript:
$(document).ready(function () {
if($("#Account").val() != '') {
$(".Url").attr('href', 'http://www.google.com');
}
});
Pretend #Account is a hidden field that is populated from your database. If the field is not null then modify the .Url element to navigate to link. That approach for Web-Forms is the most simple.
Web-Forms:
protected void btnAccount_Click(object sender, EventArgs e)
{
if(User.IsInRole("Account"))
Response.Redirect("~/Admin.aspx");
else
Response.Redirect("~/User.aspx");
}
That would use the default Windows Authentication for the domain, you could bend and contort to use the database to pull data. An example, the Model View Controller would be similar as the Controller will simply handle that capability.
Hope this points in right direction.
This is a redirects based approach. Create a web page mapped to /settings, and have this code run on page load.
if(User.IsAdministrator()) //I take it you have some way of determining who is an Admin, so this is just example code
{
Response.Redirect("~/AdminSettings.aspx");
}
else
{
Response.Redirect("~/UserSettings.aspx");
}
Note that you'll need security on the Admin page to make sure a regular user can't just navigate directly there.

Categories

Resources