asp.net – 哪个会员提供程序实现存储在web.config中的用户?

前端之家收集整理的这篇文章主要介绍了asp.net – 哪个会员提供程序实现存储在web.config中的用户?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有一个代码盲的时刻.

ASP.NET 4.0.

Web.config文件

<?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.

所以我的问题是,我应该使用什么成员资格提供者让ASP.NET使用< credentials>中的用户名和密码. web.config的元素?

解决方法

我很惊讶,考虑到框架设计师如何处理定义“凭证/>”的麻烦.元素,他们没有实现任何代码来消费它.

我发现这个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;
    }
}
原文链接:https://www.f2er.com/aspnet/246749.html

猜你在找的asp.Net相关文章