Modifying AccessDenied.aspx - c#

I'm working on a website I didn't build. As far as I understand, AccessDenied.aspx comes with some default behaviour, such as the default error message for a failed login attempt is ''Your login attempt was not successful. Please try again.'
I want to change the message conditionally so it shows a different message if they have exhausted their login attempts.
I have some code in AccessDenied.aspx: <asp:Literal ID="msgFailedLogin" runat="server" EnableViewState="False"></asp:Literal>
When I try to access the fields from AccessDenied.aspx.cs using
msgFailedLogin.InnerText = "New text";
the compiler tells me
msgFailedLogin does not exist in current context.
I am able to access it using
((Literal)Login1.FindControl("msgFailedLogin")).Text = "New text";
Is there some built in behaviour interfering with my attempt to access this field using the typical convention of <id>.<method/property>?
I would include more code but none of it seems to be relevant.

Related

Query String Parameter Being Lost on Request

i'm developing an MVC 4 web application.
I'm trying to make an url that changes in an authorized/unauthorized context.
I'm generating the following url for unauthorized user:
http://localhost/vendas-web/Login?ReturnUrl=%2Fvendas-web%2FClienteNovo%2FIndex%299999
The first time I've tested, it worked just fine.
But.. the second time I've tried, the query string got lost.. and the url turned into:
http://localhost/vendas-web/Login
When i test it against chrome on anonymous tab, it works FINE.
When i change the value of the last parameter, it works FINE.
There's some sort of cache related to this ?
What i'm doing wrong ?
Soo, my question is:
How do i keep my full url in any scenario ??
Ty
There's really not enough information here, but what you're likely talking about is that the first time a user needs to be authorized, they are automatically redirected to the first URL, which includes the ReturnUrl bit. That's built into the framework to allow the user to be redirected back to that URL after logging in. However, if you need to persist this past that initial first redirect to the login page, that's on you. Any links must manually add the query string param:
#Url.Action("SomeAction", new { ReturnUrl = Request["ReturnUrl"] })
And any forms must include it as a hidden input:
#Html.Hidden("ReturnUrl", Request["ReturnUrl"])
Otherwise, yes, it will be lost, because the literal URL you're now requesting doesn't include it. It's not just magically appended.
My problem was cache...
I've used this annotation to avoid using cache by application.
[OutputCache(NoStore = true, Duration = 0)]

MVC Redirect to another page

I have a controller which processes an uploaded file.
In that controller, I return the user to a SharePoint list depending on the successful parsing of that file. I am able to enter a direct URL, but I am opening this page in a form so I need to change the window.top.location instead of just window.location. I tried doing this a few ways such as returning a JavaScript result, but I received some browser warning messages I'd like to avoid.
I ended up making a partial razor view which grabs a parameter from the query string in order to determine which list it should go to. The function works fine, but the page is seemingly inactive when I return it using:
return Redirect("~/Parsing/ParsingRedirector?List=MasterDealer");
My page exists in the folder, but I get an error stating "The resource cannot be found. "
Any reason why that's happening? I admittedly don't have a full understanding of MVC or even close to it at this point.
Try this:
return RedirectToAction("ParsingRedirector", "Parsing", new { List = "MasterDealer"});
This may be of help:
http://www.dotnet-tricks.com/Tutorial/mvc/4XDc110313-return-View()-vs-return-RedirectToAction()-vs-return-Redirect()-vs-return-RedirectToRoute().html
Keep in mind that, per that article, in the case of Redirect "you have to specify the full URL to redirect."

Did I Misuse the AntiForgery.Validate Helper from WebMatrix in One of My Pages?

