Page posting after session expired in ASP.Net - asp.net

I am working on a ASP.net application. I have some code in the page init event and using some session variables.
protected override void OnInit(EventArgs e)
{
if (HttpContext.Current.Session["ApplicationUser"] == null)
// If Session Expires then reload the user roles.
{
HttpContext.Current.Session.Remove("ApplicationUser");
var userService = new UserService();
var userRoles = userService.GetUserRoles(userName);
if (userRoles.Count() == 0)
{
HttpContext.Current.Response.Redirect("~/UnAuthorized.aspx", true);
}
else
{
isAuthunticated = true;
roles = userRoles;
HttpContext.Current.Session["ApplicationUser"] = userRoles;
}
}
}
Note: I am not using any session variables apart from this two places.
The default session timeout value is 20 mins.
I opened a page and left the system idle for 30 mins. After 30 mins, I filled some fields in the page and hits save button(now page is posting and the session is expired)
In this scenario, system will accept the post request if the session is expired?

Related

How to redirect user to login page instantly after token expires

I am trying to redirect user to login page instantly after token expires and not after the next click how it is now. I have set
PostLogoutRedirectUri, FrontChannelLogoutUri, IdentityTokenLifetime, AccessTokenLifetime
correctly and it works fine redirecting user to login page after expiration of token. But it's not instant and requires a click. Is there a way to redirect user instantly?
I had a similar problem and can show my solution:
Some explaining words:
Using cookie authentication, the user gets a cookie containing an authentication ticket. The ticket is encrypted by the server and contains a lifetime. Every time a request is sent, the security ticket is sent with it and the lifetime is evaluated by the server. Then, if the remaining lifetime is less than half of the configured session lifetime, the lifetime in the authentication ticket is resetted.
My approach:
Knowing the process, the only solution I came up with, was to handle logout (and in my scenario session renewal) on client side. The general approach is to start a JS counter counting to session time configured by the server; Showing a popup for renewal 3 minutes before the lifetime ends and redirecting to the login page one minute before the session lifetime ends.
Here are some snippets I used:
This is part of all of my templates:
jQuery(function{
#if (HttpContext.Current != null && HttpContext.Current.Session["timeOutValue"] != null)
{
#:var timeOutMinute = #HttpContext.Current.Session["timeOutValue"].ToString();
}
else
{
#:var timeOutMinute = 20;
}
localStorage.setItem("timeoutInMinutes", timeOutMinute)
sessionWarning(timeOutMinute);
});
This is my function handling timer and renewal dialogue:
function sessionWarning(timeoutMinutes) {
var warningTime = ((timeoutMinutes - 3) * 60 * 1000);
var sessionTimer = parseInt(localStorage.getItem("sessionTimer"));
if ((sessionTimer !== null) && (sessionTimer < ((timeoutMinutes * 60 * 1000) / 2))) {
warningTime = warningTime - sessionTimer;
}
else {
localStorage.setItem("sessionTimer", "0");
sessionTimer = 0;
}
clearTimeout(timer);
timer = setTimeout(function () {
jQuery("#modal-session-container").modal();
}, warningTime);
intervalTimer = setInterval(function () {
if (isNaN(parseInt(localStorage.getItem("sessionTimer")))) {
localStorage.setItem("sessionTimer", "0");
}
if (!isNaN(timer)) {
localStorage.setItem("sessionTimer", String(parseInt(localStorage.getItem("sessionTimer")) + 1000));
}
}, 1000);
}
I hope this helps!

Preventing FormsAuthentication expiry time from increasing

