session is expiring even sending request to server - c#

when a user login I store his id in session let say in Session["id"]. on mostly pages I store id from session in an integer and use it in various methods. I put a check on page_load event
protected void Page_Load(object sender, EventArgs e)
{
if (Session["id"] == null)
{
Response.Redirect("Home.aspx");
}
//code goes here
}
What I know is that session expire after 20 min if no request is send to server. but even continuously sending request session expire and i redirected on home page. Is this correct approach or I should try other alternative. any help will be appreciated.

The correct way would be to use the membership API which handles all these details transparently. As shown in this explanatory page you could directly set the timeout interval in membership API using a parameter in the web.config.
Hope I helped!

If there is gap more than 20 minutes between two requests to server then only your session will get expired

Use Permanent User Login Session In ASP.NET thi sample describes how to create a permanent user login session in ASP.NET. The sample code includes an ASP.NET MVC4 project to control the user registration and login process. But you can use this technique in any type of ASP.NET project. But briefly you can use this code
The functionality of this class is to add a form authentication ticket to the browser cookie collection with a life time expiry.
public sealed class CookieHelper
{
private HttpRequestBase _request;
private HttpResponseBase _response;
public CookieHelper(HttpRequestBase request,
HttpResponseBase response)
{
_request = request;
_response = response;
}
//[DebuggerStepThrough()]
public void SetLoginCookie(string userName,string password,bool isPermanentCookie)
{
if (_response != null)
{
if (isPermanentCookie)
{
FormsAuthenticationTicket userAuthTicket =
new FormsAuthenticationTicket(1, userName, DateTime.Now,
DateTime.MaxValue, true, password, FormsAuthentication.FormsCookiePath);
string encUserAuthTicket = FormsAuthentication.Encrypt(userAuthTicket);
HttpCookie userAuthCookie = new HttpCookie
(FormsAuthentication.FormsCookieName, encUserAuthTicket);
if (userAuthTicket.IsPersistent) userAuthCookie.Expires =
userAuthTicket.Expiration;
userAuthCookie.Path = FormsAuthentication.FormsCookiePath;
_response.Cookies.Add(userAuthCookie);
}
else
{
FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
}
}
}
}
This function is used in login page or control on the click of login button. In the attached sample project, the following function is written in AccountController class. This function validates the login of the user and then add a permanent form authentication ticket to the browser.
private bool Login(string userName, string password,bool rememberMe)
{
if (Membership.ValidateUser(userName, password))
{
CookieHelper newCookieHelper =
new CookieHelper(HttpContext.Request,HttpContext.Response);
newCookieHelper.SetLoginCookie(userName, password, rememberMe);
return true;
}
else
{
return false;
}
}

Related

ValidateAntiForgeryToken in WebForms Application

