Sessions in asp.net - asp.net

i have a login page so once the user enters the correct details he enters into the home page. Now i want to implement 3 things
once he clicks the button 'log out' he must be redirected to a page saying" logged out successfully " n even if clicks the back button in the browser, he should not be able to access.
if the user leaves the homepage idle for a specific amount of time say 10minutes and then he tries to navigate after 10 mins a msg should display saying "Your Session has been expired login again"
if given the url of homepage he shouldnt be able to access unless logged in.
I am not sure about what exactly i need to do and how to do. Plz Help
Regards
Indranil Mutsuddy

1) When the user logs out of the system I would recommend doing a Session.Abandon(). If the user clicks the Back button in the browser he might see the cached version of the old page (this is entirely browser dependant), but he won't be able to do anything anyway.
Disable the caching in your pages and the user shouldn't even see the cached old version :)
A simple way to do this would be to add the following into Global.asax's Application_BeginRequest:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
2) In your web.config set the session lifetim to 10 minutes, incremental.. That will do the trick
<system.web>
<authentication mode="Forms">
<forms defaultUrl="~/LoggedIn.aspx" loginUrl="~/Login.aspx" protection="All" path="/" slidingExpiration="true" timeout="10"/>
</authentication>
</system.web>
3) You can do this using authorization rules in web.config. If you want no anonymous users to access your website just enable access only to logged in users like this:
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
If you want to restrict access not to the whole website, but only to some areas (like the MyAccount area, then you can add this instead.. Note: Web.config can have multiple <location> elements!
<location path="MyAccountFolder">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
There's one important note about the location tag. The Path does NOW start with a '/'! So if you want to secure the /MyAccount folder, then your tag will start like this:
<location path="MyAccount" />

You should generally use ASP.NET Forms Authentication for this.
When the Log Out button is clicked, call FormsAuthentication.SignOut. This will remove the forms-authentication ticket information from the cookie (or URL if cookieless).
For a timeout, use the timeout attribute in the system.web/authentication/forms element of your web.config. Note that your forms authentication timeout is independent of your Session timeout.

Case 1:
When clicked on the log off button clear the Session.
Clicking the back button in the browser might result in fetching the page from the cache. So by cheking Session in the page might not be effective. You can disable caching for the page so that when back button is clicked a new request to the page will be generated.
For pages not to be cached set this
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Case 2:
You can set the default timeout for Session as 10 minutes. See HttpSessionState.Timeout Property
Case 3:
Check Session for null and if found to be null then redirect to a login page.

Related

ASP.Net authentication: Can I have multiple responses when user fails to authenticate/authorize to access a page

I am using ASP.net form authentication for my web application. I have folder "admin" for administration work, and also I can lock one user if he/she misbehaves.
currently if an normal user tries to access the admin page, it will be redirected to the logon page, although he/she is already logged on.
The question is: how can I configure the web app, so that when the user fails to access a page, I can show different pages such as "you need admin privilege to access this page"/"your account is locked out"/(normal logon page)?
ValidateUser() can only return bool. :(
Thanks a lot
You'll need to implement roles and add people to them. Once you assign people to the proper roles, you would check to see if the person is in the proper role to access a page. If not, redirect them or show the proper error message. You would be able to do this with code behind like it seems like you are already trying:
if(!Roles.IsUserInRole("Administrator")) Response.Redirect("~/");
Or you can use the web.config
<configuration>
<location path="memberPages">
<system.web>
<authorization>
<allow roles="Administrator" />
<deny users="*" />
</authorization>
</system.web>
</location>
<configuration>
See the links below for more info:
https://web.archive.org/web/20210417083524/https://www.4guysfromrolla.com/articles/121405-1.aspx
http://msdn.microsoft.com/en-us/library/ff647401.aspx
I solved this kind of problem giving different urls to diffenrent roles.
To admin you give www.yoursite.com/admin
to user you give www.yoursite.com/private
asp.net will automatically redirect both to the login.aspx page but you can get from the url parameter which kind of user it is.
//I detect where the request originated from
string str = Request.QueryString["ReturnUrl"] == null ? "" : Request.QueryString["ReturnUrl"].ToString();
//if this is Admin can access to Admin Area only
if (str.Contains("Admin") == true || str.Contains("admin") == true || str.Contains("ADMIN") == true)
{ .......

asp.net forms authentication redirect problem

The default document feature is turned off in IIS and here's the situation...
My start page for my project say is A.aspx. I run the project and sure enough, A.aspx appears in the url of the browser. Like it should though, A.aspx finds no user logged in and redirects to Login.aspx like it should.
A.aspx:
if (Session["UserStuff"] == null)
Response.Redirect("~/Account/Login.aspx");
The login.aspx shows up BUT when the user Logs in, the code:
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
always redirects to "Default.aspx" and not "A.aspx"
I've examined FormsAuthentication.GetRedirectUrl and sure enough it returns "Default.aspx"
I'm stumped????
In web.config you could set the default page using the defaultUrl attribute:
<authentication mode="Forms">
<forms
loginUrl="login.aspx"
defaultUrl="a.aspx"
protection="All"
timeout="30"
/>
</authentication>
http://www.codeproject.com/KB/aspnet/custom_authentication.aspx Follow this
If you're using FormsAuthentication, your settings should be defined in the web.config. It sounds like you have a default setting in the web.config for DefaultUrl. You shouldn't need the session redirect though. FormsAuthentication should perform this for you. It doesn't hurt to check the session and force a SignOut() if you don't find it, but FormsAuthentication should perform this redirect.
From my understanding, when the user is redirectoed to your login screen, the Forms Authentication mechanism will add the url of the page that the user was originally tring to access, to the login url that that they user tried to access. For example, if you had a login page: http;//bob/login.aspx, and a user tried to access http;//bob/showmethemoney.aspx, then they would get redirected to http;//bob/login.aspx?ReturnUrl=showmethemoney.aspx. So, if you use the ReturnUrl to redirect the user after the user logs in, the user will always be returned to the resource that they were originally trying to get to.

Strange logging off on ASP.NET 3.5 website

Please help me I'm getting desperate here trying to find the problem, and I don't know where to start looking for it.
Here are the symptoms:
I've noticed, that when a user logs on in the morning, he is then immediately logged off, then when he logs on again, everything is fine and he can work on the site.
Every once in a while, when the user clicks a link, the page takes a lot of time to load, but it never actually loads, and the user is thrown to the login page.
Also, after an Exception has occurred in the website, the user is then thrown to the login page. It's as if the exception clears somehow the session.
Do any of you know of a situation where this might happen ?
The code I use in every page in my application is as follows :
If (Not User.Identity.IsAuthenticated) Then
Response.Redirect("../login2.aspx")
End If
' If session timeout then return to login screen '
If ((Session("LocationId") Is DBNull.Value) Or (Session("LocationId") Is Nothing))
Then
Response.Redirect("../login2.aspx")
End If
The code in the web.config:
<sessionState cookieless="false" timeout="600" />
<authentication mode="Forms">
<forms timeout="600" />
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
Why are you using that code in every page?
.NET authorization and authentication normally takes care of all those things if you have it set up correctly.
Related to this scenario *`
".... after an Exception has occurred
in the website, the user is then
thrown to the login page. It's as if
the exception clears somehow the
session
I know of one possible situation where it may occur.
It is far fetched especially in a production scenaio for multiple reasons but i have seen it happen :-)
If the session is In Memory and logging is done by writing to a log file that is in the Bin directory of the application, then this may occur as modifying the bin folder of the web application results in the application restarting i.e the in memory session getting lost.
Just one possible scenario. If your session is not in Memory OR your logging mechanism isnt like this, then this doesnt apply to you.
I am turning to all the dot net experts out there because I am really desperate,
let me give another symptom of the problem because it still persists,
the server is a very strong server - intel xeon with a 3 gb ram, so it is probably not a problem of resources.
When the user uses the system continuously there is no problem and she can work freely, the problem arises when the user leaves the computer (or the application for that matter) for as long as 5 minutes, then when she wants to continue working and clicks a link in the application she is thrown to the login page. when she tries to login again, she succeeds, but after she clicks another link, she is thrown out again, then when she logins she can work freely and everything is fine.
Somehow the session is being cleared when the site is idle. let me emphasize that this doesn't happen when I run the app in visual studio, only in iis.
The app was converted from asp.net 2.0 to 3.5,
that's it, thanks
First of all, you need to deny access for non-authenticated (anonymous) users:
<authorization>
<deny users="?" />
</authorization>
Have you configured default and login pages?
<authentication mode="Forms">
<forms name=".ASPXFORMSAUTH" loginUrl="Login.aspx" defaultUrl="Default.aspx" slidingExpiration="true" timeout="30" />
</authentication>
name sets the name of a cookie, useful if you will use .NET 2.0 built-in security infrastructure (roles, membership, etc)
slidingExpiration enabled normal timeout behavior - any user action resets timeout
If you are just using the normal session functionality in asp.net I believe that the session times out after 15-30 minutes of inactivity (I typically don't use session so I remember it is somewhere in this range). Every postback to the server resets this timer so if a user is active doing things then they won't hit this time out.
For the page taking a long time to load it is most likely due to the worker process recycling and that user is the first user to access the site after a recycle which triggers IIS to do all of it's compilation stuff and then serve the page which causes the delay. This only happens for the first visitor after a worker process recycle. You can change this behavior in IIS to happen on a schedule rather than after a certain amount of time has passed without activity. This will cause your worker process to take up more memory though so depending on your environment this might not be a good change to make.
EDIT: I should add that the code you posted explains exactly why the user is kicked back to the login page. It is checking to make sure that there is something in the session and if there isn't anything there it kicks the user back to the login page. So if they are inactive for too long your session times out, so it is cleared, and the user is kicked back to the login page by your code. Also you should use FormsAuthentication.RedirectToLoginPage(); for your redirect instead of Response.Redirect. This way after logging in they go back to the page they requested originally.

Why Response.Redirect("Pagename.aspx") doesn't work

I have one application where after successful Login user will be redirected to Home.aspx.
Now if I try Response.Redirect("Home.aspx") it doesnt work, But if I try
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);..its working.
Now my question is why Response.Redirect() is not working?
I know FormsAuthentication.RedirectFromLoginPage do much more than Login, it also sets cookie,and also redirects to Login Page, but why Redirct() is not working?
web.config:
<authentication mode="Forms">
<forms loginUrl="LogIn.aspx" defaultUrl="Home.aspx" path="/"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Can somebody help?
You already have the answer pretty much.
Response.Redirect does not set the authentication cookie so when Home.aspx is loading it fails authentication and will redirect you back to the login page.
To use response.redirect, you will have to manage the cookie yourself, an example from https://web.archive.org/web/20210513002246/https://www.4guysfromrolla.com/webtech/110701-1.3.shtml is:
Dim cookie As HttpCookie = FormsAuthentication.GetAuthCookie(UserName.Text, _
chkPersistCookie.Checked)
Response.Cookies.Add (cookie)
Response.Redirect(FormsAuthentication.GetRedirectUrl (UserName.Text, _
chkPersistCookie.Checked))
EDIT:
To answer the question in your comment, if you pass true as the second parameter to RedirectFromLoginPage then the cookie will be set to never expire, and you won't need to login again.
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, true)

After doing FormsAuthentication.SignOut(), user is not able to login again

I am using formAuthentication with the following Web.Config file.
<authentication mode="Forms">
<forms name="SnowBall" timeout="30" slidingExpiration="true" loginUrl="Login.aspx" cookieless="AutoDetect">
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
I have a user control which has a LogOut button. Code of the logout button is:
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
After executing this code, I am no longer able to authenticate the user. When i click "Sign In", the page is refreshed and event handlers are not executed.
When I close the browser window and re-run the site, everything works fine. Please help me.
First you need to clear that there are two separate Ids one is session id which is alloted for browser session and another is form authentication cookie which is encrypted alphanumeric id.
Whenever you use formauthentication.signout your formauthentication cookies will removed as per your implementation.But your session id will remain there.
You cancheck it by using fiddler/ firefox browser.
I have found the solution.Hope it helps somebody out there
Problem lies with this line
Response.Redirect("Login.aspx");
What it does is redirects user to Login.aspx with ReturnUrl as querystring.For Eg.
Login.aspx?ReturnUrl="Name of the page from where logout happened";
Now what happened was that FormsAuthentication.GetRedirectUrl() preserved this querystring path and after authentication was redirecting to this path.the user credentials i was putting in were not authorized to view this page.So i was always on the login screen.
To Resolve this issue replace
Response.Redirect("Login.aspx");
With
Response.Redirect(FormsAuthentication.LoginUrl);

Resources