`

RoleProvider的重写(转至msdn)

    博客分类:
  • C#
阅读更多

using System.Configuration.Provider;
using System.Collections.Specialized; using System;
using System.Data;
using System.Data.Odbc;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using System.Globalization;

/*

This provider works with the following schema for the tables of role data.

CREATE TABLE Roles
(
Rolename Text (255) NOT NULL,
ApplicationName Text (255) NOT NULL,
CONSTRAINT PKRoles PRIMARY KEY (Rolename, ApplicationName)
)

CREATE TABLE UsersInRoles
(
Username Text (255) NOT NULL,
Rolename Text (255) NOT NULL,
ApplicationName Text (255) NOT NULL,
CONSTRAINT PKUsersInRoles PRIMARY KEY (Username, Rolename, ApplicationName)
)

*/



namespace Samples.AspNet.Roles
{

public sealed class OdbcRoleProvider: RoleProvider
{

//
// Global connection string, generic exception message, event log info.
//

private string eventSource = "OdbcRoleProvider";
private string eventLog = "Application";
private string exceptionMessage = "An exception occurred. Please check the Event Log.";

private ConnectionStringSettings pConnectionStringSettings;
private string connectionString;


//
// If false, exceptions are thrown to the caller. If true,
// exceptions are written to the event log.
//

private bool pWriteExceptionsToEventLog = false;

public bool WriteExceptionsToEventLog
{
get { return pWriteExceptionsToEventLog; }
set { pWriteExceptionsToEventLog = value; }
}



//
// System.Configuration.Provider.ProviderBase.Initialize Method
//

public override void Initialize(string name, NameValueCollection config)
{

//
// Initialize values from web.config.
//

if (config == null)
throw new ArgumentNullException("config");

if (name == null || name.Length == 0)
name = "OdbcRoleProvider";

if (String.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Sample ODBC Role provider");
}

// Initialize the abstract base class.
base.Initialize(name, config);


if (config["applicationName"] == null || config["applicationName"].Trim() == "")
{
pApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
}
else
{
pApplicationName = config["applicationName"];
}


if (config["writeExceptionsToEventLog"] != null)
{
if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
{
pWriteExceptionsToEventLog = true;
}
}


//
// Initialize OdbcConnection.
//

pConnectionStringSettings = ConfigurationManager.
ConnectionStrings[config["connectionStringName"]];

if (pConnectionStringSettings == null || pConnectionStringSettings.ConnectionString.Trim() == "")
{
throw new ProviderException("Connection string cannot be blank.");
}

connectionString = pConnectionStringSettings.ConnectionString;
}



//
// System.Web.Security.RoleProvider properties.
//


private string pApplicationName;


public override string ApplicationName
{
get { return pApplicationName; }
set { pApplicationName = value; }
}

//
// System.Web.Security.RoleProvider methods.
//

//
// RoleProvider.AddUsersToRoles
//

public override void AddUsersToRoles(string[] usernames, string[] rolenames)
{
foreach (string rolename in rolenames)
{
if (!RoleExists(rolename))
{
throw new ProviderException("Role name not found.");
}
}

foreach (string username in usernames)
{
if (username.Contains(","))
{
throw new ArgumentException("User names cannot contain commas.");
}

foreach (string rolename in rolenames)
{
if (IsUserInRole(username, rolename))
{
throw new ProviderException("User is already in role.");
}
}
}


OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("INSERT INTO UsersInRoles " +
" (Username, Rolename, ApplicationName) " +
" Values(?, ?, ?)", conn);

OdbcParameter userParm = cmd.Parameters.Add("@Username", OdbcType.VarChar, 255);
OdbcParameter roleParm = cmd.Parameters.Add("@Rolename", OdbcType.VarChar, 255);
cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

OdbcTransaction tran = null;

try
{
conn.Open();
tran = conn.BeginTransaction();
cmd.Transaction = tran;

foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
userParm.Value = username;
roleParm.Value = rolename;
cmd.ExecuteNonQuery();
}
}

tran.Commit();
}
catch (OdbcException e)
{
try
{
tran.Rollback();
}
catch { }


if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "AddUsersToRoles");
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
}


//
// RoleProvider.CreateRole
//

public override void CreateRole(string rolename)
{
if (rolename.Contains(","))
{
throw new ArgumentException("Role names cannot contain commas.");
}

if (RoleExists(rolename))
{
throw new ProviderException("Role name already exists.");
}

OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("INSERT INTO Roles " +
" (Rolename, ApplicationName) " +
" Values(?, ?)", conn);

cmd.Parameters.Add("@Rolename", OdbcType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

try
{
conn.Open();

cmd.ExecuteNonQuery();
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "CreateRole");
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
}


//
// RoleProvider.DeleteRole
//

public override bool DeleteRole(string rolename, bool throwOnPopulatedRole)
{
if (!RoleExists(rolename))
{
throw new ProviderException("Role does not exist.");
}

if (throwOnPopulatedRole && GetUsersInRole(rolename).Length > 0)
{
throw new ProviderException("Cannot delete a populated role.");
}

OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("DELETE FROM Roles " +
" WHERE Rolename = ? AND ApplicationName = ?", conn);

cmd.Parameters.Add("@Rolename", OdbcType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;


OdbcCommand cmd2 = new OdbcCommand("DELETE FROM UsersInRoles " +
" WHERE Rolename = ? AND ApplicationName = ?", conn);

cmd2.Parameters.Add("@Rolename", OdbcType.VarChar, 255).Value = rolename;
cmd2.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

OdbcTransaction tran = null;

try
{
conn.Open();
tran = conn.BeginTransaction();
cmd.Transaction = tran;
cmd2.Transaction = tran;

cmd2.ExecuteNonQuery();
cmd.ExecuteNonQuery();

tran.Commit();
}
catch (OdbcException e)
{
try
{
tran.Rollback();
}
catch { }


if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "DeleteRole");

return false;
}
else
{
throw e;
}
}
finally
{
conn.Close();
}

return true;
}


//
// RoleProvider.GetAllRoles
//

public override string[] GetAllRoles()
{
string tmpRoleNames = "";

OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("SELECT Rolename FROM Roles " +
" WHERE ApplicationName = ?", conn);

cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

OdbcDataReader reader = null;

try
{
conn.Open();

reader = cmd.ExecuteReader();

while (reader.Read())
{
tmpRoleNames += reader.GetString(0) + ",";
}
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "GetAllRoles");
}
else
{
throw e;
}
}
finally
{
if (reader != null) { reader.Close(); }
conn.Close();
}

if (tmpRoleNames.Length > 0)
{
// Remove trailing comma.
tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
return tmpRoleNames.Split(',');
}

return new string[0];
}


//
// RoleProvider.GetRolesForUser
//

public override string[] GetRolesForUser(string username)
{
string tmpRoleNames = "";

OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("SELECT Rolename FROM UsersInRoles " +
" WHERE Username = ? AND ApplicationName = ?", conn);

cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

OdbcDataReader reader = null;

try
{
conn.Open();

reader = cmd.ExecuteReader();

while (reader.Read())
{
tmpRoleNames += reader.GetString(0) + ",";
}
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "GetRolesForUser");
}
else
{
throw e;
}
}
finally
{
if (reader != null) { reader.Close(); }
conn.Close();
}

if (tmpRoleNames.Length > 0)
{
// Remove trailing comma.
tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
return tmpRoleNames.Split(',');
}

return new string[0];
}


//
// RoleProvider.GetUsersInRole
//

public override string[] GetUsersInRole(string rolename)
{
string tmpUserNames = "";

OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("SELECT Username FROM UsersInRoles " +
" WHERE Rolename = ? AND ApplicationName = ?", conn);

cmd.Parameters.Add("@Rolename", OdbcType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

OdbcDataReader reader = null;

try
{
conn.Open();

reader = cmd.ExecuteReader();

while (reader.Read())
{
tmpUserNames += reader.GetString(0) + ",";
}
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "GetUsersInRole");
}
else
{
throw e;
}
}
finally
{
if (reader != null) { reader.Close(); }
conn.Close();
}

if (tmpUserNames.Length > 0)
{
// Remove trailing comma.
tmpUserNames = tmpUserNames.Substring(0, tmpUserNames.Length - 1);
return tmpUserNames.Split(',');
}

return new string[0];
}


//
// RoleProvider.IsUserInRole
//

public override bool IsUserInRole(string username, string rolename)
{
bool userIsInRole = false;

OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("SELECT COUNT(*) FROM UsersInRoles " +
" WHERE Username = ? AND Rolename = ? AND ApplicationName = ?", conn);

cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
cmd.Parameters.Add("@Rolename", OdbcType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

try
{
conn.Open();

int numRecs = (int)cmd.ExecuteScalar();

if (numRecs > 0)
{
userIsInRole = true;
}
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "IsUserInRole");
}
else
{
throw e;
}
}
finally
{
conn.Close();
}

return userIsInRole;
}


//
// RoleProvider.RemoveUsersFromRoles
//

public override void RemoveUsersFromRoles(string[] usernames, string[] rolenames)
{
foreach (string rolename in rolenames)
{
if (!RoleExists(rolename))
{
throw new ProviderException("Role name not found.");
}
}

foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
if (!IsUserInRole(username, rolename))
{
throw new ProviderException("User is not in role.");
}
}
}


OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("DELETE FROM UsersInRoles " +
" WHERE Username = ? AND Rolename = ? AND ApplicationName = ?", conn);

OdbcParameter userParm = cmd.Parameters.Add("@Username", OdbcType.VarChar, 255);
OdbcParameter roleParm = cmd.Parameters.Add("@Rolename", OdbcType.VarChar, 255);
cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

OdbcTransaction tran = null;

try
{
conn.Open();
tran = conn.BeginTransaction();
cmd.Transaction = tran;

foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
userParm.Value = username;
roleParm.Value = rolename;
cmd.ExecuteNonQuery();
}
}

tran.Commit();
}
catch (OdbcException e)
{
try
{
tran.Rollback();
}
catch { }


if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "RemoveUsersFromRoles");
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
}


//
// RoleProvider.RoleExists
//

public override bool RoleExists(string rolename)
{
bool exists = false;

OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("SELECT COUNT(*) FROM Roles " +
" WHERE Rolename = ? AND ApplicationName = ?", conn);

cmd.Parameters.Add("@Rolename", OdbcType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

try
{
conn.Open();

int numRecs = (int)cmd.ExecuteScalar();

if (numRecs > 0)
{
exists = true;
}
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "RoleExists");
}
else
{
throw e;
}
}
finally
{
conn.Close();
}

return exists;
}

//
// RoleProvider.FindUsersInRole
//

public override string[] FindUsersInRole(string rolename, string usernameToMatch)
{
OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("SELECT Username FROM UsersInRoles " +
"WHERE Username LIKE ? AND RoleName = ? AND ApplicationName = ?", conn);
cmd.Parameters.Add("@UsernameSearch", OdbcType.VarChar, 255).Value = usernameToMatch;
cmd.Parameters.Add("@RoleName", OdbcType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

string tmpUserNames = "";
OdbcDataReader reader = null;

try
{
conn.Open();

reader = cmd.ExecuteReader();

while (reader.Read())
{
tmpUserNames += reader.GetString(0) + ",";
}
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "FindUsersInRole");
}
else
{
throw e;
}
}
finally
{
if (reader != null) { reader.Close(); }

conn.Close();
}

if (tmpUserNames.Length > 0)
{
// Remove trailing comma.
tmpUserNames = tmpUserNames.Substring(0, tmpUserNames.Length - 1);
return tmpUserNames.Split(',');
}

return new string[0];
}

//
// WriteToEventLog
// A helper function that writes exception detail to the event log. Exceptions
// are written to the event log as a security measure to avoid private database
// details from being returned to the browser. If a method does not return a status
// or boolean indicating the action succeeded or failed, a generic exception is also
// thrown by the caller.
//

private void WriteToEventLog(OdbcException e, string action)
{
EventLog log = new EventLog();
log.Source = eventSource;
log.Log = eventLog;

string message = exceptionMessage + "\n\n";
message += "Action: " + action + "\n\n";
message += "Exception: " + e.ToString();

log.WriteEntry(message);
}

}
}

分享到:
评论

相关推荐

    Custom Membership and Role provider(MVC 3)

    4. **自定义会员和角色提供者的实现**:创建自定义会员和角色提供者需要继承ASP.NET的抽象基类,如`MembershipProvider`和`RoleProvider`,并实现其中的虚方法。这包括`ValidateUser`(验证用户)、`CreateUser`...

    OracleRoleProvider

    在ASP.NET中,RoleProvider是一个抽象类,用于提供对用户角色的管理。通过继承这个类并实现其接口方法,我们可以创建自定义的角色提供者,以适应不同的数据库系统,如Oracle。OracleRoleProvider就是这样的一个实现...

    .net基类BasePage

    这可以通过集成如`RoleProvider`或`Authorization`特性来实现,确保用户只能访问他们被授权的功能。 3. **HTML清理与安全**: 为了防止XSS(跨站脚本)攻击,`BasePage`类可能会包含一个方法来清除用户输入的HTML...

    基于c#的角色管理代码

    在IT行业中,尤其是在开发企业级应用时,角色管理和权限控制是一个至关重要的部分。"基于C#的角色管理代码"提供了一种方法,通过编程实现对不同用户角色的管理和权限分配,确保系统安全性和数据访问的合规性。以下是...

    ASP.NET源码——[CMS程序]Shangducms NT v2.0 beta 1.zip

    5. **搜索引擎优化(SEO)**:Shangducms NT 内置 SEO 功能,如元标签设置、URL 重写等,帮助提升网站在搜索引擎中的排名。 6. **插件机制**:允许第三方开发者开发并集成自己的插件,丰富系统功能。 **深入源码...

    (还有)Windows角色提供程序-用于企业环境

    描述提到"为AD和本地计算机实现自定义RoleProvider,以与Forms Authentication一起使用",这暗示了我们将探讨如何将Windows角色提供程序与Active Directory(AD)集成,并创建适应企业特定需求的自定义角色提供程序...

    MVC4实现角色权限验证的例子

    在本文中,我们将深入探讨如何在ASP.NET MVC4框架中实现角色权限验证,这是一个非常重要的概念,对于构建安全、有管理的Web应用程序至关重要。MVC4是Microsoft开发的一个用于构建动态网站的开源Web应用程序框架,它...

    一个很简单的权限做法

    而`RoleProvider`则是一个接口,允许我们自定义如何存储和检索用户角色信息,例如可以是数据库、XML文件或Windows Active Directory。 描述中提到的"小练习"可能涉及到以下步骤: 1. **配置身份验证**:在`Web....

    Mysql Profile

    `RoleProvider` 类似地扩展了 .NET 的 `System.Web.Security.RoleProvider`,并为 MySQL 数据库提供角色相关的操作,如添加、删除用户角色,检查用户是否属于某个角色等。 5. **性能优化**:为了提高性能,`...

    asp.net常用函数

    3. **Server对象**:Server对象提供了一系列服务器端操作的实用方法,如MapPath()可以获取相对于应用程序根目录的物理路径,Transfer()和Execute()可以在不生成新的HTTP响应的情况下转到另一个页面。 4. **Session...

    新闻发布系统

    例如,使用Forms身份验证控制用户登录,角色管理则可以通过RoleProvider实现权限控制。 开发过程中,数据库设计是关键,可能包括新闻表(含新闻ID、标题、内容、发布时间、作者、分类ID等字段)、分类表(含分类ID...

    ASP,NET源码——[新闻文章]DRLerNews新闻系统.zip

    DRLerNews可能实现了SEO(搜索引擎优化)策略,如元标签的设置、URL重写和友好的网页结构,以便提高搜索引擎的抓取和排名。 通过对DRLerNews新闻系统的源码分析,我们可以深入了解ASP.NET的开发实践,提升自己的...

    高质量C#源码.rar

    了解如何使用`BinaryFormatter`、`XmlSerializer`或`DataContractSerializer`对于数据交换至关重要。 3. 线程并发:多线程编程是C#的一个重要特性,用于实现并行处理和提高应用程序性能。`System.Threading`命名...

    asp.net权限管理框架

    在企业级应用开发中,权限管理是至关重要的,它确保了不同用户群体对系统资源的访问权限得以有效控制,从而提高了系统的安全性与效率。 1. 用户管理:用户管理是权限系统的基础,涉及到用户的创建、删除、修改和...

    asp.net教学管理权限

    在这个“教学管理权限”项目中,我们聚焦于如何在ASP.NET环境中实现用户权限的管理和控制,这对于任何涉及用户交互的在线教育平台至关重要。 一、权限管理基础 权限管理是系统安全的重要组成部分,它允许管理员...

    IIS工作原理-通俗易懂

    总之,了解IIS的工作原理对于任何在Windows环境下开发和维护Web应用程序的开发者都至关重要。它不仅帮助我们理解请求的处理流程,还能让我们更好地应对性能瓶颈和安全挑战,从而提高Web应用程序的质量和用户体验。

    RBAC权限管理系统,是一个开源的

    在.NET中实现RBAC,可以利用.NET Framework的安全特性,如Principal和Identity对象来处理用户认证,RoleProvider和AuthorizationManager类进行角色管理和授权。同时,可以结合Entity Framework或其它ORM工具,将RBAC...

    从Membership 到 .NET4.5 之 ASP1

    它和 MembershipProvider, RoleProvider 一起组成了用户信息、权限管理这样一套完整的框架。 ProfileProvider 可以让我们扩展用户信息,例如,我们可以添加一个 Model 继承 ProfileBase 来为我们新的用户对象建模...

Global site tag (gtag.js) - Google Analytics