Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)aaa
published in(发表于) 2013/12/8 7:51:00
asp.net身份验证和授权_.net资料_编程技术

asp.net身份验证和授权_.net资料_编程技术-你的首页-uuhomepage.com





今天闲着无聊.想起来了ASP.NET身份验证.感觉良好.贴出下列代码:
login.aspx HTML代码





1<%@ Page language="c#" Codebehind="02Login.aspx.cs" AutoEventWireup="false" Inherits="身份验证._02Login" %>
2
3
4
5 02Login
6
7
8
9 http://schemas.microsoft.com/intellisense/ie5">
10
11
12
13
14 15 cellSpacing="1" cellPadding="1" width="446" border="1">
16
17
18 用户名称:
19
20
21
22
23
24
25
26 密码:
27
28
29
30
31
32
33 是否保存Cookie
34
35
36
37
38
39 40 runat="server" Width="78px" Text="登录">
41 42 runat="server" NavigateUrl="Default.aspx">HyperLink

43


44
45
login.aspx.cs代码如下







private void btnLoginBetter_Click(object sender, System.EventArgs e)
{
if (this.tbName.Text == "admin" && this.tbPass.Text == "admin")
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,this.tbName.Text,DateTime.Now,DateTime.Now.AddMinutes(30),this.PersistCookie.Checked,"User");//创建一个验证票据
string cookieStr = FormsAuthentication.Encrypt(ticket);进行加密
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,cookieStr);创建一个cookie,cookie名为web.config设置的名,值为加密后的数据cookieStr,
if (this.PersistCookie.Checked)//判断用户是否选中保存cookie
cookie.Expires = ticket.Expiration;//获取cookie过期时间
cookie.Path = FormsAuthentication.FormsCookiePath;//设置cookie保存路径
Response.Cookies.Add(cookie);
string strRedirect;
strRedirect = Request["ReturnUrl"];//取出返回url
if (strRedirect == null)
strRedirect = "Default.aspx";
Response.Redirect(strRedirect,true);




}
else
{
Response.Write("");
}
}








Default.aspx HTML代码










用户名称:
身份:


runat="server" Text="注销" Width="101px">



后置代码







private void Page_Load(object sender, System.EventArgs e)
{
this.lbUser.Text = User.Identity.Name;
if (User.IsInRole("Admin"))
this.lbSf.Text = "Admin";
else
this.lbSf.Text = "User";
}




Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/**////


/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///

private void InitializeComponent()
{
this.btnLogout.Click += new System.EventHandler(this.btnLogout_Click);
this.Load += new System.EventHandler(this.Page_Load);




}
#endregion




private void btnLogout_Click(object sender, System.EventArgs e)
{
FormsAuthentication.SignOut();//注销票
Response.Redirect("login.aspx",true);返回login.aspx页面
}





webconfig配置如下

//.SecurityDemo为cookie名,





//拒绝所有匿名用户
//允许管理级别用户访问

自我感觉ASP写多了,一般是用session进行判断用户是否合法,但在一个ASP.NET项目中使用身份验证,基本上所有页面都要验证才能访问,感觉有点迁强.但可以在web.config页面对指定的页面设置权限,设置代码如下







如果只有几个页面设置如上代码,感觉还可以接受.但页面多了岂不是要把人累死呀..
可能是小的项目做多了,大项目没接触过.请高手给指点具体用途呀.不甚感激














If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759