在看2.0里的基于角色的安全技术,用了用提供的一些控件,如LOGIN控件,注册控件等,写了一些代码,贴出来给自己留个底底。
没有用它的那个自带的ASPNETDB.MDF的库,直接连接的我本地的SQL。连接代码在web.config中,在CS里直接读取。
在web.config中重新定义了membership和roleManager,指向了我自己的类,覆写了基类的一些东东。在web.config中规定了页面需要的权限,实现了分权限的浏览。
覆写了RoleProvider中的GetRolesForUser和GetAllRoles方法,用来判断我在自己数据库里定义的权限。
覆写了MembershipProvider中的Initialize、CreateUser、MinRequiredPasswordLength、RequiresQuestionAndAnswer以及ValidateUser方法,实现操作自己指定的数据库。
大概的方法就是这些了,如果自己要是想写删除更新什么的,覆写相对应的方法就好了。
具体程序代码如下,给出了MyRole.cs、MyMemberShip.cs和web.config的全部代码。前台拖拖控件就好了,代码不再给出。
MyMemberShip.cs
using
System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Data.SqlClient;
/// <summary>
/// MyMemberShip 的摘要说明
/// </summary>
public class MyMemberShip : MembershipProvider
{
public MyMemberShip()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
string connectionstring = ConfigurationManager.ConnectionStrings["SqlServices"].ConnectionString.ToString();
private bool _requiresQuestionAndAnswer;
private int _minRequiredPasswordLength;
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
if (config["requiresQuestionAndAnswer"].ToLower() == "true")
{
_requiresQuestionAndAnswer = true;
}
else
{
_requiresQuestionAndAnswer = false;
}
int.TryParse(config["minRequiredPasswordLength"], out _minRequiredPasswordLength);
//connStr = config["connectionString"];
base.Initialize(name, config);
}
public override string ApplicationName
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new Exception("The method or operation is not implemented.");
}
public override MembershipUser CreateUser(string username,string password,string email,string passwordQuestion,string passwordAnswer,bool isApproved,Object providerUserKey,out MembershipCreateStatus status)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand comm = new SqlCommand();
comm.CommandText = "insert into users(u_name,u_pwd,u_role) values(@cname,@cpwd,@crole)";
comm.Parameters.AddWithValue("@cname", username);
comm.Parameters.AddWithValue("@cpwd", password);
comm.Parameters.AddWithValue("@crole", "guest");
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
MembershipUser user = new MembershipUser("MyMemberShip", username, providerUserKey, email, passwordQuestion, "", isApproved, true, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
status = MembershipCreateStatus.Success;
return user;
}
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool EnablePasswordReset
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override bool EnablePasswordRetrieval
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new Exception("The method or operation is not implemented.");
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new Exception("The method or operation is not implemented.");
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new Exception("The method or operation is not implemented.");
}
public override int GetNumberOfUsersOnline()
{
throw new Exception("The method or operation is not implemented.");
}
public override string GetPassword(string username, string answer)
{
throw new Exception("The method or operation is not implemented.");
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
throw new Exception("The method or operation is not implemented.");
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new Exception("The method or operation is not implemented.");
}
public override string GetUserNameByEmail(string email)
{
throw new Exception("The method or operation is not implemented.");
}
public override int MaxInvalidPasswordAttempts
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override int MinRequiredNonAlphanumericCharacters
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override int MinRequiredPasswordLength
{
get { return _minRequiredPasswordLength; }
}
public override int PasswordAttemptWindow
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override MembershipPasswordFormat PasswordFormat
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override string PasswordStrengthRegularExpression
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override bool RequiresQuestionAndAnswer
{
get { return _requiresQuestionAndAnswer; }
}
public override bool RequiresUniqueEmail
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override string ResetPassword(string username, string answer)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool UnlockUser(string userName)
{
throw new Exception("The method or operation is not implemented.");
}
public override void UpdateUser(MembershipUser user)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool ValidateUser(string username, string password)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand comm = new SqlCommand();
comm.CommandText = "select count(0) from users where u_name=@cname and u_pwd=@cpwd";
comm.Parameters.AddWithValue("@cname", username);
comm.Parameters.AddWithValue("@cpwd", password);
comm.Connection = conn;
conn.Open();
return ((int)comm.ExecuteScalar()) > 0 ? true : false;
}
}
}
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Data.SqlClient;
/// <summary>
/// MyMemberShip 的摘要说明
/// </summary>
public class MyMemberShip : MembershipProvider
{
public MyMemberShip()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
string connectionstring = ConfigurationManager.ConnectionStrings["SqlServices"].ConnectionString.ToString();
private bool _requiresQuestionAndAnswer;
private int _minRequiredPasswordLength;
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
if (config["requiresQuestionAndAnswer"].ToLower() == "true")
{
_requiresQuestionAndAnswer = true;
}
else
{
_requiresQuestionAndAnswer = false;
}
int.TryParse(config["minRequiredPasswordLength"], out _minRequiredPasswordLength);
//connStr = config["connectionString"];
base.Initialize(name, config);
}
public override string ApplicationName
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new Exception("The method or operation is not implemented.");
}
public override MembershipUser CreateUser(string username,string password,string email,string passwordQuestion,string passwordAnswer,bool isApproved,Object providerUserKey,out MembershipCreateStatus status)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand comm = new SqlCommand();
comm.CommandText = "insert into users(u_name,u_pwd,u_role) values(@cname,@cpwd,@crole)";
comm.Parameters.AddWithValue("@cname", username);
comm.Parameters.AddWithValue("@cpwd", password);
comm.Parameters.AddWithValue("@crole", "guest");
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
MembershipUser user = new MembershipUser("MyMemberShip", username, providerUserKey, email, passwordQuestion, "", isApproved, true, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
status = MembershipCreateStatus.Success;
return user;
}
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool EnablePasswordReset
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override bool EnablePasswordRetrieval
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new Exception("The method or operation is not implemented.");
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new Exception("The method or operation is not implemented.");
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new Exception("The method or operation is not implemented.");
}
public override int GetNumberOfUsersOnline()
{
throw new Exception("The method or operation is not implemented.");
}
public override string GetPassword(string username, string answer)
{
throw new Exception("The method or operation is not implemented.");
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
throw new Exception("The method or operation is not implemented.");
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new Exception("The method or operation is not implemented.");
}
public override string GetUserNameByEmail(string email)
{
throw new Exception("The method or operation is not implemented.");
}
public override int MaxInvalidPasswordAttempts
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override int MinRequiredNonAlphanumericCharacters
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override int MinRequiredPasswordLength
{
get { return _minRequiredPasswordLength; }
}
public override int PasswordAttemptWindow
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override MembershipPasswordFormat PasswordFormat
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override string PasswordStrengthRegularExpression
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override bool RequiresQuestionAndAnswer
{
get { return _requiresQuestionAndAnswer; }
}
public override bool RequiresUniqueEmail
{
get { throw new Exception("The method or operation is not implemented."); }
}
public override string ResetPassword(string username, string answer)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool UnlockUser(string userName)
{
throw new Exception("The method or operation is not implemented.");
}
public override void UpdateUser(MembershipUser user)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool ValidateUser(string username, string password)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand comm = new SqlCommand();
comm.CommandText = "select count(0) from users where u_name=@cname and u_pwd=@cpwd";
comm.Parameters.AddWithValue("@cname", username);
comm.Parameters.AddWithValue("@cpwd", password);
comm.Connection = conn;
conn.Open();
return ((int)comm.ExecuteScalar()) > 0 ? true : false;
}
}
}
MyRole.cs
using
System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Data.SqlClient;
/// <summary>
/// MyRole 的摘要说明
/// </summary>
public class MyRole : RoleProvider
{
public MyRole()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
string connectionstring = ConfigurationManager.ConnectionStrings["SqlServices"].ConnectionString.ToString();
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new Exception("The method or operation is not implemented.");
}
public override string ApplicationName
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
public override void CreateRole(string roleName)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new Exception("The method or operation is not implemented.");
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new Exception("The method or operation is not implemented.");
}
public override string[] GetAllRoles()
{
return new string[] { "admin", "guest" };
}
public override string[] GetRolesForUser(string username)
{
string[] tmp = new string[] { };
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand comm = new SqlCommand();
comm.CommandText = "select top 1 * from users where u_name=@name";
comm.Parameters.AddWithValue("@name", username);
comm.Connection = conn;
conn.Open();
using (SqlDataReader dr = comm.ExecuteReader())
{
if (dr.Read())
{
tmp = dr["U_role"].ToString().Split(',');
}
}
conn.Close();
}
return tmp;
}
public override string[] GetUsersInRole(string roleName)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool IsUserInRole(string username, string roleName)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand comm = new SqlCommand();
comm.CommandText = "select top 1 * from users where u_name=@name and u_role=@role";
comm.Parameters.AddWithValue("@name", username);
comm.Parameters.AddWithValue("@role", roleName);
comm.Connection = conn;
conn.Open();
using (SqlDataReader dr = comm.ExecuteReader())
{
if (dr.HasRows)
{
return true;
}
return false;
}
}
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool RoleExists(string roleName)
{
throw new Exception("The method or operation is not implemented.");
}
}
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Data.SqlClient;
/// <summary>
/// MyRole 的摘要说明
/// </summary>
public class MyRole : RoleProvider
{
public MyRole()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
string connectionstring = ConfigurationManager.ConnectionStrings["SqlServices"].ConnectionString.ToString();
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new Exception("The method or operation is not implemented.");
}
public override string ApplicationName
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
public override void CreateRole(string roleName)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new Exception("The method or operation is not implemented.");
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new Exception("The method or operation is not implemented.");
}
public override string[] GetAllRoles()
{
return new string[] { "admin", "guest" };
}
public override string[] GetRolesForUser(string username)
{
string[] tmp = new string[] { };
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand comm = new SqlCommand();
comm.CommandText = "select top 1 * from users where u_name=@name";
comm.Parameters.AddWithValue("@name", username);
comm.Connection = conn;
conn.Open();
using (SqlDataReader dr = comm.ExecuteReader())
{
if (dr.Read())
{
tmp = dr["U_role"].ToString().Split(',');
}
}
conn.Close();
}
return tmp;
}
public override string[] GetUsersInRole(string roleName)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool IsUserInRole(string username, string roleName)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand comm = new SqlCommand();
comm.CommandText = "select top 1 * from users where u_name=@name and u_role=@role";
comm.Parameters.AddWithValue("@name", username);
comm.Parameters.AddWithValue("@role", roleName);
comm.Connection = conn;
conn.Open();
using (SqlDataReader dr = comm.ExecuteReader())
{
if (dr.HasRows)
{
return true;
}
return false;
}
}
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new Exception("The method or operation is not implemented.");
}
public override bool RoleExists(string roleName)
{
throw new Exception("The method or operation is not implemented.");
}
}
web.config
<?
xml version="1.0"
?>
< configuration >
< appSettings />
< connectionStrings >
< add name ="SqlServices" connectionString ="server=;database=;uid=;pwd=;"
providerName ="System.Data.SqlClient" />
</ connectionStrings >
< system .web >
< compilation debug ="true" />
< authentication mode ="Forms" >
< forms defaultUrl ="default.aspx" loginUrl ="userlogin.aspx" path ="/" name ="mytest" />
</ authentication >
< membership defaultProvider ="MyMemberShip" userIsOnlineTimeWindow ="20" >
< providers >
< remove name ="AspNetSqlProvider" />
< add name ="MyMemberShip"
type ="MyMemberShip"
connectionStringName ="SqlServices"
enablePasswordRetrieval ="false"
enablePasswordReset ="true"
requiresQuestionAndAnswer ="true"
passwordFormat ="Hashed"
applicationName ="/" />
</ providers >
</ membership >
< roleManager defaultProvider ="MyRole" enabled ="true" >
< providers >
< add name ="MyRole" type ="MyRole" />
</ providers >
</ roleManager >
</ system.web >
< location path ="admin.aspx" >
< system .web >
< authorization >
< allow roles ="admin" />
< deny users ="*" />
</ authorization >
</ system.web >
</ location >
< location path ="guest.aspx" >
< system .web >
< authorization >
< allow roles ="guest" />
< deny users ="*" />
</ authorization >
</ system.web >
</ location >
</ configuration >
< configuration >
< appSettings />
< connectionStrings >
< add name ="SqlServices" connectionString ="server=;database=;uid=;pwd=;"
providerName ="System.Data.SqlClient" />
</ connectionStrings >
< system .web >
< compilation debug ="true" />
< authentication mode ="Forms" >
< forms defaultUrl ="default.aspx" loginUrl ="userlogin.aspx" path ="/" name ="mytest" />
</ authentication >
< membership defaultProvider ="MyMemberShip" userIsOnlineTimeWindow ="20" >
< providers >
< remove name ="AspNetSqlProvider" />
< add name ="MyMemberShip"
type ="MyMemberShip"
connectionStringName ="SqlServices"
enablePasswordRetrieval ="false"
enablePasswordReset ="true"
requiresQuestionAndAnswer ="true"
passwordFormat ="Hashed"
applicationName ="/" />
</ providers >
</ membership >
< roleManager defaultProvider ="MyRole" enabled ="true" >
< providers >
< add name ="MyRole" type ="MyRole" />
</ providers >
</ roleManager >
</ system.web >
< location path ="admin.aspx" >
< system .web >
< authorization >
< allow roles ="admin" />
< deny users ="*" />
</ authorization >
</ system.web >
</ location >
< location path ="guest.aspx" >
< system .web >
< authorization >
< allow roles ="guest" />
< deny users ="*" />
</ authorization >
</ system.web >
</ location >
</ configuration >
User.Identity.Name可以直接得到登录的名称,有一定的声明周期,可以在WEB.CONFIG中进行修改。
admin.aspx.cs
public
partial
class
admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("您的登录名称:" + User.Identity.Name + " <br>权限为:");
foreach (string s in Roles.GetRolesForUser())
{
Response.Write("<li>" + s + "</li>");
}
}
}
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("您的登录名称:" + User.Identity.Name + " <br>权限为:");
foreach (string s in Roles.GetRolesForUser())
{
Response.Write("<li>" + s + "</li>");
}
}
}