在非SqlServer数据库上实现MemberShip和Role功能(自定义MemberShipProvider和RoleProvider)

本文涉及的产品
云数据库 RDS SQL Server,独享型 2核4GB
简介: 默认情况下,.Net网站上的MemberShip和Role功能只能用于SqlServer,如果要在其它数据库,比如Access,Oracle上使用该功能该怎么办呢? 其实MS早就为我们考虑到了,用户只要从MemberShipProvider和RoleProvider派生自己的Provider类,并...
默认情况下,.Net网站上的MemberShip和Role功能只能用于SqlServer,如果要在其它数据库,比如Access,Oracle上使用该功能该怎么办呢?

其实MS早就为我们考虑到了,用户只要从MemberShipProvider和RoleProvider派生自己的Provider类,并实现相关的方法和属性就可以了,其实ASPX中的MemberShip功能就是这二个抽象类在SqlServer上的实现(有兴趣的朋友可以查阅一下 System.Web.Security.SqlMembershipProvider)

这里只是给出一个MemberShip的演示,数据库结构如下:
用户表T_LoginUser
F_ID            用户ID
F_LoginName     登录名  
F_Password      登录密码

自定义一个MyMemberShipProvider类,这里只实现了三个方法( Initialize, ValidateUser, CreateUser)

using  System;
using  System.Data;
using  System.Data.SqlClient;
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;

/**/ /// <summary>
/// MyMemberShipProvider 的摘要说明
/// </summary>

public   class  MyMemberShipProvider:System.Web.Security.MembershipProvider
{
    
public MyMemberShipProvider()
    
{
        
//
        
// TODO: 在此处添加构造函数逻辑
        
//
    }



    
private string connStr;
    
private bool _requiresQuestionAndAnswer;
    
private int _minRequiredPasswordLength;

    
public override int MinRequiredPasswordLength
    
{
        
get return _minRequiredPasswordLength; }
    }

    
public override bool RequiresQuestionAndAnswer
    
{
        
get
        
{
            
return _requiresQuestionAndAnswer;
        }

    }


    
/**//// <summary>
    
/// 初始化
    
/// </summary>
    
/// <param name="name"></param>
    
/// <param name="config"></param>

    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);
    }


    
/**//// <summary>
    
/// 验证用户
    
/// </summary>
    
/// <param name="username"></param>
    
/// <param name="password"></param>
    
/// <returns></returns>

    public override bool ValidateUser(string username, string password)
    
{
        
using(SqlConnection conn = new SqlConnection(connStr))
        
{
            SqlCommand comm 
= new SqlCommand();
            comm.CommandText 
= "Select Top 1 * From T_LoginUser Where F_LoginName=@LoginName And F_PassWord=@Password";
            comm.Parameters.AddWithValue(
"@LoginName", username);
            comm.Parameters.AddWithValue(
"@Password", password);
            comm.Connection 
= conn;
            conn.Open();
            
using (SqlDataReader dr = comm.ExecuteReader())
            
{
                
if (dr.HasRows)
                
{                   
                   
return true;                    
                }

                
return false;
            }

        }
        
    }


    
/**//// <summary>
    
/// 创建用户
    
/// </summary>
    
/// <param name="username"></param>
    
/// <param name="password"></param>
    
/// <param name="email"></param>
    
/// <param name="passwordQuestion"></param>
    
/// <param name="passwordAnswer"></param>
    
/// <param name="isApproved"></param>
    
/// <param name="providerUserKey"></param>
    
/// <param name="status"></param>
    
/// <returns></returns>

    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(connStr))
        
{
            SqlCommand comm 
= new SqlCommand();
            comm.CommandText 
= "Insert Into T_LoginUser(F_LoginName,F_Password) values(@LoginName,@Password)";
            comm.Parameters.AddWithValue(
"LoginName", username);
            comm.Parameters.AddWithValue(
"Password", password);
            comm.Connection 
= conn;
            conn.Open();
            
try
            
{
                comm.ExecuteNonQuery();
            }

            
catch (Exception Ex)
            
{
                
throw new Exception("创建用户失败!原因:" + Ex.Message.ToString());
            }


            MembershipUser user 
= new MembershipUser("MyMemberShipProvider", username, providerUserKey, email, passwordQuestion, "", isApproved, true, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
            status 
= MembershipCreateStatus.Success;
            
return user;
        }

    }


    
