如何设置 web.config 并使用 ASP.NET ResetPassword() 方法

发布于 2024-12-02 05:13:40 字数 5563 浏览 1 评论 0 原文

我正在使用 asp.net 表单身份验证,并且我需要能够重置用户的密码。

这是代码:

protected void resetPassword(string username)
{
    MembershipUser user = Membership.GetUser(username);
    if (user != null)
    {
        string newPassword = user.ResetPassword();
        Membership.UpdateUser(user);
        MailMessage message = new MailMessage("", user.Email, "change password", "your Password changed to: " + newPassword);
        userManager.sendMail(message);
    }
}

这是我的 web.config 文件:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
  </appSettings>
  <system.webServer>
    <handlers>
      <remove name="ChartImageHandler" />
      <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST"
       path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </handlers>
  </system.webServer>
  <connectionStrings>
    <add name="CRM_DBConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\CRM\CRM\DAL_new\CRM_DB.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
    <add name="CRM_DBConnectionString2" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\CRM\DAL_new\CRM_DB.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <httpHandlers>
      <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
       validate="false" />
    </httpHandlers>
    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting"
         assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </controls>
    </pages>
    <roleManager enabled="true"/>
    <authentication mode="Forms">
      <forms loginUrl="./login_page/Default.aspx" name=".ASPXFORMSAUTH" protection="All" timeout="43200" requireSSL="false" slidingExpiration="true" cookieless="UseCookies" enableCrossAppRedirects="false" />
    </authentication>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>
  </system.web>
  <system.net>
    <mailSettings>
      <smtp from="[email protected]">
        <network host="smtp.gmail.com" password="########" port="587" userName="######@gmail.com"/>
      </smtp>
    </mailSettings>
  </system.net>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IBlServer" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
            <message clientCredentialType="UserName" algorithmSuite="Default"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:51109/Service1.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IBlServer" contract="CrmServiceReference.IBlServer" name="BasicHttpBinding_IBlServer"/>
    </client>
  </system.serviceModel>
</configuration>

行: string newPassword = user.ResetPassword(); 抛出异常:

System.ArgumentNullException was unhandled by user code
  Message=Value cannot be null.
Parameter name: passwordAnswer

我在这里和其他地方遇到了很多类似的问题网站,但我似乎无法正确理解。它要么以有关必须获取参数的 ResetPassword() 的错误结束,要么弄乱页面上检索用户帐户以进行其他操作的其他代码。

解决方案这里搞乱了其他MembershipUser user = Membership.GetUser(username) ; 我的代码中的行。

那么如果我想要以下内容,我应该在哪里以及如何配置我的 web.config:
1. 用户可以使用安全问答为自己重置密码(这已经有效)
2. 管理员可以为用户重置密码。用户将收到一封包含新密码的电子邮件。

预先感谢,
夏季灯泡

I'm using the asp.net forms authentication and i need to be able to reset the password for a user.

This is the code:

protected void resetPassword(string username)
{
    MembershipUser user = Membership.GetUser(username);
    if (user != null)
    {
        string newPassword = user.ResetPassword();
        Membership.UpdateUser(user);
        MailMessage message = new MailMessage("", user.Email, "change password", "your Password changed to: " + newPassword);
        userManager.sendMail(message);
    }
}

And here is my web.config file:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
  </appSettings>
  <system.webServer>
    <handlers>
      <remove name="ChartImageHandler" />
      <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST"
       path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </handlers>
  </system.webServer>
  <connectionStrings>
    <add name="CRM_DBConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\CRM\CRM\DAL_new\CRM_DB.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
    <add name="CRM_DBConnectionString2" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\CRM\DAL_new\CRM_DB.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <httpHandlers>
      <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
       validate="false" />
    </httpHandlers>
    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting"
         assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </controls>
    </pages>
    <roleManager enabled="true"/>
    <authentication mode="Forms">
      <forms loginUrl="./login_page/Default.aspx" name=".ASPXFORMSAUTH" protection="All" timeout="43200" requireSSL="false" slidingExpiration="true" cookieless="UseCookies" enableCrossAppRedirects="false" />
    </authentication>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>
  </system.web>
  <system.net>
    <mailSettings>
      <smtp from="[email protected]">
        <network host="smtp.gmail.com" password="########" port="587" userName="######@gmail.com"/>
      </smtp>
    </mailSettings>
  </system.net>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IBlServer" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
            <message clientCredentialType="UserName" algorithmSuite="Default"/>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:51109/Service1.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IBlServer" contract="CrmServiceReference.IBlServer" name="BasicHttpBinding_IBlServer"/>
    </client>
  </system.serviceModel>
