Blog Reader RSS LoveCherry 技术无极限 GEO MVP MS Project开源技术

asp.net中使用窗体身份验证 [转]来源:小灰http://www.svnhost.cn/Article/Detail-23.shtml

转载地址:http://www.svnhost.cn/Article/Detail-23.shtml
1.
1<authentication mode="Forms"></authentication>
2.新建一个独立用户登录的类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;

namespace BLL
{
    
/// <summary>
    
/// 用户实用类
    
/// </summary>

    public sealed class UserUtil
    
{
        
public static void Login(string username, string roles, bool isPersistent)
        
{
            DateTime dt 
= isPersistent ? DateTime.Now.AddMinutes(99999) : DateTime.Now.AddMinutes(60);
            FormsAuthenticationTicket ticket 
= new FormsAuthenticationTicket(
                                                                                
1// 票据版本号
                                                                                username, // 票据持有者
                                                                                DateTime.Now, //分配票据的时间
                                                                                dt, // 失效时间
                                                                                isPersistent, // 需要用户的 cookie 
                                                                                roles, // 用户数据,这里其实就是用户的角色
                                                                                FormsAuthentication.FormsCookiePath);//cookie有效路径

            
//使用机器码machine key加密cookie,为了安全传送
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie 
= new HttpCookie(FormsAuthentication.FormsCookieName, hash); //加密之后的cookie

            
//将cookie的失效时间设置为和票据tikets的失效时间一致 
            if (ticket.IsPersistent)
            
{
                cookie.Expires 
= ticket.Expiration;
            }


            
//添加cookie到页面请求响应中
            HttpContext.Current.Response.Cookies.Add(cookie);
        }


        
public static void Logout()
        
{
            HttpCookie cookie 
= HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];

            
if (cookie == null)
            
{
                cookie 
= new HttpCookie(FormsAuthentication.FormsCookieName);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }

            cookie.Expires 
= DateTime.Now.AddYears(-10);
        }

    }

}

3.
//假设有UserInfo实体类,有UserInfo.GetUserInfoByPassword根据用户名,密码取用户的方法。chkCookie.Checked表示是否持久登录。true:下次打开浏览器自动登录。//u.Roles表示该用户的角色,如果没有启用角色的话,随便传值即可。
UserInfo u = UserInfo.GetUserInfoByPassword(txtUserName.Text, MD5(txtPassword.Text));
if (u!=null && u.UserId>0)
{
 UserUtil.Login(u.UserName, u.Roles chkCookie.Checked);
 
if (Request.QueryString["ReturnUrl"!= null && !Request.QueryString["ReturnUrl"].ToLower().Contains("login.aspx"))
    Response.Redirect(Request.QueryString[
"returnUrl"]);
 
else
    Response.Redirect(
"/");
}

else
 Label1.Text 
= "登录失败,可能是密码错误,请重新登录";
4.如果需要对登录用户也区别对待?这时用“角色”来处理就最方便了。首先需要建立如下类,该类是用来恢复用户身份和角色用的:
using System;
using System.Web;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Security.Principal;
using System.IO;

namespace BLL
{
    
/// <summary>
    
/// MyHttpModule 的摘要说明。
    
/// </summary>

    public class MyHttpModule : IHttpModule
    
{
        
public void Init(HttpApplication app)
        
{
            app.AuthenticateRequest 
+= new EventHandler(app_AuthenticateRequest);
            app.EndRequest 
+= new EventHandler(app_EndRequest);
        }


        
void app_EndRequest(object sender, EventArgs e)
        
{
            
foreach (string key in HttpContext.Current.Response.Cookies)
            
{
                HttpContext.Current.Response.Cookies[key].Domain 
= ConfigurationManager.AppSettings["domain"];//这里可以保证你的cookie都是顶级域名下的,可以实现二级域名,N级域名登录
            }

        }


        
public void Dispose() { }

        
private void app_AuthenticateRequest(object sender, EventArgs e)
        
{
            
// 提取窗体身份验证 cookie
            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie 
= HttpContext.Current.Request.Cookies[cookieName];

            
if (null == authCookie)
            
{
                
// 没有身份验证 cookie。
                return;
            }


            FormsAuthenticationTicket authTicket 
= null;
            authTicket 
= FormsAuthentication.Decrypt(authCookie.Value);

            
if (null == authTicket)
            
{
                
// 无法解密 Cookie。
                return;
            }

            
// 创建票证后,为 UserData 属性指定一个
            
// 以管道符分隔的角色名字符串。
            string[] roles = authTicket.UserData.Split(new char[] ',' });


            
// 创建一个标识对象
            FormsIdentity id = new FormsIdentity(authTicket);

            
// 该主体将通过整个请求。
            GenericPrincipal principal = new GenericPrincipal(id, roles);
            
// 将新的主体对象附加到当前的 HttpContext 对象
            HttpContext.Current.User = principal;
        }

    }

}

posted @ 2008-06-03 19:44  大宋提刑官  阅读(207)  评论(0编辑  收藏  举报