asp.Netforms認証、車輪の重複を避ける

7840 ワード

質問:forms検証では現在ログインしているユーザーのユーザー名以外の情報は得られないと言われていますが、私の小さな実験を経て、forms方式で持参したuserdataは私たちのために天地を発揮することができます.私の操作手順をメモします.
step 1: web.config構成のキー:
web.config構成
 
  


name=".ztinfozero" path="/Manager"
slidingExpiration="true" timeout="10">






Step 2:SiteUser Modelの構築
 
  
TopicUser Model
[Serializable]
public class TopicUser
{
public TopicUser() { }
model#region model
private System.Int32 _autoID;
/**////
///
///

public System.Int32 autoID
{
get { return _autoID; }
set { _autoID = value; }
}
private System.String _UserName;
/**////
///
///

public System.String UserName
{
get { return _UserName; }
set { _UserName = value; }
}
private System.String _UserChName;
/**////
///
///

public System.String UserChName
{
get { return _UserChName; }
set { _UserChName = value; }
}
private System.String _UserPass;
/**////
///
///

public System.String UserPass
{
get { return _UserPass; }
set { _UserPass = value; }
}
private System.String _DepartMent;
/**////
///
///

public System.String DepartMent
{
get { return _DepartMent; }
set { _DepartMent = value; }
}
private System.String _Duty;
/**////
///
///

public System.String Duty
{
get { return _Duty; }
set { _Duty = value; }
}
private System.Int32 _UserPermit;
/**////
///
///

public System.Int32 UserPermit
{
get { return _UserPermit; }
set { _UserPermit = value; }
}
private System.Int32 _Status;
/**////
///
///

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("window.top.location='login.aspx';");
Response.End();
}

これで、認証が完了します.ユーザーがログインしているかどうかを判断するコードをあちこちに積み上げる必要はありません.