I have done some reading about the use of ValidateAntiForgeryToken to prevent XSRF/CSRF attacks. However what I have seen seems to relate only to MVC.
These are the articles I've seen:
ValidateAntiForgeryToken purpose, explanation and example
CSRF and AntiForgeryToken
XSRF/CSRF Prevention in ASP.NET MVC and Web Pages
How can I implement this or something similar in a WebForms Application?
CSRF attacks are not exclusive to MVC application, webforms are vulnerable too.
Basically, CSRF attack exploits the trust that a site has in a user's browser, by requesting or posting information to the website, generally through hidden forms or JavaScript XMLHttpRequests within a the malicious website, as user using cookies stored in the browser.
To prevent this attacks you will need an antiforgery token, a unique token sent within your forms, that you need to validate before trusting the form's information.
You can find a detailed explanation here.
To protect your webforms apps against CSRF attacks (it's working in my projects), is to implement it in your master pages, like this:
Add new Class that will handle the CSRF Validations for you:
public class CsrfHandler
{
public static void Validate(Page page, HiddenField forgeryToken)
{
if (!page.IsPostBack)
{
Guid antiforgeryToken = Guid.NewGuid();
page.Session["AntiforgeryToken"] = antiforgeryToken;
forgeryToken.Value = antiforgeryToken.ToString();
}
else
{
Guid stored = (Guid)page.Session["AntiforgeryToken"];
Guid sent = new Guid(forgeryToken.Value);
if (sent != stored)
{
// you can throw an exception, in my case I'm just logging the user out
page.Session.Abandon();
page.Response.Redirect("~/Default.aspx");
}
}
}
}
Then implement this in your master pages:
MyMasterPage.Master.cs:
protected void Page_Load(object sender, EventArgs e)
{
CsrfHandler.Validate(this.Page, forgeryToken);
...
}
MyMaster.Master:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:HiddenField ID="forgeryToken" runat="server"/>
...
</form>
Hope you'll find this useful.
I found this article How To Fix Cross-Site Request Forgery (CSRF) using Microsoft .Net ViewStateUserKey and Double Submit Cookie with the following information code and instructions:
Starting with Visual Studio 2012, Microsoft added built-in CSRF protection to new web forms application projects. To utilize this code, add a new ASP .NET Web Forms Application to your solution and view the Site.Master code behind page. This solution will apply CSRF protection to all content pages that inherit from the Site.Master page.
The following requirements must be met for this solution to work:
•All web forms making data modifications must use the Site.Master
page.
•All requests making data modifications must use the ViewState.
•The web site must be free from all Cross-Site Scripting (XSS)
vulnerabilities. See how to fix Cross-Site Scripting (XSS) using
Microsoft .Net Web Protection Library for details.
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
//First, check for the existence of the Anti-XSS cookie
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
//If the CSRF cookie is found, parse the token from the cookie.
//Then, set the global page variable and view state user
//key. The global variable will be used to validate that it matches in the view state form field in the Page.PreLoad
//method.
if (requestCookie != null
&& Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
//Set the global token variable so the cookie value can be
//validated against the value in the view state form field in
//the Page.PreLoad method.
_antiXsrfTokenValue = requestCookie.Value;
//Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
//If the CSRF cookie is not found, then this is a new session.
else
{
//Generate a new Anti-XSRF token
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
//Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
//Create the non-persistent CSRF cookie
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
//Set the HttpOnly property to prevent the cookie from
//being accessed by client side script
HttpOnly = true,
//Add the Anti-XSRF token to the cookie value
Value = _antiXsrfTokenValue
};
//If we are using SSL, the cookie should be set to secure to
//prevent it from being sent over HTTP connections
if (FormsAuthentication.RequireSSL &&
Request.IsSecureConnection)
responseCookie.Secure = true;
//Add the CSRF cookie to the response
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
//During the initial page load, add the Anti-XSRF token and user
//name to the ViewState
if (!IsPostBack)
{
//Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
//If a user name is assigned, set the user name
ViewState[AntiXsrfUserNameKey] =
Context.User.Identity.Name ?? String.Empty;
}
//During all subsequent post backs to the page, the token value from
//the cookie should be validated against the token in the view state
//form field. Additionally user name should be compared to the
//authenticated users name
else
{
//Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] !=
(Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of
Anti-XSRF token failed.");
}
}
}
}
Using WebForms, the best thing to do is leverage the ViewStateUserKey.
Here is how to do it...
void Page_Init(object sender, EventArgs args)
{
ViewStateUserKey = (string)(Session["SessionID"] = Session.SessionID);
}
It seems kind of strange to save the SessionID in a session variable, but this is needed because it will auto-generate a new ID when empty.

ServiceStack Authentication validation with Captcha

