1. 配置 web.config

<membership defaultProvider="AspNetReadOnlyXmlMembershipProvider">
<providers>
<clear />
<add name="AspNetReadOnlyXmlMembershipProvider" type="OpenIdWebRingSsoProvider.Code.ReadOnlyXmlMembershipProvider" description="Read-only XML membership provider" xmlFileName="~/App_Data/Users.xml" />
</providers>
</membership>

2.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Security.Permissions;
using System.Web;
using System.Web.Hosting;
using System.Web.Security;
using System.Xml; public class ReadOnlyXmlMembershipProvider : MembershipProvider {
private Dictionary<string, MembershipUser> users;
private string xmlFileName; // MembershipProvider Properties
public override string ApplicationName {
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
} public override bool EnablePasswordRetrieval {
get { return false; }
} public override bool EnablePasswordReset {
get { return false; }
} public override int MaxInvalidPasswordAttempts {
get { throw new NotSupportedException(); }
} public override int MinRequiredNonAlphanumericCharacters {
get { throw new NotSupportedException(); }
} public override int MinRequiredPasswordLength {
get { throw new NotSupportedException(); }
} public override int PasswordAttemptWindow {
get { throw new NotSupportedException(); }
} public override MembershipPasswordFormat PasswordFormat {
get { throw new NotSupportedException(); }
} public override string PasswordStrengthRegularExpression {
get { throw new NotSupportedException(); }
} public override bool RequiresQuestionAndAnswer {
get { throw new NotSupportedException(); }
} public override bool RequiresUniqueEmail {
get { throw new NotSupportedException(); }
} // MembershipProvider Methods
public override void Initialize(string name, NameValueCollection config) {
// Verify that config isn't null
if (config == null) {
throw new ArgumentNullException("config");
} // Assign the provider a default name if it doesn't have one
if (string.IsNullOrEmpty(name)) {
name = "ReadOnlyXmlMembershipProvider";
} // Add a default "description" attribute to config if the
// attribute doesn't exist or is empty
if (string.IsNullOrEmpty(config["description"])) {
config.Remove("description");
config.Add("description", "Read-only XML membership provider");
} // Call the base class's Initialize method
base.Initialize(name, config); // Initialize _XmlFileName and make sure the path
// is app-relative
string path = config["xmlFileName"]; if (string.IsNullOrEmpty(path)) {
path = "~/App_Data/Users.xml";
} if (!VirtualPathUtility.IsAppRelative(path)) {
throw new ArgumentException("xmlFileName must be app-relative");
} string fullyQualifiedPath = VirtualPathUtility.Combine(
VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath),
path); this.xmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath);
config.Remove("xmlFileName"); // Make sure we have permission to read the XML data source and
// throw an exception if we don't
FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, this.xmlFileName);
permission.Demand(); // Throw an exception if unrecognized attributes remain
if (config.Count > ) {
string attr = config.GetKey();
if (!string.IsNullOrEmpty(attr)) {
throw new ProviderException("Unrecognized attribute: " + attr);
}
}
} public override bool ValidateUser(string username, string password) {
// Validate input parameters
if (string.IsNullOrEmpty(username) ||
string.IsNullOrEmpty(password)) {
return false;
} try {
// Make sure the data source has been loaded
this.ReadMembershipDataStore(); // Validate the user name and password
MembershipUser user;
if (this.users.TryGetValue(username, out user)) {
if (user.Comment == password) { // Case-sensitive
// NOTE: A read/write membership provider
// would update the user's LastLoginDate here.
// A fully featured provider would also fire
// an AuditMembershipAuthenticationSuccess
// Web event
return true;
}
} // NOTE: A fully featured membership provider would
// fire an AuditMembershipAuthenticationFailure
// Web event here
return false;
} catch (Exception) {
return false;
}
} public override MembershipUser GetUser(string username, bool userIsOnline) {
// Note: This implementation ignores userIsOnline // Validate input parameters
if (string.IsNullOrEmpty(username)) {
return null;
} // Make sure the data source has been loaded
this.ReadMembershipDataStore(); // Retrieve the user from the data source
MembershipUser user;
if (this.users.TryGetValue(username, out user)) {
return user;
} return null;
} public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) {
// Note: This implementation ignores pageIndex and pageSize,
// and it doesn't sort the MembershipUser objects returned // Make sure the data source has been loaded
this.ReadMembershipDataStore(); MembershipUserCollection users = new MembershipUserCollection(); foreach (KeyValuePair<string, MembershipUser> pair in this.users) {
users.Add(pair.Value);
} totalRecords = users.Count;
return users;
} public override int GetNumberOfUsersOnline() {
throw new NotSupportedException();
} public override bool ChangePassword(string username, string oldPassword, string newPassword) {
throw new NotSupportedException();
} public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) {
throw new NotSupportedException();
} public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) {
throw new NotSupportedException();
} public override bool DeleteUser(string username, bool deleteAllRelatedData) {
throw new NotSupportedException();
} public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) {
throw new NotSupportedException();
} public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) {
throw new NotSupportedException();
} public override string GetPassword(string username, string answer) {
throw new NotSupportedException();
} public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) {
throw new NotSupportedException();
} public override string GetUserNameByEmail(string email) {
throw new NotSupportedException();
} public override string ResetPassword(string username, string answer) {
throw new NotSupportedException();
} public override bool UnlockUser(string userName) {
throw new NotSupportedException();
} public override void UpdateUser(MembershipUser user) {
throw new NotSupportedException();
} // Helper method
private void ReadMembershipDataStore() {
lock (this) {
if (this.users == null) {
this.users = new Dictionary<string, MembershipUser>(, StringComparer.InvariantCultureIgnoreCase);
XmlDocument doc = new XmlDocument();
doc.Load(this.xmlFileName);
XmlNodeList nodes = doc.GetElementsByTagName("User"); foreach (XmlNode node in nodes) {
MembershipUser user = new MembershipUser(
Name, // Provider name
node["UserName"].InnerText, // Username
null, // providerUserKey
null, // Email
string.Empty, // passwordQuestion
node["Password"].InnerText, // Comment
true, // isApproved
false, // isLockedOut
DateTime.Now, // creationDate
DateTime.Now, // lastLoginDate
DateTime.Now, // lastActivityDate
DateTime.Now, // lastPasswordChangedDate
new DateTime(, , )); // lastLockoutDate this.users.Add(user.UserName, user);
}
}
}
}
}

