自定义一个叫 ReadOnlyXmlMembershipProvider 的 MembershipProvider,用 XML 作为用户储藏室
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 作为用户储藏室的更多相关文章
- Spring自定义一个拦截器类SomeInterceptor,实现HandlerInterceptor接口及其方法的实例
利用Spring的拦截器可以在处理器Controller方法执行前和后增加逻辑代码,了解拦截器中preHandle.postHandle和afterCompletion方法执行时机. 自定义一个拦截器 ...
- JSTL,自定义一个标签的功能案例
1.自定义一个带有两个属性的标签<max>,用于计算并输出两个数的最大值: 2.自定义一个带有一个属性的标签<lxn:readFile src=“”>,用于输出指定文件的内容 ...
- 自定义View(7)官方教程:自定义View(含onMeasure),自定义一个Layout(混合组件),重写一个现有组件
Custom Components In this document The Basic Approach Fully Customized Components Compound Controls ...
- 自定义一个EL函数
自定义一个EL函数 一般就是一下几个步骤,顺便提供一个工作常用的 案例: 1.编写一个java类,并编写一个静态方法(必需是静态方法),如下所示: public class DateTag { pri ...
- 自定义一个可以被序列化的泛型Dictionary<TKey,TValue>集合
Dictionary是一个键值类型的集合.它有点像数组,但Dictionary的键可以是任何类型,内部使用Hash Table存储键和值.本篇自定义一个类型安全的泛型Dictionary<TKe ...
- SpringMVC 自定义一个拦截器
自定义一个拦截器方法,实现HandlerInterceptor方法 public class FirstInterceptor implements HandlerInterceptor{ /** * ...
- jQuery Validate 表单验证插件----自定义一个验证方法
一.下载依赖包 网盘下载:https://yunpan.cn/cryvgGGAQ3DSW 访问密码 f224 二.引入依赖包 <script src="../../scripts/j ...
- Volley HTTP库系列教程(5)自定义一个Volley请求
Implementing a Custom Request Previous Next This lesson teaches you to Write a Custom Request parse ...
- 在String()构造器不存在的情况下自定义一个MyString()函数,实现如下内建String()方法和属性:
在String()构造器不存在的情况下自定义一个MyString()函数,实现如下内建String()方法和属性: var s = new MyString("hello"); s ...
随机推荐
- Leetcode 13 Roman to Integer 字符串处理+STL
题意:将罗马数字1到3999转化成自然数字,这里用了STL库map将罗马字符映射到自然数字. I,V,X,L,C,D,M -> 1,5,10,50,100,500,1000 m[s[i]]< ...
- J2EE学习笔记-第二章(Web应用初步)
首先要理解一些概念的词语,到底这些是什么(当我读懂了后,会逐一填补完整,现在我真的有点混淆) web组件-相当于功能性的组件,就像是零件,汽车的轮胎,汽车的门,所有组件组合后,才能成为一辆车,有时候也 ...
- js模块方案
在浏览器环境中,模块的各个部分通常都是从网上获取的,有时无法知道js哪个模块会先加载,所以传入的返回函数除了返回函数本身,还可以返回为空对象. 自执行函数的处理方式: var module1 = (f ...
- gulp学习笔记1
gulp系列学习笔记: 1.gulp学习笔记1 2.gulp学习笔记2 3.gulp学习笔记3 4.gulp学习笔记4 1.安装gulp 首先我们需要node环境,nodejs安装这里就不说了,不懂的 ...
- windows远程连接Linux(Ubuntu)的方法
需要做的工作: 1.在Linux(Ubuntu)端安装.设置好SSH 2.下载putty,并通过putty的SSH连接登录Linux 一 .如何在Linux(Ubuntu)端安装.设置好SSH,获取I ...
- Python LDAP中的时间戳转换为Linux下时间
(Get-ADUser zhangsan -Properties badpasswordtime).badpasswordtime返回值为:131172610187388712131172610187 ...
- WIN7、WIN8 右键在目录当前打开命令行Cmd窗口(图文)
Win7系统大家习惯“Win+R”的组合键打开命令提示符. 通常右击文件夹是没有进入命令行 进入某个文件夹里面,先按住Shift键,然后鼠标右键,出现选项“在此处打开命令窗口(W)”也可以打开命令行. ...
- nginx+tomcat+java部署总结
昨天部署了一下nginx+tomcat+java出现了很多问题,以下为整理总结. 使用了两种部署方式,一种是源码部署,一种是war部署. java源码部署总结: 环境:nginx+tomcat 部署方 ...
- Scala 深入浅出实战经典 第49课 Scala中Variance代码实战(协变)
王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-64讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...
- windbg-bp、 bm、 bu、 bl、 bc、 ba(断点、硬件断点)
bp bp 命令是在某个地址下断点, 可以 bp 0x7783FEB 也可以 bp MyApp!SomeFunction . 对于后者,WinDBG 会自动找到MyApp!SomeFunction 对 ...