I have a relatively simple WebForms-based site using Forms Authentication:
<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="secure/home.aspx" name=".AdminSite" />
</authentication>
As it's not explicitly mentioned, slidingExpiration is set to true by default, and thus a user is not logged off as long as they're still navigating around the site.
However, I'd like a specific page to not increment the expiry time. Is this possible, either within web.config or in code? The only suggestions I've seen mention setting slidingExpiration to false, which would apply side-wide.
The authentication cookie is set using:
FormsAuthentication.RedirectFromLoginPage(username, False)
and therefore altering the authentication cookie itself isn't practical.
The sliding expiration is achieved by the FormsAuthentication module by re-issuing the cookie when necessary. To prevent the sliding, you need to prevent the cookie renewal from happening.
This can be done by simply removing the FormsAuthentication cookie from the response.
Below is the code behind from a very simple web form. The aspx page has a div that shows the output from the Page_Load event.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
testDiv.InnerHtml = "Hi, cookie is: " + HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
testDiv.InnerHtml += "<br />";
var ticket = FormsAuthentication.Decrypt( HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
testDiv.InnerHtml += "Expires: " + ticket.Expiration.ToString("yyyy-MM-dd HH:mm:ss");
if(Response.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName))
testDiv.InnerHtml += "<br />Forms auth is trying to update the cookie in this response";
}
protected void Page_Prerender(object sender, EventArgs e)
{
if (Response.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName))
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
}
}
The Page_Prerender event removes the FormsAuthentication cookie from the response if it's present, thereby preventing the sliding.
I tested this by setting the timeout for the FormsAuthentication to two minutes. Then I start debug and log in. Then I keep refreshing the page in question.
Since FormsAuthentication doesn't update the cookie unless half the expiration time has gone, what happens is that for the first minute, the page will keep showing the same encrypted cookie and the same expires time. After a bit more than one minute, the page will be reporting that FormsAuthentication is trying to renew the cookie. But the Page_Prerender removes the cookie so it doesn't get sent. After another minute you will be redirected to the login page.
Testing the same but removing the Page_Prerender method show that the cookie is changed and the expires time updated after about one minute.
You could set the response cookie's expiry date to the expiry date of the request cookie, effectively overwriting what the system is doing for that specific page.
After some thought, I deviated from trying to alter the cookie or create a second cookie or override the cookie by changing the Session.Timeout. I think it may actually be easier to use a timer, using System.Timers. The methods for the timer can always be put into a separate class if you like.
using System.Timers;
public partial class MyPage:Page
{
private System.Timers.Timer timer;
protected void Page_Load(object sender, EventArgs e)
{
SetTimer();
}
private void SetTimer()
{
// Interval is set in milliseconds- set as you please.
timer = new System.Timers.Timer(1000 * 60);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
}
// In this handler, stop the timer and call a method to clear all cookies.
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
timer.Stop();
ClearAllCookies();
}
// Method to clear all cookies. There may be a simpler way to do this, you are vague about your cookies, so I supplied a clear all.
public void ClearAllCookies()
{
HttpCookie cookie;
string cookieName;
int cookieCnt = Request.Cookies.Count;
for(int i = 0; i < cookieCnt; i++)
{
cookieName = Request.Cookies[i].Name;
cookie = new HttpCookie(cookieName);
// This causes the cookie to expire
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
Response.Redirect("LogIn.aspx");
}
}
Edit
Or use a method that logs the user out. Either way, you will end the session without having to fiddle with the user's authentication for the duration of the remainder of the website, except to end it if the session times out on this particular page.
public void ForceLogOff(){
Session.Clear();
Session.Abandon();
Session.RemoveAll();
// Do here whatever you need to do.
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
Response.Redirect("LogIn.aspx");
}
How you end the session is up to you. This provides you a way to override the sliding expiration issue, and set a custom timeout from within one page only.

ASP.NET MVC determine remaining session timeout using SessionState

In one of my web application I need to popup alert when session timeout in 5 minutes. Users have option either continue to extend the session or log out immediately.
In Web.config set session timeout to 30 min:
<sessionState mode="InProc" timeout="30">
Since ASP.NET MVC do not give a way to check the remaining session timeout, I come up a solution as follow:
In Global.asax it tracks the current session last access time as a session variable. If the coming in request is not session state readonly (see below), the last access time session variable is updated with current time. Otherwise session variable's value is set with current time.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
var context = HttpContext.Current;
if (context != null && context.Session != null && !context.Session.IsReadOnly)
{
context.Session["_LastAccessTime"] = DateTime.Now;
}
}
In my session controller, I set the session state behavior to read only. Requests to this controller neither reset session nor do it refresh my last access time session variable.
[SessionState(SessionStateBehavior.ReadOnly)]
public class SessionController : BaseController
{
[AjaxOnly]
public ActionResult GetRemainingSessionTimeout()
{
if (!Request.IsAjaxRequest())
{
return Content("Not an Ajax call.");
}
var remainingSessionTimeout = 0;
if (Session["_LastAccessTime"] != null)
{
var lastAccessTime = (DateTime) Session["_LastAccessTime"];
var timeSpan = DateTime.Now.Subtract(lastAccessTime);
remainingSessionTimeout = Session.Timeout - timeSpan.Minutes;
}
return Json(new {RemainingSessionTimeout = remainingSessionTimeout}, JsonRequestBehavior.AllowGet);
}
}
In a view, Ajax request checks the remaining session timeout silently. If less than 5 min, then popup alert:
$(document).ready(function () {
$("#remainingSessionTimeout").click(function (e) {
var url = '#Url.Action("GetRemainingSessionTimeout", "Session", new { area = "" })';
$.ajax({
type: "POST",
url: url,
data: {},
success: function (result) {
$("#timeoutLeft").html('Your session expries in ' + result.Timeout * 60 + ' seconds.');
},
error: function (result) {
$("#timeoutLeft").html('error in getting session data.');
}
});
});
});
Any drawback or flaw of this solution? Thanks.

