欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net forms身份验证,避免重复造*

程序员文章站 2024-03-08 16:20:42
问题:大家都说使用 forms 验证无法得到当前登录用户除了用户名之外的更多信息,经过我的一番小试验,在 forms 方式下自带的 userdata 可以为我们施展天地的地...
问题:大家都说使用 forms 验证无法得到当前登录用户除了用户名之外的更多信息,经过我的一番小试验,在 forms 方式下自带的 userdata 可以为我们施展天地的地方。下面记录一下我的操作步骤备忘。
step 1: web.config 配置关键地方:
web.config配置
复制代码 代码如下:

<!--
通过 <authentication> 节可以配置 asp.net 用来
识别进入用户的
安全身份验证模式。
-->
<authentication mode="forms">
<forms loginurl="login.aspx" defaulturl="index.aspx"
name=".ztinfozero" path="/manager"
slidingexpiration="true" timeout="10"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>

step 2: 构造 siteuser model
复制代码 代码如下:

topicuser model
[serializable]
public class topicuser
{
public topicuser() { }
model#region model
private system.int32 _autoid;
/**//// <summary>
///
/// </summary>
public system.int32 autoid
{
get { return _autoid; }
set { _autoid = value; }
}
private system.string _username;
/**//// <summary>
/// 用户名
/// </summary>
public system.string username
{
get { return _username; }
set { _username = value; }
}
private system.string _userchname;
/**//// <summary>
/// 真实姓名
/// </summary>
public system.string userchname
{
get { return _userchname; }
set { _userchname = value; }
}
private system.string _userpass;
/**//// <summary>
///
/// </summary>
public system.string userpass
{
get { return _userpass; }
set { _userpass = value; }
}
private system.string _department;
/**//// <summary>
///
/// </summary>
public system.string department
{
get { return _department; }
set { _department = value; }
}
private system.string _duty;
/**//// <summary>
///
/// </summary>
public system.string duty
{
get { return _duty; }
set { _duty = value; }
}
private system.int32 _userpermit;
/**//// <summary>
///
/// </summary>
public system.int32 userpermit
{
get { return _userpermit; }
set { _userpermit = value; }
}
private system.int32 _status;
/**//// <summary>
///
/// </summary>
public system.int32 status
{
get { return _status; }
set { _status = value; }
}
#endregion
}

step 3: 创建用户登录代码:

数据库-用户登录方法
复制代码 代码如下:

public topicuser userlogon(string username, string pass) {
string proc = "dbo.infozero_proc_userlogon";
database db = datafactory.userdb;
dbcommand cmd = db.getstoredproccommand(proc);
db.addinparameter(cmd, "@username", dbtype.string, username);
db.addinparameter(cmd, "@userpass", dbtype.string, pass);
db.addoutparameter(cmd, "@result", dbtype.int32, 4);
dataset ds = db.executedataset(cmd);
topicuser user = null;
int result = 0;
if (int.tryparse(db.getparametervalue(cmd, "@result").tostring(), out result) )
user = tabletouser(ds.tables[0]);
return user;
}
#region table to user
private topicuser tabletouser(datatable dt) {
topicuser model = null;
if (dt.rows.count > 0) {
model = new topicuser();
datarow dr = dt.rows[0];
int aid = 0;
int.tryparse(dr["autoid"].tostring(), out aid );
model.autoid = aid;
model.username = dr["username"].tostring();
model.userchname = dr["userchname"].tostring();
model.userpass = dr["userpass"].tostring();
model.department = dr["department"].tostring();
model.duty = dr["duty"].tostring();
if (dr["userpermit"].tostring() != "")
{
model.userpermit = int.parse(dr["userpermit"].tostring());
}
if (dr["status"].tostring() != "")
{
model.status = int.parse(dr["status"].tostring());
}
}
return model;
}
#endregion

step 4 : 创建登录页:

代码
复制代码 代码如下:

protected void btnok_click(object sender, eventargs e)
{
string username = tbname.text.trim();
string pass = tbpass.text.trim();
if (!string.isnullorempty(username)) {
if (!string.isnullorempty(pass)) {
dataservice.user b = new dataservice.user();
dataservice.topicuser user = b.userlogon(username, pass);
if (user != null) {
//roles , userid | userchname
string userdata = string.format("{0},{1}|{2}",
user.userpermit, user.autoid, user.userchname);
formsauthenticationticket ticket = new formsauthenticationticket(
, username, datetime.now, datetime.now.addhours(2),
true, userdata);
string encticket = formsauthentication.encrypt(ticket);
httpcookie cookie = new httpcookie(
formsauthentication.formscookiename, encticket);
response.cookies.add(cookie);
response.redirect("index.aspx");
}
}
}
}

step 5: 在 global.asax 里添加 application_authenticaterequest 事件以设置当前登录用户的信息:
复制代码 代码如下:

protected void application_authenticaterequest(object sender, eventargs e)
{
httpcookie cookie = context.request.cookies[formsauthentication.formscookiename];
if (cookie != null) {
formsauthenticationticket ticket = formsauthentication.decrypt(cookie.value);
if (ticket != null) {
string[] roles = ticket.userdata.split(',');
formsidentity id = new formsidentity(ticket);
system.security.principal.genericprincipal principal = new genericprincipal(id, roles);
context.user = principal;
}
}
}

step 6: 如何得到当前登录用户的信息
复制代码 代码如下:

public static topicuser currentuser {
get {
dataservice.topicuser user = new dataservice.topicuser();
formsidentity identity = httpcontext.current.user.identity as formsidentity;
formsauthenticationticket ticket = identity.ticket;
string userdata = ticket.userdata; //获取自定义的 userdata 串
if (!string.isnullorempty(userdata)) {
if (userdata.indexof(',') > 0 && userdata.indexof('|') > 0)
{
//roles , userid | userchname
string uinfo = userdata.split(',')[1];
string[] u = uinfo.split('|');
int uid = 0;
int.tryparse(u[0], out uid);
user.autoid = uid;
user.userchname = u[1];
user.username = httpcontext.current.user.identity.name;
}
}
return user;
}
}

由此得到当前登录用户的 id 为 userbase.currentuser.autoid ; 真实名字是: userbase.currentuser.userchname ;
判断当前用户的角色是否为管理员: httpcontext.current.user.isinrole("1") ; // 1 为管理员
退出当前登录的方法:
logout.aspx
复制代码 代码如下:

protected void page_load(object sender, eventargs e)
{
system.web.security.formsauthentication.signout();
response.write("<script>window.top.location='login.aspx';</script>");
response.end();
}

至此,身份验证完成。我们不用费尽心思在四处堆放用户是否登录判断的代码了。