asp.net 2.0下自动登录,SkipAuthorization问题
想在网站上实现自动登录。网站中有些页面不需要登录,像注册页面,有些必须登录,不过实现的时候需要登录的页面都正常,而有的页面不需要登录的却自动跳转到登录页面了。采用cookie+Session+配置文件实现。网站中使用了asp.ajax。
当网页中有请求WebResource.axd时,SkipAuthorization为false了,比较麻烦。
顺便问下应该注册什么事件比较好?
代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using Common.Web;
using Model.Users;
namespace BLL
{
public class AutoLoginHttpModule : IHttpModule
{
private HttpApplication _applicationContext;
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
this._applicationContext = context;
this._applicationContext.PostRequestHandlerExecute += new EventHandler(_applicationContext_PreRequestHandlerExecute);
}
#endregion
/// <summary>
/// 使用cookie和session的Forms验证实现网站自动登录
/// </summary>
/// <param name= "sender "> </param>
/// <param name= "e "> </param>
void _applicationContext_PreRequestHandlerExecute(object sender, EventArgs e)
{
//检查配置文件是否跳过授权检查
if (HttpContext.Current.SkipAuthorization ) return;
//只针对aspx页面进行检查
int dotIndex = this._applicationContext.Request.Url.LocalPath.LastIndexOf( ". ");
if(dotIndex > -1)
{
string aspx = this._applicationContext.Request.Url.LocalPath.Substring(dotIndex + 1);
if(string.Compare(aspx, "aspx ",true) != 0 )
return;
}
if(!FormsAuthentication.CookiesSupported && HttpContext.Current != null && HttpContext.Current.Response != null )
{
HttpContext.Current.Response.Write(string.Format( " <script language= 'javascript '> alert( '{0} '); </script> ", "必须开启Cookie才能正常登录! "));
return;
}
HttpCookie cookie = this._applicationContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
if (AppContext.Current.User.UserID > 0) return;
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket != null && !ticket.Expired)
{
QueryResult result;
UserInfo info = BLL.Users.User.LoadByLoginName(ticket.Name, out result);
if (info != null)
{
AppContext.Current.SetUserInfo(info);
BLLUtility.SetFormsAuthenticationCookie(ticket.Name, ticket.IsPersistent);
return;
}
}
}
this.RedirectToLoginPage();
}
private void RedirectToLoginPage()
{
if (string.Compare(this._applicationContext.Request.Url.LocalPath, FormsAuthentication.LoginUrl, true) != 0)
{
FormsAuthentication.RedirectToLoginPage();
}
}
}
}
[解决办法]
啊啊,太长了,自动登录的实现:
常用的就是在客户端保存cookie然后 在打个页面的时候把cookie转成session
[解决办法]
不懂 帮你顶下
[解决办法]
做一公共界面或公用函数..加以判断...