Handling session and authentication timeouts in ASP.Net

本文探讨了ASP.NET应用中会话(session)及认证(authentication)超时的处理方式,包括如何配置会话超时、检测会话过期并重定向用户,以及在认证超时情况下的自动处理机制。

Handling session and authentication timeouts in ASP.Net

 

By George Mihaescu

 

Summary: this article describes the handling of in-process session and authentication timeouts in an ASP.Net application. Both types of timeouts are discussed in the same article because sometimes there may be a dependency between the two. The article also covers the in-process session timeout due to application domain recycling and the conditions that can cause the recycling. Applies to ASP.Net 2.0 (I have not tested the solutions listed here on ASP.Net 1.1 or 1.0).

Handling the in-process session timeout

You configure your session's attributes (including the timeout) through the web.config file, similar to:

 

<sessionState cookieless="UseDeviceProfile" timeout="30" />

 

This specifies that a user's in-process session will expire after 30 minutes of inactivity (i.e. no requests received from that user in the specified time since the last request). When the timeout occurs, the session in question is destroyed and any data that you had stored for that user in the session is therefore gone.

 

Many developers forget about this possibility and assume that once they've stuck something in the session, it will be forever there. However, if the user hits the site again after his previous session has expired, ASP.Net will create a new session for him, one that obviously will be initially empty. This means that the following scenario is possible: the user accesses the site, has a session and goes through a number of pages that cause some data to be accumulated in the session, but then makes no requests for more than your set timeout, causing the session to expire on the server. Then the user gets back to the browser and hits submit in the page he has in the browser – if your code assumes the data to be in the session and work with it, you are in trouble. 

