I am new to ASP.NET and web application developing. What I'm trying to implement is, I am storing a file on the web server and is supposed to give the link of the file to the user for them to download the file. The link and the "downloading" process is easy but I wanted to make it more secure like having the link go through the login page, then the user will enter his/her credentials, if success, then the file will be automatically downloaded.
Does anyone know how where should I start or what is the name of this kind of method/processing for me to be able to start my research.
Thanks.
In the download page's Page_Load method check Session["IsLoggedIn"] or Session["LoggedInUserId"] where these session variables is set at your login page's BttnLogin_Click method.
Login.aspx
<asp:TextBox ID="TxtBxUserName" runat="server"></asp:TextBox>
<asp:Button ID="BttnLogin" runat="server" Text="Login" OnClick="BttnLogin_Click"/>
Login.aspx.cs
protected void BttLogin_Click(object sender, EventArgs e)
{
// guarantee that a user with the given username(TxtBxUserName.Text) exist
// find the id of the user
Session["LoggedInUserId"] = userId;
//or just do
Session["IsLoggedIn"] = 1;// I use 0 and 1 for this kind of job
}
Don't forget you need to set 0 to Session["IsLoggedIn"] and set -1(for an invalid id) to Session["LoggedInUserId"].
Now when you download page loads, just check one of these session variables.If the login condition is met then let the user download that file if not redirect to login page like below;
if(Session["IsLoggedIn"].ToString() == "1")
{
// download
}
else
{
Response.Redirect("Login.aspx");
}
donot put the link to that file directly. call an asp page which will read and write the file contents
to it's output stream. All this is done on page_load (sender, event); but before reading or writing the file contents, just check if there is a username or password or user id or whatever in the session variables. if there is nothing such, redirect to login.aspx.
You can use ASP.NET forms authentication to authenticate the user and after authetication process you can redirect the user to the download page.
You can employ forms based authentication. This is the standard way of handling a user login in asp.net. There are some easy to follow tutorials on the official Asp.net website: http://www.asp.net/web-forms/tutorials/security
Related
I created a new asp.net web application using the template that visual studio has. That type of project create a login out-of-the-box which I configured with the aspnet_regsql command to work with my database.
Now, when someone logs into the application, I need to know whether or not the login was sucessful, so I can save in Session[''] the user name among other things.
I was expecting to find a method that returns true or false but instead in the Login.aspx.cs is just the Page_Load method and I don't understand how it works.
I tried associated a onclick method that get the value of the UserName control, but obviously, that only works when the user log in for the first time, if the user check "Remember me next time" it won't work.
The AuthenticateRequest event is raised when the user has been authenticated, however in this event you do not have access to the SessionState yet. Therefore, to save the Session you should consider the PostAcquireRequestState application event.
ASP.NET Application Life Cycle Overview for IIS 7.0
ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0
For additional info:
AuthenticateRequest event
Example:
In global.asax
void Application_PostAcquireRequestState(object sender, EventArgs e)
{
if (Context.Session != null)
{
Application.Lock();
Session["user"] = User.Identity.Name;
Application.UnLock();
}
}
Additionally, if you are using the LoginControl, you can handle the LoggedIn event:
ASPX
<asp:Login runat="server" ID="login" DestinationPageUrl="~/Default.aspx"
FailureAction="RedirectToLoginPage"
onloggedin="login_LoggedIn" ...>
....
ASPX code behind
protected void login_LoggedIn(object sender, EventArgs e)
{
// set the Session here
}
The aspx web project template makes use of the asp:Login control, which does the authentication for you.
If you need to customize the login, you can roll your own username / password inputs, and then call the membership API directly, e.g.
if (Membership.ValidateUser(username, password))
{
FormsAuthentication.SetAuthCookie(username, rememberMe);
// Do your custom stuff here
...
You can also check to see whether the user is authenticated by using
UserPrincipal.Identity.IsAuthenticated
See MSDN for more details
I have a login control supporting "Remember Me" option.
The Markup
<asp:Login ID="UsersLogin" runat="server" OnAuthenticate="UsersLogin_Authenticate" DisplayRememberMe="true"
CssClass="usersLogin" FailureText="The username or password you supplied is incorrect"
Width="100%">
</asp:Login>
The Code-behind:
protected void UsersLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
Page.Validate(); // Executes the validation controls against the input controls.
if (!Page.IsValid) return; // Return from the function, incase validation fails.
e.Authenticated = Membership.ValidateUser(UsersLogin.UserName, UsersLogin.Password);
FormsAuthentication.RedirectFromLoginPage(UsersLogin.UserName, UsersLogin.RememberMeSet);
}
Steps performed and my observations (might be incorrect):
1). User enters the credentials and checks the "Remember Me" check box. ASP.NET will create a persistent cookie on the client side.
2). ASP.NET then navigates the user to some protected resource as indicated by "returnUrl" query string parameter, if available. Otherwise it will redirect the user to the page as specified in the "DefaultUrl" property of tag in web.config.
3). User closes the browser.
4). User reopens the browser, and types the url to the same protected resource. ASP.NET will grant access to that protected resource, because of the persistent cookie.
5). Now user navigates to the login page. ASP.NET should populate the username and password text box and also check the "Remember Me" check box.
The step 5 is where I am stuck. I'm not sure whether its the responsibility of ASP.NET to ensure step 5.
I'm aware this problem has been asked many a times, but I haven't found a reasonable solution, as many were just workarounds. Some solution suggested to create your own FormsAuthenticationTicket and add UserData to store the remember Me status. Rest suggested to explicitly write down the tag in web.config and explicitly specifying every parameter including timeout, path etc.
Also correct me on this statement:
"ASP.NET will delete the persistent cookie if we log out from the application, either by clicking the "LoginStatus" control or by having a normal link button and writing
"FormsAuthentication.Log();
FormsAuthentication.RedirectToLoginPage()"
on the click of normal link button".
Please advice, what needs to be done so that I can make the login control check the Remember Me checked.
Thanks in advance.
I think I have found the solution. This is what I did to get the check box checked.
if (User.Identity.IsAuthenticated)
{
FormsIdentity identity = User.Identity as FormsIdentity;
FormsAuthenticationTicket ticket = identity.Ticket;
if (ticket.IsPersistent)
{
UsersLogin.RememberMeSet = true;
}
}
If the user had checked the Remember Me check box, the ticket would be a persistent ticket.
Thanks anyways.
I have an ASP.NET page called admin.aspx that needs to be protected from direct access.
I want it to be accessed only when the user enter his name & password in another page called login.aspx.
I'm working in ASP.NET with Visual Basic .NET 2008, and I have no idea how to do it.
How can I do it?
The correct term for this behavior is Authorization
Some things I need to know beforehand:
Do you have your own Login / Logout Logic?
Are you using a custom User database / table?
If both of the above were answered with a yes: Have you read / heard something about Membership- and RoleProviders?
.NET has great built in mechanisms for solving this problem. It doesn't just offer great configuration possibilities, it is also very easy to implement!
Here is a very very detailed walk trough on the ASP.NET Membership Provider:
ASP.NET 2.0 Membership and Roles Tutorial Series
Even though it is using ASP.NET 2.0 and C#, it shouldn't really be that different on .NET3.5/4.0 and VB.NET
I found it :
In the login page ("login.aspx") do this :
Session("Name") = "Yes"
Response.Redirect("admin.aspx")
In the admin page ("admin.aspx") this :
If Session("Name") = "Yes" Then
'You can here display anything you want, or just leave it blank
Else
Response.Redirect("ErrorPage.aspx")
End If
You should check the user session first before loading your page:
protected void Page_Load(object sender, EventArgs e)
{
if (session == null)
{
// Just redirect to login page or no access page warning.**
}
if (!Page.IsPostBack)
{
//If your were logged in then you will access this page
}
}
You can handle it via Forms authentication. In your case you want to make sure that you restrict the access of admin.aspx so you can do so by giving that entry in web .config by specifying the location tag. Check out this site:
http://www.dnzone.com/go?60
HTH
we are running into an issue with our ASP server.
If you try to access a password protected page it does a security check and redirects you if you are not logged in, retaining the URL (ie. Members/MemberLogin.aspx?doc=/PodCast/Default.aspx)
The vb script places the "/PodCast/Default.aspx" in a variable and holds it until the login process is complete.
Once the user types in their username and password it is suppose to do a Response.Redirect(strRedirectURL) and go to the "/PodCast/Default.aspx" but instead it goes to the default.aspx page for logging in successfully.
The kicker is, I know the code is 100% correct becuase it was working on our previous server, but when we pushed all the data onto this server, everything works BUT that piece.
Any suggestions, would be great!
Thanks everyone!
Do you use custom redirection code? The default querystring parameter ASP.NET uses for redirection after login is ReturnUrl.
You gave the example: Members/MemberLogin.aspx?doc=/PodCast/Default.aspx.
Based on this, I would assume once logged in, the .net framework checks the value of Request.QueryString["ReturnUrl"] and finding it empty, so the site redirects to the base url.
If for some reason you are constructing a non-standard url using doc as your querystring parameter, you could hook into your Login control's OnLogin event, such as:
markup:
<asp:Login id="Login1" runat="server" OnLoggedIn="Login1_LoggedIn" />
code:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
string url = Request.QueryString["doc"];
if(!string.IsNullOrEmpty(url))
{
Response.Redirect(url);
}
}
If your postback mechanism (like a button) exists inside an updatepanel, you need to set the trigger
asp:PostBackTrigger ControlID="XXXX" /
I have an ASP.NET Role/Membership based forms authentication site. There's a subfolder and its pages which can be accessed only by a certain role. The problem is, login page does not display any error message if any user from non-allowed role group logins in login page. I mean, when a user from AllowedRole logins, the login page redirects the user correctly to the protected page, but when a user from NonAllowedRole tries to login, he/she correctly logs in but there are no error messages displayed, the user is back to the login page without any information. I do have a FailureText set in Login form but it's not displayed. loginForm.LoginError event is also doesn't get raised. I tried this code but it doesn't display either:
protected void frmLogin_LoggedIn(object sender, EventArgs e)
{
if (!User.IsInRole("AllowedRole"))
frmLogin.FailureText = "Access denied.";
//Label1.Text = "Access denied."; //doesn't work either
}
What am I doing wrong?
On thing you can do is check the ReturnUrl query string parameter and if it's you "denied" folder, redirect the user to either an error page or an allowed login page. Like this:
protected void frmLogin_LoggedIn(object sender, EventArgs e)
{
if (!User.IsInRole("AllowedRole") &&
InRestrictedArea(Request.QueryString["ReturnUrl"]))
{
Response.Redirect("Not-Allowed-Here.aspx");
}
}
Define InRestrictedArea to check if the requested area is where they aren't allowed.
I don't know where to find the documentation to support this. This answer is based on observation of the behavior I've seen io apps I've written.
The login page is exluded from the allowed access rules. It needs to be. Say you have a site where the whole site disallows anonymous users, even at the root level. The users need to be able to access the login page to be able to log in.
To resolve your dilemma you would need to add a label (I would call it lblError) and in your Page_Load, add the following (C# example code):
if(User.IsLoggedIn)
{
If(!User.IsInRole("AllowedRole")
{
lblError.Text = "Access denied.";
}
}
Added
Gving this more thought, the reason there is no error in the login page is that the error is happening when the user attempts to access the protected page, not within the login page.
However, I believe my suggestion will work for your situation as well.