会话操纵

需要学习会话管理,实现了一个在ASP.NET下的会话Cookie定制功能,将会话Cookie进行了一定的安全处理。主要是继承了httpmodule模块,代码如下:


using System; using System.Text; using System.Web; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Security; using System.Globalization; namespace MySession { public class SecureSessionModule : IHttpModule { private static string _ValidationKey = null; public void Init(HttpApplication app) { //如果密钥还没有初始化则初始化验证密钥 if (_ValidationKey == null) { _ValidationKey = GetValidationKey(); } //注册时间,用于对请求和响应事件 app.BeginRequest += new EventHandler(OnBeginRequest); app.EndRequest += new EventHandler(OnEndRequest); } public void Dispose() { } void OnBeginRequest(object sender, EventArgs e) { //查找进来的请求中存在名为:ASP.NET_SESSIONID的cookie HttpRequest request = ((HttpApplication)sender).Request; HttpCookie cookie = GetCookie(request, "ASP.NET_SessionId"); if (cookie != null) { //如果cookie不存在mac,抛出异常 if ((cookie.Value.Length <= 24)) { throw new InvalidationExecption("Access Denied"); } //将cooki与哈希码分离出来 string id = cookie.Value.Substring(0, 24); string mac1 = cookie.Value.Substring(24); //从会话ID和请求中产生一个新的哈希码 string mac2 = GetSessionIDMac(id, request.UserHostAddress, request.UserAgent, _ValidationKey); //不匹配的时候抛出异常 if (string.CompareOrdinal(mac1, mac2) != 0) { throw new InvalidationExecption("Access Denied"); } cookie.Value = id; } } void OnEndRequest(object sender, EventArgs e) { //找名为:ASP.NET_SESSIONID的cookie HttpRequest request = ((HttpApplication)sender).Request; HttpResponse response = ((HttpApplication)sender).Response; // HttpCookie Custoncookie = new HttpCookie("lxk613"); HttpCookie Custoncookie = GetCookie(request, "ASP.NET_SessionId"); string id = Custoncookie.Value.Substring(0, 24); HttpCookie cooki = new HttpCookie("lxk2011",id); response.Cookies.Add(cooki); cooki.Expires = DateTime.Now.AddSeconds(0); cooki.Domain = @"/store"; //客户的IP地址 string abc=Hex2NOrder("ffffffff", 2); HttpCookie ip = new HttpCookie("ClientIP", request.UserHostAddress+abc); response.Cookies.Add(ip); HttpCookie cookie = GetCookie(response, "ASP.NET_SessionId"); //HttpCookie cookieRemove = GetCookie(response, "删除的Cookie子项"); if (cookie != null) { //添加哈希码至每一个会话中 cookie.Value += GetSessionIDMac(cookie.Value, request.UserHostAddress, request.UserAgent, _ValidationKey); } } private string GetValidationKey() { // string key = ConfigurationSettings.AppSettings["SessionValidationKey"]; string key = System.Configuration.ConfigurationManager.AppSettings["SessionValidationKey"]; if (key == null || key == string.Empty) { throw new InvalidationExecption("session key is missing"); } return key; } private HttpCookie GetCookie(HttpRequest request, string name) { HttpCookieCollection cookies = request.Cookies; return FindCookie(cookies, name); } private HttpCookie GetCookie(HttpResponse response, string name) { HttpCookieCollection cookies = response.Cookies; return FindCookie(cookies, name); } private HttpCookie FindCookie(HttpCookieCollection cookies, string name) { int count = cookies.Count; for (int i = 0; i < count;i++ ) { if (string.Compare(cookies[i].Name,name,true,CultureInfo.InvariantCulture)==0) { return cookies[i]; } } return null; /*foreach (HttpCookie c in cookies) { if (string.Compare(c.Name, name, true, CultureInfo.InvariantCulture) == 0) { return c; } } return null;*/ } private string GetSessionIDMac(string id, string ip, string agent, string key) { StringBuilder sb = new StringBuilder(id, 512); sb.Append(ip.Substring(0, ip.IndexOf('.', ip.IndexOf('.') + 1))); sb.Append(agent); using (HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(key))) { return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()))); } } [Serializable] public class InvalidationExecption : Exception { public InvalidationExecption() : base("session cookie is invalid") { } public InvalidationExecption(string message) : base(message) { } public InvalidationExecption(string message, Exception inner) : base(message, inner) { } protected InvalidationExecption(SerializationInfo info, StreamingContext context) : base(info, context) { } } } }

你可能感兴趣的:(会话操纵)