I want to put a CAPTCHA field into the the auth submit form api/auth/credentials.
So, now the form will need to contain a captcha field apart from username, password and rememberme.
I will then check the session where I stored the answer of the captcha image vs the form submitted captcha result.
My question is, which part(s) of the SS source code do I need to override in order to do it correctly?
My feeling is that I should look into override and customise CredentialsAuthProvider class for the start?
Here is a quickie way to do it:
public ExtDeskResponse Post(MyAuth req) {
//Captcha Validation
var valid = req.Captcha == base.Session.Get<Captcha>("Captcha").result;
//SS Authentication
var authService = AppHostBase.Instance.TryResolve<AuthService>();
authService.RequestContext = new HttpRequestContext(
System.Web.HttpContext.Current.Request.ToRequest(),
System.Web.HttpContext.Current.Response.ToResponse(),
null);
var auth = string.IsNullOrWhiteSpace(
authService.Authenticate(new Auth {
UserName = req.UserName,
Password = req.Password,
RememberMe = req.RememberMe,
}).UserName);
if (valid && auth) {
//...logic
}
return new MyAuthResponse() {
//...data
};
}
Look forward to see you guys show me more elegant/efficient/expandable ways to do it.

Cookies and session in asp.net

I am creating a login and the storing the user details in a cookie using this code
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
//string useremail = Convert.ToString(txtUserName.Value);
Session.Add("useremail", txtUserName.Value);
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires=tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
}
I am also creating a session Session.Add("useremail", txtUserName.Value);
After succesfull authentication it is redirected to user.aspx
I want to read the useremail value in the user.aspx page but when I tried to access the value in the user page it is not showing useremail field.
protected void Page_Load(object sender, EventArgs e)
{
if
(Session["useremail"] == null) Response.Redirect("Home.aspx");
else
BindGridView(useremail);
}
And this is my webconfig:
<authentication mode="Forms"><forms name=".YAFNET_Authentication" loginUrl="Home.aspx" protection="All" timeout="43200" cookieless="UseCookies"/></authentication>
Correct me if i am doing any wrong. And also please tell me how to pass the useremail value to the user.aspx page so that I can pass that value to gridview function
Just change it to
protected void Page_Load(object sender, EventArgs e)
{
if (Session["useremail"] == null)
Response.Redirect("Home.aspx");
else
BindGridView((string)Session["useremail"]);
}
You can add an object to the session state like this:
Session["useremail"] = "john.smith#microsoft.com";
You can then retrieve it in the following manner:
var useremail = Session["useremail"] ?? null;
if (useremail == null)
{
//...
}
else
{
BindGridView(useremail);
}
If the item "useremail" is not present in the session state the useremail variable will be set to null otherwhise it will contain the e-mail address.
You are getting confused with relationship between authentication, session state and cookies.
In ASP.NET, Session State and Forms Authentication are not linked i.e. their scope are different. You can have some session state for un-authenticated user. Session and forms authentication uses different cookies for tracking purposes and the cookie management is more or less automatic and you don't really need to write code to manage it as you have done. Besides, what you store in the cookie has no bearing on what goes in the session state. Its also possible to have both session and forms authentication to get working w/o cookies. So code such as below should work for session state
Session["key"] = "put your data here";
// retrieve the data elsewhere
var data = Session["key"];

ASP.NET 3.5 MVC1 - Users randomly unauthenticated/required to log back in

