ASP.NET面向角色授权之:自定义Forms用户验证与授权

来源:互联网 发布:c语言api函数 编辑:程序博客网 时间:2024/05/22 05:07

 

流程

一、配置config

n  基本内容

<configuration>

<system.web>

<authenticationmode="Forms">

<formsname=".WroxDemo" loginUrl="login.aspx"protection="All" timeout="60"/>

</authentication>

<machinekey  validationkey=”AutoGenerate” decrptionKey=”AutoGenerate”>//配置身份验证的加密解密和验证级别。

<authorization>

<denyusers="?">

</authorization>

</system.web>

</configuration>

 

<!—还可以配置某个目录的权限à

<lacatoinpath=”admin”>

<system.web>

<authorization>

<deny user=”?”>

</authorization>

</system.web>

</location>

 

 

二、填写与匹配帐户信息

//从数据库或文件取得填写的帐户信息

If(Dr.Read) //如果存在集合中

{

//则用户验证通过。

{

//方式四:创建自定义身份验证票 

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "yundao", DateTime.Now,DateTime.Now.AddMinutes(30), false, "admin"); 

//将身份验证票加密 

string EncrTicket = FormsAuthentication.Encrypt(ticket); 

//创建一个Cookie 

HttpCookiemyCookie = new HttpCookie(FormsAuthentication.FormsCookieName,EncrTicket); 

Cookie写入客户端 

Response.Cookies.Add(myCookie); 

 

//如果Cookie被禁

If(Request.Browser.Cookies==null)

{

Session["user_name"]= TextBoxUserName.Text;

Seesion[“user_pwd”]= TextBoxPwd.Text;

}

跳转到初始请求页或默认页面

//Response.Redirect(FormsAuthentication.GetRedirectUrl("yundao",false));

FormsAuthentication.RedirectFromLoginPage(txtEmail.Text,false)

}

}

 

三、 验证与授权

在初始访问页中(比如Default.aspx)验证与授权

If(Request.IsAuthenticated==true)//如果有访问权限

{

//do something

String pwd=””;

Stirng roles=””;

If(Request.Cookies[FormsAuthentication.FormsCookieName]==null)

{

Pwd = Session[“pwd”].tostring();

Roles = Session[“role”].toString();

}

Else

{

//获得存放身份验证票的Cookie值,这个值是经过加密的 

string EncrTicket =Request.Cookies[FormsAuthentication.FormsCookieName].Value; 

//获得身份验证票 

FormsAuthenticationTicket  ticket =FormsAuthentication.Decrypt(EncrTicket); 

//从身份验证票中提取经过验证的用户名 

string UserName = ticket.Name; 

//从身份验证票中提取用户数据 

string UserData = ticket.UserData; 

Label1.Text = UserName + ",您好!您的权限为:" + UserData; 

}

}

 

0 0
原创粉丝点击