Custom authentication module inheriting IHttpModule issue

LoginPage.aspx:-
protected void Button1_Click(object sender, EventArgs e)
{
Context.Items["Username"] = txtUserId.Text;
Context.Items["Password"] = txtPassword.Text;
//
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Context.Items["Username"].ToString(), DateTime.Now, DateTime.Now.AddMinutes(10), true, "users", FormsAuthentication.FormsCookiePath);
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
Response.Redirect("Default.aspx");
}
Global.asax file:-
void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
// Get the stored user-data, in this case, our roles
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
Response.Write(HttpContext.Current.User.Identity.Name);
Response.Redirect("Default.aspx");
}
}
}
}
I get the following error after signing in
This webpage has a redirect loop.
The webpage at http://localhost:1067/Default.aspx has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
This is the rough idea of what your module should look like. Your module will run on every request. You don't invoke it or pass anything to it, it just automatically fires whenever a request is made that ASP.Net is set to process.
Your module will do two things, 1) authenticate a user in the login page, 2) authenticate a user on subsequent pages. The first step is to subscribe to the BeginRequest method which will be given the current HttpApplication as the first parameter. From there you need to determine if the user is on your login page or not. If they're not on your login page, check your session or cookie or querystring token, or whatever you're using to make sure that they're still valid. If they're invalid, bounce them back to the login page.
If they're on your login page and have made a POST, look at the raw form fields and validate them. TextBoxes, checkboxes, etc don't exist here, only raw form fields. If they're valid, set your authentication token however you want (session, cookies, etc). If they're invalid, either redirect to the login page or inject a "try again" message or something.
Also, if you double-post a message please reference it so that we can follow the chain of what was already said.
class MyModule : IHttpModule
{
void IHttpModule.Init(HttpApplication context)
{
//Subscribe to the BeginRequest event
context.BeginRequest += new EventHandler(this.Application_BeginRequest);
}
private void Application_BeginRequest(Object source, EventArgs e)
{
//Initialize our variables, null checks should be put here, too
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
System.Web.SessionState.HttpSessionState s = context.Session;
//Normally our module needs to validate every request to make sure our request is still authenticated.
//The exception to that rule is on our logon page where they obviously don't have credentials yet.
if(!context.Request.FilePath.ToLowerInvariant().StartsWith("/login.aspx")){
//If we're here then we're not on the logon page, validate our current session according to whatever logic we want
if (s != null && s["isvalid"] == "true"){
return;
}else{
context.Response.Redirect("/login.aspx");
}
}else{
//If we're here then we're on the login page itself. If there's a post, assume that they've hit the login button
if (context.Request.HttpMethod == "POST")
{
//Whatever your form variables are called
string username = context.Request.Form["username"];
string password = context.Request.Form["password"];
//Your own validation logic would go here
if (MyCustomLogin.IsUserValid(username, password))
{
s["isvalid"] = "true";
context.Response.Redirect("/Home.aspx");
}else{
s["isvalid"] = "false";
context.Response.Redirect("/login.aspx?error=invalid_login");
}
}else{
//If we're here then the request is probably a GET or HEAD which would be from a person
//initially browsing to our page so just do nothing and pass it through normally
}
}
}
}
There is no direct way to have access to this information in the module (for authenticated user, you can access the username via the context, but not the password). The module checks if a request is carrying required authentication information and serve or deny the request based on that. Unless you deliberately from the login page collect this information and store somewhere where you can access it in the module, e.g session. But ideally, storing password is not widely recommended, collect it use it for authentication and destroy.
You might ideally throw more light on the reason why you want to have access to this information in the module and guys can then suggest methods to accomplish it.
Edited, after Chandan comment:
#Chandan, your comment here suggest to me what you want to do is use httpmodule for your authentication as against using standard form authentication. If I am on track, then you can check this project on codeproject at http://www.codeproject.com/KB/web-security/AspNetCustomAuth.aspx. Goodluck