public override string ApplicationName
    
{
        
get
        
{
            
throw new Exception("暂未实现");
        }

        
set
        
{
            
throw new Exception("暂未实现");
        }

    }


    
public override bool ChangePassword(string username, string oldPassword, string newPassword)
    
{
        
throw new Exception("暂未实现");
    }


    
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
    
{
        
throw new Exception("暂未实现");
    }


   

    
public override bool DeleteUser(string username, bool deleteAllRelatedData)
    
{
        
throw new Exception("暂未实现");
    }


    
public override bool EnablePasswordReset
    
{
        
get throw new Exception("暂未实现"); }
    }


    
public override bool EnablePasswordRetrieval
    
{
        
get throw new Exception("暂未实现"); }
    }


    
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
    
{
        
throw new Exception("暂未实现");
    }


    
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
    
{
        
throw new Exception("暂未实现");
    }


    
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
    
{
        
throw new Exception("暂未实现");
    }


    
public override int GetNumberOfUsersOnline()
    
{
        
throw new Exception("暂未实现");
    }


    
public override string GetPassword(string username, string answer)
    
{
        
throw new Exception("暂未实现");
    }


    
public override MembershipUser GetUser(string username, bool userIsOnline)
    
{
        
throw new Exception("暂未实现");
    }


    
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
    
{
        
throw new Exception("暂未实现");
    }


    
public override string GetUserNameByEmail(string email)
    
{
        
throw new Exception("暂未实现");
    }


    
public override int MaxInvalidPasswordAttempts
    
{
        
get throw new Exception("暂未实现"); }
    }


    
public override int MinRequiredNonAlphanumericCharacters
    
{
        
get throw new Exception("暂未实现"); }
    }



    
public override int PasswordAttemptWindow
    
{
        
get throw new Exception("暂未实现"); }
    }


    
public override MembershipPasswordFormat PasswordFormat
    
{
        
get throw new Exception("暂未实现"); }
    }


    
public override string PasswordStrengthRegularExpression
    
{
        
get throw new Exception("暂未实现"); }
    }


    
public override bool RequiresUniqueEmail
    
{
        
get throw new Exception("暂未实现"); }
    }


    
public override string ResetPassword(string username, string answer)
    
{
        
throw new Exception("暂未实现");
    }


    
public override bool UnlockUser(string userName)
    
{
        
throw new Exception("暂未实现");
    }


    
public override void UpdateUser(MembershipUser user)
    
{
        
throw new Exception("暂未实现");
    }

}



顺便也给个MyRoleProvider.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;

/**/ /// <summary>
/// MyRoleProvider 的摘要说明
/// </summary>

public   class  MyRoleProvider:System.Web.Security.RoleProvider
{
    
public MyRoleProvider()
    
{
        
//
        
// TODO: 在此处添加构造函数逻辑
        
//
    }


    
// 摘要:
    
//     获取或设置要存储和检索其角色信息的应用程序的名称。
    
//
    
// 返回结果:
    
//     要存储和检索其角色信息的应用程序的名称。
    public override string ApplicationName 
    
{
        
get throw new Exception("暂未实现"); }
        
set throw new Exception("暂未实现"); }
    }


    
// 摘要:
    
//     将指定用户名添加到已配置的 applicationName 的指定角色名。
    
//
    
// 参数:
    
//   roleNames:
    
//     一个字符串数组,其中包含要将指定用户名添加到的角色的名称。
    
//
    
//   usernames:
    
//     一个字符串数组,其中包含要添加到指定角色的用户名。
    public override void AddUsersToRoles(string[] usernames, string[] roleNames) 
    
{
        
throw new Exception("暂未实现");
    }


    
//
    
// 摘要:
    
//     在数据源中为已配置的 applicationName 添加一个新角色。
    
//
    
// 参数:
    