3.

谢谢浏览!

自定义一个叫 ReadOnlyXmlMembershipProvider 的 MembershipProvider,用 XML 作为用户储藏室的更多相关文章

  1. Spring自定义一个拦截器类SomeInterceptor,实现HandlerInterceptor接口及其方法的实例

    利用Spring的拦截器可以在处理器Controller方法执行前和后增加逻辑代码,了解拦截器中preHandle.postHandle和afterCompletion方法执行时机. 自定义一个拦截器 ...

  2. JSTL,自定义一个标签的功能案例

    1.自定义一个带有两个属性的标签<max>,用于计算并输出两个数的最大值: 2.自定义一个带有一个属性的标签<lxn:readFile  src=“”>,用于输出指定文件的内容 ...

  3. 自定义View(7)官方教程:自定义View(含onMeasure),自定义一个Layout(混合组件),重写一个现有组件

    Custom Components In this document The Basic Approach Fully Customized Components Compound Controls ...

  4. 自定义一个EL函数

    自定义一个EL函数 一般就是一下几个步骤,顺便提供一个工作常用的 案例: 1.编写一个java类,并编写一个静态方法(必需是静态方法),如下所示: public class DateTag { pri ...

  5. 自定义一个可以被序列化的泛型Dictionary<TKey,TValue>集合

    Dictionary是一个键值类型的集合.它有点像数组,但Dictionary的键可以是任何类型,内部使用Hash Table存储键和值.本篇自定义一个类型安全的泛型Dictionary<TKe ...

  6. SpringMVC 自定义一个拦截器

    自定义一个拦截器方法,实现HandlerInterceptor方法 public class FirstInterceptor implements HandlerInterceptor{ /** * ...

  7. jQuery Validate 表单验证插件----自定义一个验证方法

    一.下载依赖包 网盘下载:https://yunpan.cn/cryvgGGAQ3DSW  访问密码 f224 二.引入依赖包 <script src="../../scripts/j ...

  8. Volley HTTP库系列教程(5)自定义一个Volley请求

    Implementing a Custom Request Previous  Next This lesson teaches you to Write a Custom Request parse ...

  9. 在String()构造器不存在的情况下自定义一个MyString()函数,实现如下内建String()方法和属性:

    在String()构造器不存在的情况下自定义一个MyString()函数,实现如下内建String()方法和属性: var s = new MyString("hello"); s ...

随机推荐

  1. paip.提升安全性----Des加密 java php python的实现总结

    paip.提升安全性----Des加密 java php python的实现总结 ///////////    uapi         private static String decryptBy ...

  2. Sql Server 调用DLL

    背景 在处理数据或者分析数据时,我们常常需要加入一定的逻辑,该些处理逻辑有些sql是可以支持,有些逻辑SQL则无能为力,在这种情况下,大多数人都会编写相关的程序来处理成自己想要的数据,但每次处理相同逻 ...

  3. Liferay7 BPM门户开发之27: MVC Portlet插件工程开发

    官网上的教材说实话实在精简不清晰. https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/creating-an-mvc-por ...

  4. 将数据导出到Excel2007格式。

    增加数据格式 public static void TableToExcel2(DataTable table, string filename, string sheetname) { XSSFWo ...

  5. Reservoir Sampling 蓄水池抽样算法,经典抽样

    随机读取数据,如何保证真随机是不可能的,因为计算机的随机函数是伪随机的. 但是在不考虑计算机随机函数的情况下,如何保证数据的随机采样呢? 1.系统提供的shuffle函数 C++/Java都提供有sh ...

  6. 【Android】wifi开发

    WIFI就是一种无线联网技术,常见的是使用无线路由器.那么在这个无线路由器的信号覆盖的范围内都可以采用WIFI连接的方式进行联网.如果无线路由器连接了一个ADSL线路或其他的联网线路,则又被称为“热点 ...

  7. Windows7下面exe寄宿WCF:Http无法注册URL{0} ,进程不具有此命名空间的访问权限问题

    运行寄宿exe程序的时候通过run as administrator来启动就OK了.

  8. nginx内置全局变量及含义

    名称        版本        说明(变量列表来源于文件 ngx_http_variables ) $args        1.0.8        请求中的参数; $binary_remo ...

  9. linux下redis设置密码登录

    redis设置密码访问 你的redis在真是环境中不可以谁想访问就可以访问,所以必须要设置密码 设置密码的流程如下: vim  /etc/redis.conf #requirepass foobare ...

  10. linux crontab 文件位置和日志位置

    一.文件位置 位置一般在/var/spool/cron/下,如果你是root用户,那下面有个root文件,建议日常备份,避免误删除导致crontab 文件丢失: 二.日志文件位置 默认情况下,cron ...