This seems simple and I remember doing it a couple of years ago.
I simply want to display a message on the login page when the user is automatically redirected there after requesting a page that they were logged in for but their session has now expired. So essentially if the user was working but stepped away for a lunch break without logging out I want the system to tell them why they were sent back to the login page.
Something like "You have been idle for too long so you must log back in".
This has to be easy I am just running into a wall here. I thought about getting the original ticket and reading the expiration date but I'm a little lost.
Any ideas?
Brent
Try this JavaScript on for size:
Make sure that a property called LoginPageUrl exists on the code behind. Great for Master pages.
If you want to register the script from code-behind, you could even pull the session timeout from the application and inject it so that you still only have one place (web.config) to update it.
To display a message to the user after redirecting them to the login page (.NET will take care of expiring the cookie), send a query string parameter that the login page looks for and shows a message indicating that the user was logged out due to inactivity.
<head>
...
</head>
<body onload="logoutOnExpire();" >
<script type="text/javascript">
// ACTIVITIES TO RUN FOR THE PAGE
function logoutOnExpire() {
clearTimeout(logoutTimeout);
logoutTimeout =
setTimeout('location.href = '<%= LoginPageUrl %>';', 1200000);
// 20 minutes
}
</script>
<form id="form" runat="server">
...
</form>
</body>
</html>
You can check the session in the inner page and if session does not exist,Redirect to the login page with some value in querystring to understand from which page this call came.When user logged in back,You can use the querystring value to determine which page to be displayed back.
MyPage.aspx.cs,In Page load you can check,
if(Session["user"]==null)
{
Response.Redirect("Login.aspx?from=mypage");
}
else
{
// Do the other stuff for the loged in user
}
And In Login.aspx.cs,In the code where you check your login details from the form
string userName=txtUserName.Text;
string password=txtPass.Text;
if(IsValidLogin(userName,password)
{
string toUrl="defaul.aspx";
if(Request.QueryString["from"]!=null)
{
string fromPage=Request.QueryString["from"];
if(fromPage=="mypage")
{
toUrl="mypage.aspx";
}
else if(fromPage=="review")
{
toUrl="review.aspx";
}
}
Response.Redirect(toUrl);
}
If what you want is to send the user to a page other than the login page when they cause a server postback after their session expires, use the following code at the top of the Page_Load event (this may not work if .NET executes it's redirect first).
if(!Context.User.Identity.IsAuthenticated)
{
Response.Redirect("~/OtherPage.aspx", false);
}
If you create a base page in your website that all pages inherit from, add it to that page's Page_Load.
If you are redirected to the default login page, after an attempt to use a page after your session has been timed out, is not the redirecturl param set to the page you were trying to access.
So you could infer that if that is set they were previously on a page and then present your message about being logged out due to going for lunch., etc.
Related
I am a new bee creating an asp.net web application for my application. I will have different users and i didn't use any special forms or methods to do the login. I have access db , in there i have some user role, company,username , and password.
In my login page through text box i will get company username and password inputting by the end user. then i will check for the company and username (which is primary key in the table.) if the password matches then will find the user role and redirect to the pages for each user.
that works fine now.
I have a log out button which is sitting in the sitemaster page and
<div id="logout" runat="server" visible="false" class="navbar-brand1">
<a id="lo" runat="server" href="/Default">Log Out </a>
</div>
then in the pages where i want to show the log out i will call the code
Master.FindControl("logout").Visible = true;
it was working fine in respect of login in and login out . but infact the log out button just redirects to the first page on site and if we do the back arrow in the browser i can go back to the prevs page i was on. Is there any way i can do it neatly so that after log out even though if i go back on the browser it will ask for log in .
Any help will be really appreciated. I made a mistake and created complete application now i am worried about this feature so technically i am not logging out :(
Whenever a user opens a page in the system use below code to check if the session is valid
if (!IsPostBack)
{
if (Convert.ToString(Session["UserName"]).Length <= 0)
{
Response.Redirect("Login.aspx");
}
}
When the user clicks on SignOut button, make redirection to a SignOut.aspx page. Use below code in the form load event of SignOut.aspx to clear the session.
protected void Page_Load(object sender, EventArgs e)
{
Session.Abandon();
Session.Contents.RemoveAll();
System.Web.Security.FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
Well, your question is how to do the
proper login
The proper way is not to reinvent the wheel, but use the framework that is built in in ASP.NET
https://msdn.microsoft.com/en-us/library/ms731049%28v=vs.110%29.aspx
It will give you a lot of extra features, like using OpenAuth etc.
Example
"https://msdn.microsoft.com/en-us/library/aa354509%28v=vs.110%29.aspx
As #Chathuranga Ranasinghe mentioned I used session varibale to store the username details and i will check if the session variable empty then go to my default page otherwise continue.
if (((string)Session["iden"]) )
{
Response.Redirect("/Default.aspx");
}
i used this on the pages comes after logged in and it works fine for me now.
When I try to log off the system, my login page is loaded. After that press the browser back button and it shows web page has expired and when I refresh the page, the database call is again made since the value in Request. Form[“__EVENTTARGET”] attribute and textbox values are retaining its previous values and the function for logging in is again executed.
Please suggest a way to solve this issue.
Ex : Server side code is given below:
if (IsPostBack)
{
string parameter = Request.Form["_EVENTTARGET"];
string argument = Request.Form["_EVENTARGUMENT"];
if (parameter == "LOGIN")
{
ValidateLoginDetails();
}
}
After log off, When I press the browser back button, browser shows web page has expired. Then I refreshed the page and I am getting the values of the string parameter. What can be the reason and how can I solve this issue.
Sounds like you haven't logged the user out correctly - you shouldn't be able to hit server-side code on a page that's configured to be authenticated until authentication has happened.
Another option is that there's a problem with the authentication configuration - have you checked that User.Identity.Name returns the value you expect?
I have a button that executes a script using AJAX.
Normally when a session is still active the script will return some data that will be placed inside the parent page.
If the session expired the AJAX will return the login screen which gets placed inside the parent page which looks really odd.
How would I be able to detect a session timeout and do a postback on the parent page?
Since you are unlikely to be calling a full page, and you login page is likely to be a full page, you could just do the following.
if (xmlhttp.responseText.indexOf("DOCTYPE") != -1) {
window.location.href = window.location.href;
}
When you make your call, first check to see if one of your session parameters is Nothing/null. If it is null, then your session has likely timed out. If you don't have any session variables that you explicitly set, you can set one when the user logs in.
What do you mean by 'if the session expired the AJAX will return the login screen'? You are in control of what is returned, so instead of returning the login screen return some sort of error code, or better throw an exception which you can catch as an error on the client.
I was working with my application which shows login first time and goes to the second screen after successful validation. But there is a problem occurs when browser get refresh by F5 or browser button the application gets reloaded and shows the very first screen i.e. the Login screen.
How to avoid this, I mean irrespective of browser reloading the current screen/component should remain intact (it should not start with the beginning).
As an example I have a link from where I took this example & uses in my code:
http://www.vipercreations.com/media/tutorials/login_system_with_flex_and_php/
credentials: user: test and pass: test
Here, once u logged in and press F5 you will back to the Ist screen rather than staying at the same screen.
Thanks,Shuo
If your login creates something like a session you can pass that same session object to the application via FlashVars.
When your application is starting, test if a session is already existing. If existing, validate it against the server. If successful: you are logged in, so skip the login screen. Otherwise: show login screen.
Besides: This is not a refresh issue but boils down to session management. Instead of hitting the refresh button I could also open the same website again and would have to login which seems akward.
Ofcourse it will reload, it is not the flash who is reloaded.. its the whole web page. or HTML file.
I have this code to disable F5 or refresh
<script>
window.history.forward(1);
document.attachEvent("onkeydown", my_onkeydown_handler);
function my_onkeydown_handler()
{
switch (event.keyCode)
{
case 116 : // 'F5'
event.returnValue = false;
event.keyCode = 0;
window.status = "We have disabled F5";
break;
}
}
</script>
You could store the sessionID in a cookie via ExternalInterface or in a shared object. This way you can even add a expiration date that of course should be in sync with the serverside expiration of the session.
Additionally you can use the HistoryManager or the BrowserManager to encode states of the app in the URL. If you design the states carefully, hitting F5 (or accessing the page via bookmarks) will direct the browser to the last state instead of the beginning. Just remember to verify the session.
I'm using OutputCache in my page that has a user control, but I don't want to cache this specific user control because it's related to a user login (if I access the page, I see the page as if I were authenticated with another user).
How can I do that?
Personally I use the VaryByCustom attribute to give logged in and logged out users different cached page views:
<%# OutputCache VaryByCustom="IsLoggedIn" Duration="30" VaryByParam="*" %>
then in global.asax you put
public override string GetVaryByCustomString(HttpContext context,
string arg)
{
if (arg == "IsLoggedIn")
{
if (context.Request.IsAuthenticated)
{
return "Logged in: " + context.User.Identity.Name;
}
else
{
return "Not Logged In";
}
}
else
{
return base.GetVaryByCustomString(context, arg);
}
}
I am just going to throw this out there. How about the substitution control?
http://msdn.microsoft.com/en-us/library/ms228212.aspx
According to msdn website:
The Substitution control lets you
create areas on the page that can be
updated dynamically and then
integrated into a cached page. ...
The Substitution control offers a
simplified solution to partial page
caching for pages where the majority
of the content is cached. You can
output-cache the entire page, and then
use Substitution controls to specify
the parts of the page that are exempt
from caching.
I have never used the substituion control personally, but I just happened to look it up the other day, and it sounded like it can somehow inject updated content into an otherwise cached page output.
You can cache a page and you can cache a user control, but you can't cache a page except for a user control. When the user control runs the entire page has to run. You have to make the output cache for the page recognise the different users.
You can use VaryByHeader="Cookie" to cache the page for each set of cookies if the user identity is stored in a cookie. You can use VaryByCustom="SomeString" and implement a check for SomeString to do your own check for user identity in the GetVaryByCustomString method in Global.asax.
You can create a cache filter : http://weblogs.asp.net/rashid/archive/2008/03/28/asp-net-mvc-action-filter-caching-and-compression.aspx
Check inside this filter if the user is logged or not.