//   roleName:
    
//     要创建的角色的名称。
    public override void CreateRole(string roleName) 
    
{
        
throw new Exception("暂未实现");
    }


    
//
    
// 摘要:
    
//     从数据源中移除已配置的 applicationName 的角色。
    
//
    
// 参数:
    
//   throwOnPopulatedRole:
    
//     如果为 true,则在 roleName 具有一个或多个成员时引发异常,并且不删除 roleName。
    
//
    
//   roleName:
    
//     要删除的角色的名称。
    
//
    
// 返回结果:
    
//     如果成功删除角色,则为 true;否则为 false。
    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) 
    
{
        
throw new Exception("暂未实现");
    }

    
//
    
// 摘要:
    
//     获取属于某个角色且与指定的用户名相匹配的用户名的数组。
    
//
    
// 参数:
    
//   usernameToMatch:
    
//     要搜索的用户名。
    
//
    
//   roleName:
    
//     作为搜索范围的角色。
    
//
    
// 返回结果:
    
//     一个字符串数组,包含用户名与 usernameToMatch 匹配且用户是指定角色的成员的所有用户的名称。
    public override string[] FindUsersInRole(string roleName, string usernameToMatch) 
    
{
        
throw new Exception("暂未实现");
    }

    
//
    
// 摘要:
    
//     获取已配置的 applicationName 的所有角色的列表。
    
//
    
// 返回结果:
    
//     一个字符串数组,包含在数据源中存储的已配置的 applicationName 的所有角色的名称。
    public override string[] GetAllRoles() 
    
{
        
throw new Exception("暂未实现");
    }

    
//
    
// 摘要:
    
//     获取指定用户对于已配置的 applicationName 所属于的角色的列表。
    
//
    
// 参数:
    
//   username:
    
//     要为其返回角色列表的用户。
    
//
    
// 返回结果:
    
//     一个字符串数组,其中包含指定用户对于已配置的 applicationName 所属于的所有角色的名称。
    public override string[] GetRolesForUser(string username) 
    
{
        
throw new Exception("暂未实现");
    }

    
//
    
// 摘要:
    
//     获取属于已配置的 applicationName 的指定角色的用户的列表。
    
//
    
// 参数:
    
//   roleName:
    
//     一个角色名称,将获取该角色的用户列表。
    
//
    
// 返回结果:
    
//     一个字符串数组,其中包含属于已配置的 applicationName 的指定角色的成员的所有用户名。
    public override string[] GetUsersInRole(string roleName) 
    
{
        
throw new Exception("暂未实现");
    }

    
//
    
// 摘要:
    
//     获取一个值,指示指定用户是否属于已配置的 applicationName 的指定角色。
    
//
    
// 参数:
    
//   username:
    
//     要搜索的用户名。
    
//
    
//   roleName:
    
//     作为搜索范围的角色。
    
//
    
// 返回结果:
    
//     如果指定用户属于已配置的 applicationName 的指定角色,则为 true;否则为 false。
    public override bool IsUserInRole(string username, string roleName) 
    
{
        
throw new Exception("暂未实现");
    }


    
//
    
// 摘要:
    
//     移除已配置的 applicationName 的指定角色中的指定用户名。
    
//
    
// 参数:
    
//   roleNames:
    
//     一个字符串数组,其中包含要将指定用户名从中移除的角色的名称。
    
//
    
//   usernames:
    
//     一个字符串数组,其中包含要从指定角色中移除的用户名。
    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) 
    
{
        
throw new Exception("暂未实现");
    }


    
//
    
// 摘要:
    
//     获取一个值,该值指示指定角色名是否已存在于已配置的 applicationName 的角色数据源中。
    
//
    
// 参数:
    
//   roleName:
    
//     要在数据源中搜索的角色的名称。
    
//
    
// 返回结果:
    
//     如果角色名已存在于已配置的 applicationName 的数据源中,则为 true;否则为 false。
    public override bool RoleExists(string roleName) 
    
{
        
throw new Exception("暂未实现");
    }

}


下面是关键的Web。config配置
<? xml version="1.0" ?>