</configuration>

The line: string newPassword = user.ResetPassword(); throws the exception:

System.ArgumentNullException was unhandled by user code
  Message=Value cannot be null.
Parameter name: passwordAnswer

I've been through lots of similar question here and on other sites, but i can't seem to get it right. It either ends up with an error about ResetPassword() that has to get a parameter, or mucks up other code on the page that retrieves user account for other manipulation.

The solution here mucks up other MembershipUser user = Membership.GetUser(username); lines in my code.

So where and how to i configure my web.config if i want the following:
1. A user can reset his password for himself using the security Q&A (this already works)
2. An admin can reset the password for a user. The user will get an E-Mail with the new password.

Thanks in advance,
Summerbulb

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

(り薆情海 2024-12-09 05:13:40

您是否提供自定义会员资格设置?我在配置中没有看到它们。我也遇到了同样的问题,最终放弃了密码问题/答案。您是否对密码和密码答案进行哈希处理?如果使用散列选项,则在不知道正确答案的情况下这将不起作用。如果您正在执行加密路由,那么您可以反射性地调用 SqlMembershipProvider 类中的 Decrypt 方法来解密数据,这有点痛苦但有效。

同样,您还有其他一些选择。关闭密码问题/答案,但可以自行自定义实现。成员资格框架不适用于系统管理功能。其次,以明文形式手动存储答案(本质上是复制它)或使用您的算法加密,然后解密。

密码问题和答案都是由配置驱动的,所以最后,您还可以考虑创建两个会员提供程序,第二个提供者要求问题和答案为 false:

<add name="AdminProvider" type="<point to SQL membership" requiresQuestionAndAnswer="false" />

在您的管理屏幕中,执行:

Membership.Providers[1].ResetPassword();

然后它就可以工作了,因为它的配置状态没有问题和需要答案。

如果您需要更多信息,请告诉我。

Do you have custom membership settings provided? I don't see them in the config. I had the same issue too, and ended up dropping the password question/answer. Are you hashing passwords and password answers? If using the hash option, this won't work without knowing the correct answer. If you are doing the encrypted route, then you could reflectively call the Decrypt methods in the SqlMembershipProvider class to decrypt the data, which is a little pain but works.

Similarly, you have a few other options. Turn off the password question/answer, but custom implement this yourself. Membership framework was not meant for sys admin features. Secondly, store the answer manually (essentially duplicate it) in clear text or encrypted using your algorithm, and decrypt it.

The password question and answer is all driven from config, so lastly, you could also consider making two membership providers, the second one with requiresquestionandanswer to false:

<add name="AdminProvider" type="<point to SQL membership" requiresQuestionAndAnswer="false" />

In your admin screen, do:

Membership.Providers[1].ResetPassword();

And then it work work because it's configuration states no question and answer is needed.

Let me know if you need more info.

忱杏 2024-12-09 05:13:40

第 2 部分所需的内容(管理员可以重置用户的密码。用户将收到一封包含新密码的电子邮件。)您可以在此处查看

http://www.ezineasp.net/post/ASP-Net-2-0-Password-Recovery-Control-With-Email.aspx

对我来说它有效。如果用户忘记了密码,他会收到包含新密码的电子邮件。只需将enablePasswordReset 设置为true。

What you need for part 2 (An admin can reset the password for a user. The user will get an E-Mail with the new password.) you can see here

http://www.ezineasp.net/post/ASP-Net-2-0-Password-Recovery-Control-With-Email.aspx

For me it works. If user forgot his password, he gets e-mail with new password.Only You need to set enablePasswordReset to true.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文