The immediate solution that comes to mind is to always check whether the expected data is in the session, and if not, redirect the user to a page where he can start the input again, a page where no data is expected to be in the session (for example, the home page, showing an explanation that the user's session has expired due to inactivity). However, this solution is not robust enough, especially for large applications, with many developers involved because:

  • I can easily imagine some developers forgetting to check the returned object from the session and assuming it is there. This is basically the equivalent of not checking a function's return code, something which is not detected by any tools that I know of, and which is also difficult to test (what are you going to do? Sit in front of each page and wait for the session to expire then hit every possible postback action in the page?)
  • Certain objects may be missing in the session for good reasons (i.e. it is an accepted business rule), and this only confuses the "always check the object retrieved from the session" rule. The developer must now know what might be rightly missing from the session and what actually should be there, but if not, conclude the session has expired and handle this case.

 

Therefore, you'd need a more robust and ideally, centralized mechanism to detect a user's session expiration and redirect the user to the said "start" page when he can go through the motions without crashing because the session is now empty.

 

As a side note: I've seen developers attempting to do this through the global Session_End method in global.asax. This is wrong and it will not work because while Session_End is indeed called when a user's session is terminated, it is being called from a worker thread of the ASP.Net worker process, and not in the context of a user's request. Consequently, there is no way you can redirect the user anywhere from this method (or show him a message or whatever) simply because you have no connection with the user. It's all on the server. What you can do in Session_End (and this is its intended purpose) is to perform whatever clean-up or other processing you need when a user's session object is terminated. For example this site (www.abstraction.net) decrements the "active user count" maintained by the application, and this is how the current count of users is displayed at the bottom of each page – this is in effect the count of sessions that are currently alive on the server.

 

The solution I found for this is to use the global Session_Start method in global.asax. This method is called in the context of a user's request, when the user's session is created. The trick is to detect whether this user had a previous session on the server – if he did, the fact that a new session is being created for him means that the previous one had timed out. The way to detect that the user had a previous session on the server is to look in the request headers for the session ID cookie:

 

void Session_Start(object sender, EventArgs e)

{

    //This is obviously a new session being created; it can be

    //created at the first hit of a user, or when the user

    //previous session has expired (timeout). We are only interested

    //in the timeout scenario, so we look at the request cookies

    //and if we have a previous session ID cookie, it means this is a

    //new session due to the timing out of the old one.

    //Note: slight problem here: in .Net 2.0 the ASP Session ID

    //cookie name is configurable, but we don't have a way to

    //retrieve that from the web.config - so if you customize

    //the session cookie name in the web.config you'll have to

    //use the same name here.

    string request_cookies = Request.Headers["Cookie"];

    if ((null != request_cookies) &&

            (request_cookies.IndexOf("ASP.NET_SessionId") >= 0))

    {

        //cookie existed, so this new one is due to timeout.

        //Redirect the user to the login page

        System.Diagnostics.Debug.WriteLine("Session expired!");

        Response.Redirect(Constants.HOME_PAGE + "?" +

                          Constants.PARAM_REQUEST + "=" +

                          Constants.PARAM_REQUEST_VALUE_TIMEOUT);

    }

}

 

The default name of the ASP.Net session cookie is "ASP.NET_SessionId". Note that (as the comments in the code explain) there is a small potential problem here, as starting with ASP.Net 2.0 the name of the ASP.Net session cookie is configurable in the web.config, but there is no way of programmatically retrieving that custom name – so if you do specify a custom ASP.Net session cookie name, you're stuck to hard-coding the same name in the code above, and keeping the two in sync.

 

The mechanism presented above worked flawlessly for me in several sites; it has the great advantages of being simple and centralized, thus guaranteeing that the moment the user hits any page after his session has expired, he is automatically sent to a location where he can safely start.

 

Note that the session may expire not only because of the user timing out; something developers often forget is that all the user sessions will also expire when the application domain is being recycled by the ASP.Net hosting process. The conditions under which the app domain is recycled are discussed at the end of this article.

Handling the authentication timeout

If you are using ASP.Net forms authentication you must configure the authentication in the web.config in a manner similar to this:

 

<authentication mode="Forms">

  <forms    name="MyAuthCookie"

loginUrl="login.aspx "

defaultUrl="home.aspx"

timeout="40"

            slidingExpiration="true"

cookieless="UseDeviceProfile"

path="/"

protection="All" />

</authentication>

 

The timeout attribute specifies the period in minutes after which the authentication token (cookie) will expire; the reference is the time the token was issued (if slidingExpiration is false – which is the default in ASP.Net 2.) or the last request time (if slidingExpiration is true; which is the default in ASP.Net 1.x).

 

Handling the authentication timeout is basically done automatically by ASP.Net: when the timeout occurs, any page that has restricted access (as specified in web.config) will cause the user to be redirected to the page specified in the loginURL attribute. So there isn't a lot to be said about this. However, you must pay attention to the case when the session expires before the authentication; you may be left with an authenticated user that does not have a session anymore. If you don't store anything related to the user security privileges in the session – for instance, his role / access rights - this is not an issue (after all, you can handle this as described above for the session timeout case).

But if you do, then the session handling will not help you, because you are left with an authenticated user for which you don't know the security privileges anymore.

 

This is why I recommend that generally you don’t store such security-related attributes in the session. If you do, then you must handle the session timeout as a logout, and force the user to log in again. This, however, is not handled automatically by ASP.Net and you will have to do it yourself.

Do you have a dependency between the user's authentication token and his session?

Ideally, the answer should be no. You should not rely on the session data being available for security-related issues for many reasons, among others being the separation of concerns. One token deals with user access rights, the other with storing user data across requests. However, in many cases developers choose to store the user's access rights in the session, most often in sites that allow both anonymous and authenticated access, with authenticated users having more functions / pages available to them then the anonymous ones. So instead of storing an access rights token in the user's authentication cookie, developers choose to store the user's access rights in the user's session (sometimes because of what is perceived to be a security issue – however, this is a generally a false concern, as the user's authentication token can be encrypted very strongly an very easily through the protection attribute of the forms element in web.config). But this assumes that the session does not expire before the authentication – otherwise you would be left with an authenticated user for which you actually don't know the access rights, as those were stored in the session that is now gone. When faced with this dependency, many developers think it will suffice to set the session timeout to a higher value than the authentication timeout, and set the slidingExpiration to true for the forms authentication. The thinking is that in this setup the user authentication will expire first, causing the ASP.Net to automatically handle this and redirect the user to the login page (as set in the web.config). If the session is still around, it will be renewed, if not, a new one will be created and then the user's access rights will be set as per his login.

 

But the above logic does not always work: even with the setup described, there is always the possibility that the user's session expires before the authentication token, due to application domain recycling. When this happens, all the user sessions are terminated, so all authenticated users will be left without the related data in the session. In other words, if you do store authentication-related data in the user's session, you must always handle the case when the session expires before the authentication token, regardless of your timeout settings. The section below describes the conditions under which the application domain is recycled.

Session termination due to app domain recycling

In ASP.Net each application resides in its application domain. Essentially an application domain is for the ASP.Net runtime host what a process is for the operating system: the ASP.Net runtime host can run multiple application domains, each in its separate memory space, with its own security attributes, loaded assemblies, etc. The sole purpose of the application domain is to provide isolation (memory, security, etc) to .Net applications running under the same runtime host.
The ASP.Net runtime host has the ability to recycle any app domain it is running, meaning that the app domain is destroyed and re-created (all assemblies are reloaded, the code is re-jitted, all the in-process variables – such as Cache and Session are destroyed, etc). Obviously, besides killing all the sessions, an app domain recycle will also cause a major performance hit to your application.

 

The ASP.Net runtime host will recycle an app domain under the following conditions:

1.    The web service is restarted – an obvious one, so I won't comment any further on this.

2.    Global.asax is modified – another obvious one, again I won't comment.

3.    Machine.config or web.config are modified – again, those appear to be obvious reasons to recycle the app domain, but in many cases those are in fact not modified explicitly – they could simply be "touched" by another program, such as a an anti-virus program. To avoid unexpected recycles, set up such programs to exclude those files from their periodic scan.

4.    The contents of the bin directory is modified – again, those can be changes that are not done explicitly, but caused by another program touching the files. As above, make sure that an anti-virus or similar program excludes the files in the bin directory from the scan.

5.    The number of re-compilations of aspx, ascx or asax exceeds the threshold set by <compilation numRecompilesBeforeAppRestart=/> in machine.config or web.config  (the default is 15).

6.    The physical path of the IIS virtual directory is modified.

7.    Sub-directories are deleted or renamed. This is new to ASP.Net 2.0 and (in my opinion) a very aggressive policy. Whenever you delete or rename a sub-directory of your application, the application domain is recycled, terminating all users' sessions (and the cache, etc). Besides being a big performance hit, this behavior affects dramatically sites that allow document publishing, to the point where they stop functioning. Imagine a situation where a request creates a thread that goes through sub-directories of the application and deletes / renames them – without knowing about this 2.0 application domain recycling policy, chances are that the worker thread in question will not complete because the domain is recycled and the thread aborted. Currently I don't know any way of altering this behavior; the only solution I have is to locate any content that needs to have the directory names altered outside the application's root directory.

 

If you suspect app domain restarts (meaning: your sessions seem to expire without obvious reasons), you will be interested to know when the restarts happen and what's causing them. One simple way of doing this (again, available only in .Net 2.0) is to add the following element to the global web.config file (under C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG) as a child of the <healthMonitoring><rules> elements:

 

<add name="Application Lifetime Events Default"

eventName="Application Lifetime Events"

      provider="EventLogProvider"

profile="Default"

minInstances="1"

      maxLimit="Infinite"

minInterval="00:01:00"

custom="" />

 

This will log system events that provide the time and the reason of the restart (such as: Application is shutting down. Reason: Configuration changed.)


标题SpringBoot智能在线预约挂号系统研究AI更换标题第1章引言介绍智能在线预约挂号系统的研究背景、意义、国内外研究现状及论文创新点。1.1研究背景与意义阐述智能在线预约挂号系统对提升医疗服务效率的重要性。1.2国内外研究现状分析国内外智能在线预约挂号系统的研究与应用情况。1.3研究方法及创新点概述本文采用的技术路线、研究方法及主要创新点。第2章相关理论总结智能在线预约挂号系统相关理论,包括系统架构、开发技术等。2.1系统架构设计理论介绍系统架构设计的基本原则和常用方法。2.2SpringBoot开发框架理论阐述SpringBoot框架的特点、优势及其在系统开发中的应用。2.3数据库设计与管理理论介绍数据库设计原则、数据模型及数据库管理系统。2.4网络安全与数据保护理论讨论网络安全威胁、数据保护技术及其在系统中的应用。第3章SpringBoot智能在线预约挂号系统设计详细介绍系统的设计方案,包括功能模块划分、数据库设计等。3.1系统功能模块设计划分系统功能模块,如用户管理、挂号管理、医生排班等。3.2数据库设计与实现设计数据库表结构,确定字段类型、主键及外键关系。3.3用户界面设计设计用户友好的界面,提升用户体验。3.4系统安全设计阐述系统安全策略,包括用户认证、数据加密等。第4章系统实现与测试介绍系统的实现过程,包括编码、测试及优化等。4.1系统编码实现采用SpringBoot框架进行系统编码实现。4.2系统测试方法介绍系统测试的方法、步骤及测试用例设计。4.3系统性能测试与分析对系统进行性能测试,分析测试结果并提出优化建议。4.4系统优化与改进根据测试结果对系统进行优化和改进,提升系统性能。第5章研究结果呈现系统实现后的效果,包括功能实现、性能提升等。5.1系统功能实现效果展示系统各功能模块的实现效果,如挂号成功界面等。5.2系统性能提升效果对比优化前后的系统性能
在金融行业中,对信用风险的判断是核心环节之一,其结果对机构的信贷政策和风险控制策略有直接影响。本文将围绕如何借助机器学习方法,尤其是Sklearn工具包,建立用于判断信用状况的预测系统。文中将涵盖逻辑回归、支持向量机等常见方法,并通过实际操作流程进行说明。 一、机器学习基本概念 机器学习属于人工智能的子领域,其基本理念是通过数据自动学习规律,而非依赖人工设定规则。在信贷分析中,该技术可用于挖掘历史数据中的潜在规律,进而对未来的信用表现进行预测。 二、Sklearn工具包概述 Sklearn(Scikit-learn)是Python语言中广泛使用的机器学习模块,提供多种数据处理和建模功能。它简化了数据清洗、特征提取、模型构建、验证与优化等流程,是数据科学项目中的常用工具。 三、逻辑回归模型 逻辑回归是一种常用于分类任务的线性模型,特别适用于二类问题。在信用评估中,该模型可用于判断借款人是否可能违约。其通过逻辑函数将输出映射为0到1之间的概率值,从而表示违约的可能性。 四、支持向量机模型 支持向量机是一种用于监督学习的算法,适用于数据维度高、样本量小的情况。在信用分析中,该方法能够通过寻找最佳分割面,区分违约与非违约客户。通过选用不同核函数,可应对复杂的非线性关系,提升预测精度。 五、数据预处理步骤 在建模前,需对原始数据进行清理与转换,包括处理缺失值、识别异常点、标准化数值、筛选有效特征等。对于信用评分,常见的输入变量包括收入水平、负债比例、信用历史记录、职业稳定性等。预处理有助于减少噪声干扰,增强模型的适应性。 六、模型构建与验证 借助Sklearn,可以将数据集划分为训练集和测试集,并通过交叉验证调整参数以提升模型性能。常用评估指标包括准确率、召回率、F1值以及AUC-ROC曲线。在处理不平衡数据时,更应关注模型的召回率与特异性。 七、集成学习方法 为提升模型预测能力,可采用集成策略,如结合多个模型的预测结果。这有助于降低单一模型的偏差与方差,增强整体预测的稳定性与准确性。 综上,基于机器学习的信用评估系统可通过Sklearn中的多种算法,结合合理的数据处理与模型优化,实现对借款人信用状况的精准判断。在实际应用中,需持续调整模型以适应市场变化,保障预测结果的长期有效性。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值