How to handle "Remember me" in the Asp.Net Membership Provider

Ive written a custom membership provider for my ASP.Net website.
Im using the default Forms.Authentication redirect where you simply pass true to the method to tell it to "Remember me" for the current user.
I presume that this function simply writes a cookie to the local machine containing some login credential of the user.
What does ASP.Net put in this cookie? Is it possible if the format of my usernames was known (e.g. sequential numbering) someone could easily copy this cookie and by putting it on their own machine be able to access the site as another user?
Additionally I need to be able to inercept the authentication of the user who has the cookie. Since the last time they logged in their account may have been cancelled, they may need to change their password etc so I need the option to intercept the authentication and if everything is still ok allow them to continue or to redirect them to the proper login page.
I would be greatful for guidance on both of these two points. I gather for the second I can possibly put something in global.asax to intercept the authentication?
Thanks in advance.
For me the solution was differentiating between a browser-session auth cookie (not to be confused with the asp.net session cookie) and a persistent one - setting a low expiration will create a persistent cookie meaning it gets remembered when the browser is closed and re-opened within the expiration time. The following works for me:
public void SetAuthenticationCookie(LoginView loginModel)
{
if (!loginModel.RememberMe)
{
FormsAuthentication.SetAuthCookie(loginModel.Email, false);
return;
}
const int timeout = 2880; // Timeout is in minutes, 525600 = 365 days; 1 day = 1440.
var ticket = new FormsAuthenticationTicket(loginModel.Email, loginModel.RememberMe, timeout);
//ticket.
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted)
{
Expires = System.DateTime.Now.AddMinutes(timeout),
HttpOnly = true
};
HttpContext.Current.Response.Cookies.Add(cookie);
}
FormsAuthentication and MembershipProviders are two completely different things, still they are made to work with each other very well. If you have written a persistent cookie ["Remember Me"] then next time, you can simply call Membership.GetUser() which will return you the MembershipUser instance of the currently logged in user or null if no user is logged in.
So first time when user arrives and authenticates with "Remember Me", you shall write a persistent cookie as following.
FormsAuthentication.RedirectFromLoginPage(strUserName, true);
Assuming user does not logout and leaves webpage and comes back after sometime. You can simply call MembershipUser.GetUser() as following and check if the user is already logged from the persistent cookie written by FormsAuthentication.
MembershipUser someUser = Membership.GetUser();
if(someUser == null)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
else
{
//Take where logged in users go.
}
You can do this check on your Login page itself or main landing page to intercept the User account to check if he needs to change the password or if the account is disabled as in your case.
EDIT
There are two ways to do this.
1.) Check for authentication as mentioned above in Session_Start event in global.asax and set a session key that becomes available on all pages for that particular session.
2.) Another way is too keep a common application wide common PageBase class that inherits from System.Web.UI.Page and acts as base page class for all your asp.net pages. On the Page Load of the common PageBase class check for the authentication as mentioned above. You will have to carefully write conditional redirection in this case since this might head towards infinite redirection with no end since it will run on Page_Load of all page from the common PageBase class.
public class PageBase : System.Web.UI.Page
{
/// <summary>
/// Initializes a new instance of the Page class.
/// </summary>
public Page()
{
this.Load += new EventHandler(this.Page_Load);
}
private void Page_Load(object sender, EventArgs e)
{
try
{
AuthenticateUser();
}
catch
{
//handle the situation gracefully.
}
}
private AuthenticateUser()
{
MembershipUser someUser = Membership.GetUser();
if(someUser == null)
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
else
{
//Take where logged in users go.
}
}
}
//in your asp.net page code-behind
public partial class contact : PageBase
{
protected void Page_Load(object sender, EventArgs e)
{
}
}

Resources