After seeing the AntiForgery.Validate() method error (which it is supposed to do, when the form token does not validate), and visiting this site: http://msdn.microsoft.com/en-us/library/system.web.helpers.antiforgery(v=vs.111).aspx
for more information, it appears that I may have misused this in the past.
I have used the combination of AntiForgery.GetHTML(); and AntiForgery.Validate(); on a login page, but not sure if it makes sense to put it there. Without being logged in, the user is always "" (empty string), so I guess I originally thought that using the AntiForgery class did more than it really does. And, thus, is my question:
Am I right to assume that the only security check that the above practice performs is simply to make sure (by putting AntiForgery.Validate(); in an if(IsPost) branch) that the user who submitted the form is the same user who was logged in when the page was loaded?
If so, then, Am I also right in assuming that utilizing this class in this way has no place in a login page?
If you look at the source code on codeplex, AntiForgery uses AntiForgeryWorker which uses TokenValidator, the ValidateTokens method does do some identity and username checking. If you aren't getting an exception thrown, it might be doing some level of validation but using "" as username.
if (!String.Equals(fieldToken.Username, currentUsername, (useCaseSensitiveUsernameComparison) ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase))
{
throw HttpAntiForgeryException.CreateUsernameMismatchException(fieldToken.Username, currentUsername);
}
However, what is the use case for "forging" a login page? If the forger know the credentials to submit, they could just login themselves. It might not matter if AntiForgery doesn't work to its full potential here.

How to get Error code on custom error page

I have a common custom error page for my asp.net website because it's common it is shown on every error I want to found the last error code which was occurred and redirected to my that custom error page so that I can show right message according to the error which was occurred.
Note : solution have to be session based, I don't want any user to show error which was occurred on any other user's system of course.
Do you use IIS or Apache?
For Apache
Configuring Apache to serve customized error pages is extremely easy; there is a section of the httpd.conf file devoted to this. It takes just one directive per error to achieve. If you open the conf file and scroll right down to almost the very bottom of section two, you’ll see the section you need to edit.
By default, these directives are commented out, but all you need to do is un-comment each directive and then change the path to point to your own error page.
ErrorDocument 404 /errordocs/404error.html
For IIS
IIS 6: Edit Website or virtual Directory then Userdefinded Error.
There you can edit all error files and change to a user defined asp.net file.
IIS 7:
Detailed Error Message see:
http://blogs.msdn.com/b/rakkimk/archive/2007/05/25/iis7-how-to-enable-the-detailed-error-messages-for-the-website-while-browsed-from-for-the-client-browsers.aspx
Not good idea what you try to do. You must capture the errors on the code that they occur inside the page, and show the message on that page - stay on page - and if this is possible give the user the opportunity to correct it. If your error gets out of your try/catch and out of control then log it and fix it.
The only error that you can show to your user is the "non found page".
You can get the last error as Exception LastOneError = Server.GetLastError();
And there you can read more about errors: How do I make a "generic error" page in my ASP.NET application so that it handles errors triggered when serving that page itself?
and How to tell if an error captured by my global.asax was displayed on the screen of the user
What I would suggest is extending the UI.Page class and using that class for all your pages.
In that class (I know vb not c# but same principle and easy to convert) use the following code:
Public Class _PageBase
Inherits System.Web.UI.Page
#Region "Page Functions"
Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error
Session("error_StackTrace") = Server.GetLastError.StackTrace.ToString
Session("error_Message") = Server.GetLastError.Message.ToString
Session("error_Page") = Request.Url.ToString
Session("error_Source") = Server.GetLastError.Source.ToString
Server.ClearError()
Response.Redirect("~/errors/Error.aspx")
End Sub
#End Region
End Class
This will fire on all pages using that base class, and pass the last 'server' error (which will be the error the user caused), store all the details in session and pass it over to your error page. Then you can do as you wish.

Handling confidentiality in application

I have an asp.net mvc3 application where each logged users may have access to some specific data.
For exemple, "user A" have acces to "Client 1" but not "Client 2", while "user B" have access to "Client 2" but not "Client 1".
If user a acces to http://myApp/Clients/2, we will throw a custom exception, say ConfidentialityException.
From that, we can trap it in global.asax Application_Error. But from that point, I wonder what would be the best practice :
Returning an error page with http 403 code (how ?)
Just returning an error page.
Let it crash.
other suggestion ?
My preffered solition is the first one (error page with 401), but I don't see how to set the http code from Application_Error.
Edit
I changed 401 status code to 403, since it's not an authentification error, but confidentiality. 403 seems more appropriate according to w3c.
To set the status code you can use the following:
HttpContextBase.Response.StatusCode = 401;
However, if you're using MVC you can simply set the result to be an HttpUnauthorizedResult, which will set the http status code for you.

Categories