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.
Related
My application is in Asp.net MVC 4. I'm using .aspx page for opening of report. I've implemented custom user rights attribute on all action of application. I want to use it on my .aspx.cs page class or every function that is in .aspx.cs page. How to use it? can i use MVC custom attribute in aspx page
In mvc I'm using like this
[AuthorizeUserControls("urlInventoryReport")]
public ActionResult Inventory(string ReportTitle)
{
}
How to use in .aspx.cs page
public partial class ReportViewer : System.Web.UI.Page
{
[AuthorizeUserControls("urlInventoryReport")] //it's not working
private void ViewInventoryReport()
{
}
}
Attributes are static objects that apply metadata to a type in .NET. They contain no behavior.
The reason why your attribute works in ASP.NET MVC is because MVC has a filter which runs before and after the call to the action method is performed. This filter is called by the MVC framework, which in turn is called by the route handler (a specialized HTTP handler).
The fact that the behavior is defined in the same class as the attribute (yielding an ActionFilterAttribute) is just for convenience. You could just as well separate the attribute from the action filter as is done in this answer.
Following the MVC approach to make your IActionFilter function, would be to use .NET routing for your page and make a specialized IRouteHandler that can scan your page object after it is instantiated using Reflection to determine if the attribute exists, and then execute the behavior in the associated IActionFilter. I suggest if you go this route, you analyze the MVC source code and extract the bits that you need, but it is not for the faint of heart.
Alternatively, you could put the scanning implementation into the Page_Init event, but at that point you might just be better off not bothering with declaring the attribute statically and just executing the behavior locally.
Assuming your attribute derives from ActionFilterAttribute, you could do something like:
protected void Page_Init(object sender, EventArgs e)
{
var attribute = new AuthorizeUserControls("urlInventoryReport");
var filterContext = CreateFakeActionExecutingContext(); // TODO: Implement this.
attribute.OnActionExecuting(filterContext);
}
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.
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.
I would like to add a check for Request.IsAuthenticated into my MasterPage (COntroller? Is there such a thing??). Is this possible? I want to redirect to a NoAccess.aspx page if the check fails.
The concept on MVC is different to web forms where you would do common logic on the master.
In ASP.NET MVC master page must only contain UI related setup.
In MVC you use Action filters: decorate your actions with [Authorize].
Did you create a project using the default MVC project template? It has everything you're looking for already in there. If you didn't go ahead and create one now.
Once you're in there you'll notice the [Authorize] attributes as #Aliostad mentioned. These are custom attributes that do the validation on the controller level.
Check out the MVC tutorial on web form security for a more detailed run-down on how it all meshes together: http://www.asp.net/mvc/tutorials/authenticating-users-with-forms-authentication-cs
You can achieve this by creating your own custom authentication attribute.
Create a new filter folder within your project and add the following class
public class NoAccessDirectAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
filterContext.Result = new RedirectResult("noaccess.aspx");
}
}
then decorate your home controller and other required controllers with the Authorization Attribute
[NoAccessDirectAuthorizeAttribute]
public class HomeController : Controller
This will redirect an unathenticated user to your noaccess.aspx page
I have something issue on how to use Attribute in asp.net page class.
The below code slice is the background:
A method is declared like below in a aspx class page:
[SomeAttribute(Name=”Test”,TargetType=typeof(System.Int32)]
Public void Verify(object obj)
{
//code to verify…
}
And other pages would use the attribute too.
Now I want a Module to do is that it will invoke a method before the Verify method is calling.
Currently, my solution is using a customer IHttpModule implement class to do it by registering the BeginRequest event.
In the method referred to the event, how can I get the method that is calling currently by request in asp.net ? This is the way I could know the request is calling Verify method so that I can do something with the Attribute on it.
I'd recommend checking out PostSharp:
http://www.sharpcrafters.com/
It's got all that goodness, and more, built in.