< configuration >
    
< appSettings />
    
< connectionStrings >
        
< add  name ="connStr"  connectionString ="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\demo.mdf;Integrated Security=True;User Instance=True"  providerName ="System.Data.SqlClient" />
    
</ connectionStrings >
    
< system.web >
        
        
< compilation  debug ="true" />
        
    
< authentication  mode ="Forms" >
      
< forms  defaultUrl ="~/Default.aspx"  name ="MemberShipProviderDemo"  cookieless ="UseCookies" ></ forms >
    
</ authentication >
    
    
    
        
< membership  defaultProvider ="MyMemberShipProvider" >
            
< providers >
                
< add  type ="MyMemberShipProvider"  name ="MyMemberShipProvider"  requiresQuestionAndAnswer ="false"  connectionString ="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\demo.mdf;Integrated Security=True;User Instance=True" />
            
</ providers >
        
</ membership >    
    
    
    
</ system.web >
</ configuration >

好了,随便建一个Default.aspx,放一个Login控件和 CreateUserWizard控件就可以测试了
相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS&nbsp;SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/sqlserver
目录
相关文章
|
1月前
|
SQL 安全 算法
【SQL server】玩转SQL server数据库:第四章 数据库安全性
【SQL server】玩转SQL server数据库:第四章 数据库安全性
69 12
|
3天前
|
SQL 存储 数据库连接
C#SQL Server数据库基本操作(增、删、改、查)
C#SQL Server数据库基本操作(增、删、改、查)
7 0
|
3天前
|
SQL 存储 小程序
数据库数据恢复—Sql Server数据库文件丢失的数据恢复案例
数据库数据恢复环境: 5块硬盘组建一组RAID5阵列,划分LUN供windows系统服务器使用。windows系统服务器内运行了Sql Server数据库,存储空间在操作系统层面划分了三个逻辑分区。 数据库故障: 数据库文件丢失,主要涉及3个数据库,数千张表。数据库文件丢失原因未知,不能确定丢失的数据库文件的存放位置。数据库文件丢失后,服务器仍处于开机状态,所幸未写入大量数据。
数据库数据恢复—Sql Server数据库文件丢失的数据恢复案例
|
12天前
|
数据管理 关系型数据库 MySQL
数据管理DMS产品使用合集之DMS可以接入其他平台的MySQL数据库,是否还支持无感知变更功能
阿里云数据管理DMS提供了全面的数据管理、数据库运维、数据安全、数据迁移与同步等功能,助力企业高效、安全地进行数据库管理和运维工作。以下是DMS产品使用合集的详细介绍。
|
16天前
|
SQL 调度 数据库
【Database】Sqlserver如何定时备份数据库和定时清除
【Database】Sqlserver如何定时备份数据库和定时清除
23 2
|
23天前
|
SQL Oracle 关系型数据库
常用数据库的分页语句(mySQL、oracle、PostgreSQL、SQL Server)
常用数据库的分页语句(mySQL、oracle、PostgreSQL、SQL Server)
|
1天前
|
关系型数据库 MySQL 数据库
docker MySQL删除数据库时的错误(errno: 39)
docker MySQL删除数据库时的错误(errno: 39)
|
1天前
|
关系型数据库 MySQL 数据库连接
用Navicat备份Mysql演示系统数据库的时候出:Too Many Connections
用Navicat备份Mysql演示系统数据库的时候出:Too Many Connections
|
2天前
|
存储 Oracle 关系型数据库
oracle 数据库 迁移 mysql数据库
将 Oracle 数据库迁移到 MySQL 是一项复杂的任务,因为这两种数据库管理系统具有不同的架构、语法和功能。
15 0
|
10天前
|
关系型数据库 MySQL Linux
【MySQL-10】数据库函数-案例演示【字符串/数值/日期/流程控制函数】(代码演示&可cv代码)
【MySQL-10】数据库函数-案例演示【字符串/数值/日期/流程控制函数】(代码演示&可cv代码)
【MySQL-10】数据库函数-案例演示【字符串/数值/日期/流程控制函数】(代码演示&可cv代码)