We employ Out-of-Process SQL Session State, ASP.NET 3.5 MVC 1.0 and Forms Authentication using IIS 7.
A user's session is correctly set on logon and will time out as expected, redirecting them to a special "Time out" login page. The problem is that some (not all) users log in and are (from what I can tell) immediately unauthenticated and are required to log back in (i.e. redirected to the original "Login" page).
Might anyone have an idea why our users are intermittently being kicked out?
EDIT: I've since added logging on every Application_AuthenticateRequest event, I can tell you that before the user is booted out both the Auth ticket is authenticated, persistent and expires two days later and the request is also authenticated. Upon arriving at the logon page the user is no longer authenticated.
EDIT #2: We've made some progress, it would appear as though users may be unauthenticated because this web app is looking for scripts and other content in the parent app for which users are not authenticated. The original format for inclusion of these scripts is as follows:
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
I have corrected it to:
<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>" type="text/javascript"></script>
ANSWER The above changes to our script references in our .master pages resolved the issue. It explicitly tells the app to look in the root folder of the current app. Thank you to all who helped. I wish I could have marked more than one as the answer!
Below is our login Action:
[AcceptVerbs(HttpVerbs.Post)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
Justification = "Needs to take same parameter type as Controller.Redirect()")]
public virtual ActionResult LogOn(string userName, string password, string returnUrl)
{
if ((HttpContext.Current.User == null) || (!HttpContext.User.Identity.IsAuthenticated))
{
if (!ValidateLogOn(userName, password))
{
try
{
return View();
}
catch (Exception ex)
{
throw new Exception(string.Format("User validation failed at LogOn: {0}", ex.ToString()));
}
}
}
bool rememberMe = true;
FormsAuth.SignIn(userName, rememberMe);
Session["userName"] = userName;
if (!String.IsNullOrEmpty(returnUrl))
{
try
{
return Redirect(returnUrl);
}
catch (Exception ex)
{
throw new Exception(string.Format("User redirect to returnUrl ({0}) failed: {1}", returnUrl, ex.ToString()));
}
}
else
{
try
{
return RedirectToAction("Index", "RodWebUI");
}
catch (Exception ex)
{
throw new Exception(string.Format("User redirect to action: Index, controller: RodWebUi failed: {0}", ex.ToString()));
}
}
}
Below is our timeoutlogon action:
public virtual ActionResult TimeOutLogon()
{
try
{
FormsAuth.SignOut();
ViewData["TimeoutMsg"] = "Session timed out. Please log back in.";
return View();
}
catch (Exception ex)
{
throw new Exception(string.Format("Error with redirecting to TimeOutLogon: {0}", ex.ToString()));
}
}
I've since added the following check to our global.asax to log the current status of the request and auth ticket. Everything is authenticated and OK prior to being kicked back to LogOn.
protected 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 identity = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = identity.Ticket;
LogFunctionCall(HttpContext.Current.User.Identity.Name, "", "User Authentication Check", "",
string.Format("Auth ticket is expired: {0}, expiration date: {1}, is persistent: {2}, issued: {3}",
ticket.Expired, ticket.Expiration, ticket.IsPersistent, ticket.IssueDate), "", 0);
LogFunctionCall(HttpContext.Current.User.Identity.Name, "", "User Authentication Check Line #2", "",
string.Format("Raw URL: {0}, Request is authenticated: {1}", HttpContext.Current.Request.RawUrl, HttpContext.Current.Request.IsAuthenticated), "", 0);
}
}
}
}
Do you have a load balanced website?
If so, are the machineKeys the same on all nodes? Is the Forms Cookie name the same? If there are discrepancies in those values you can login on one node and seem unauthenticated to the other node.
ASP.Net redirects users to the login page if they are not authenticated OR if they are not authorized to view the resource they are trying to go to.
This might be silly but could the returnUrl be pointing to the login page?
How does the login page behave when the user is already logged in?
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void signout_Click(object sender, EventArgs e)
{
Response.Write("<script language=javascript>var wnd=window.open('','newWin','height=1,width=1,left=900,top=700,status=no,toolbar=no,menubar=no,scrollbars=no,maximize=false,resizable=1');</script>");
Response.Write("<script language=javascript>wnd.close();</script>");
Response.Write("<script language=javascript>window.open('login.aspx','_parent',replace=true);</script>");
Session["name"] = null;
}
}
I'm also adding on all page this code.
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetAllowResponseInBrowserHistory(false);
}
}
Spidey sense says that the ASP.NET process or app pool is recycling on you. Could happen for a few reasons. Since sessions are out of process, they won't get eaten by this event.
I'd look at the event logs to see if anything hinkey is going on there.

Setting ViewStateUserKey gives me a "Validation of viewstate MAC failed" error

