有一个代码盲时刻。
ASP.NET 4.0。
网络配置:
<?xml version="1.0"?>
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="DataViewer" loginUrl="login.aspx">
<credentials passwordFormat="Clear">
<user name="devuser" password="test" />
</credentials>
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
和一个登录控件:
<asp:Login ID="login" runat="server" />
如果我输入用户名和密码,然后单击登录,它会挂起。
如果我中断,我可以在调用堆栈中看到
login.AuthenticateUsingMembershipProvider()
正在通话中 SqlMembershipProvider.ValidateUser()
.这个项目根本没有定义或涉及数据库,我也没有指定应该使用 SqlMembershipProvider。所以我的问题是,我应该使用哪个成员(member)提供程序来让 ASP.NET 使用
<credentials>
中的用户名和密码web.config
的元素?
最佳答案
我很惊讶考虑到框架设计者是如何麻烦地定义 <credentials />
他们没有实现任何代码来使用它的元素。
我找到了这个 here 的一种工作实现我已经修复并包含在下面。 MembershipProvider
的所有其他成员扔NotImplementedException
.
using System.Configuration;
using System.Web.Configuration;
using System.Web.Security;
public class WebConfigMembershipProvider : MembershipProvider
{
private FormsAuthenticationUserCollection _users = null;
private FormsAuthPasswordFormat _passwordFormat;
public override void Initialize(string name,
System.Collections.Specialized.NameValueCollection config)
{
base.Initialize(name, config);
_passwordFormat = getPasswordFormat();
}
public override bool ValidateUser(string username, string password)
{
var user = getUsers()[username];
if (user == null) return false;
if (_passwordFormat == FormsAuthPasswordFormat.Clear)
{
if (user.Password == password)
{
return true;
}
}
else
{
if (user.Password == FormsAuthentication.HashPasswordForStoringInConfigFile(password,
_passwordFormat.ToString()))
{
return true;
}
}
return false;
}
protected FormsAuthenticationUserCollection getUsers()
{
if (_users == null)
{
AuthenticationSection section = getAuthenticationSection();
FormsAuthenticationCredentials creds = section.Forms.Credentials;
_users = section.Forms.Credentials.Users;
}
return _users;
}
protected AuthenticationSection getAuthenticationSection()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
return (AuthenticationSection)config.GetSection("system.web/authentication");
}
protected FormsAuthPasswordFormat getPasswordFormat()
{
return getAuthenticationSection().Forms.Credentials.PasswordFormat;
}
}
关于asp.net - 哪个 Membership Provider 实现了存储在 web.config 中的用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12425890/