I have the following in my BasePage class which all my ASPX pages derive from:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ViewStateUserKey = Session.SessionID;
}
I also have a machineKey set in Web.config. I don't think this error is because of a web farm because this happens on my dev machine too.
My host has now upgraded to .NET 3.5 SP1. After this update, everytime I compile with the ViewStateUserKey setting above, I constantly get the "Validation of viewstate MAC failed" error on every postback.
What am I doing wrong here? Is this setting even necessary anymore with the latest framework update?
OK - Im a year late to the conversation - but how is this the correct answer? This applies only in the case of authenticated users and using the ViewStateUserKey as the username is a lot easier to guess than a session id GUID.
BTW if you want to 'fix' the code up top, use the Session ID, however you must set a session variable in order for the session id to stop from changing every time. Ex.
Session["Anything"] = DateTime.Now
ViewStateUserKey = Session.SessionID;
This of course is assuming you are going to use sessions, otherwise you need some other key to use such as the username or any other guid kept in a cookie.
I've searched around quite a bit to find the definitive cause of the issue.
This post from Microsoft really helped explain all the different causes.
http://support.microsoft.com/kb/2915218
Cause 4 is what we have landed on which is an invalid ViewStateUserKeyValue
Setting ViewStateUserKey to Session.SessionID or User.Identity.Name did not work for us.
We intermittently got the validation error due to the following.
When the application pool is reset by IIS, the session is renewed in effect causing the error.
We drop the Session on login to avoid session fixation, also resulting in the error on login.
What finally worked for us was a cookie based solution, which is now provided in VS2012.
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
//First, check for the existence of the Anti-XSS cookie
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
//If the CSRF cookie is found, parse the token from the cookie.
//Then, set the global page variable and view state user
//key. The global variable will be used to validate that it matches in the view state form field in the Page.PreLoad
//method.
if (requestCookie != null
&& Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
//Set the global token variable so the cookie value can be
//validated against the value in the view state form field in
//the Page.PreLoad method.
_antiXsrfTokenValue = requestCookie.Value;
//Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
//If the CSRF cookie is not found, then this is a new session.
else
{
//Generate a new Anti-XSRF token
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
//Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
//Create the non-persistent CSRF cookie
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
//Set the HttpOnly property to prevent the cookie from
//being accessed by client side script
HttpOnly = true,
//Add the Anti-XSRF token to the cookie value
Value = _antiXsrfTokenValue
};
//If we are using SSL, the cookie should be set to secure to
//prevent it from being sent over HTTP connections
if (FormsAuthentication.RequireSSL &&
Request.IsSecureConnection)
responseCookie.Secure = true;
//Add the CSRF cookie to the response
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
//During the initial page load, add the Anti-XSRF token and user
//name to the ViewState
if (!IsPostBack)
{
//Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
//If a user name is assigned, set the user name
ViewState[AntiXsrfUserNameKey] =
Context.User.Identity.Name ?? String.Empty;
}
//During all subsequent post backs to the page, the token value from
//the cookie should be validated against the token in the view state
//form field. Additionally user name should be compared to the
//authenticated users name
else
{
//Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] !=
(Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of
Anti-XSRF token failed.");
}
}
}
}
Source
I fixed it for now by changing the code to:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (User.Identity.IsAuthenticated)
ViewStateUserKey = User.Identity.Name;
}
Can you turn off ViewState MAC encoding with the EnableViewStateMac #Page attribute?
VERY Strange, I too had similar issue for 3 days and now i resolved it.
1. I had enabled forms authentication and had ssl false
<forms defaultUrl="~/" loginUrl="~/Account/Login.aspx" requireSSL="false" timeout="2880" />
but in my httpcookies tag I had requireSSL=true. Since in the Site.Master.cs it uses cookies to set the ViewStateUserKey, it was having issues
hence I was getting the error.
I modified this to false and restarted web app, now its all good.

Categories