c# – WebMatrix.WebData.WebSecurity – 如何只通过PasswordResetToken获取UserName

前端之家收集整理的这篇文章主要介绍了c# – WebMatrix.WebData.WebSecurity – 如何只通过PasswordResetToken获取UserName前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我只是想请求帮助以使我的方案工作?我想使用PasswordResetToken获取UserName.

这是我的情景.

>我的网站上有一个忘记密码功能,可以向用户发送密码重置电子邮件更改密码.
>我只想发送密码重置字符串.
>当用户单击链接时.我将只查询请求[“token”]以获取用户名,然后将允许用户更改密码和自动登录.

这是我的代码如下:

public ActionResult ChangePassword()
{
    ChangePasswordModel model = new ChangePasswordModel();
    string token=string.Empty;
    try
    {
        token = Request["token"].ToString();
        int userId = WebSecurity.GetUserIdFromPasswordResetToken(token);

        if (userId > 0)
        {
           //Get the user object by (userid) 
           //???????????????????
           //???????????????????
        }
        else
        {
            throw new Exception("The change password token has expired. Please go to login page and click forgot password again.");
        }
    }
    catch
    {
        model.HasError = true;
        ModelState.AddModelError("","The change password token has expired. Please go to login page and click forgot password again.");
    }

    return View(model);
}

先感谢您.

解决方法

看看本文末尾的评论WebSecurity.GeneratePasswordResetToken Method.

为方便起见,我会复制相关部分:

If users have forgotten their password,they can request a new one. To
provide a new password,do the following:

  1. Create a password-reset page that has a field where users can enter their email address.
  2. When a user has entered his or her email address in the password-reset page,verify that the email address represents a valid
    user. If it does,generate a password reset token by calling the
    GeneratePasswordResetToken(String,Int32) method.
  3. Create a hyperlink that points to a confirmation page in your site and that includes the token as a query-string parameter in the link’s
    URL.
  4. Send the link to a user in an email message. When the user receives the email message,he or she can click the link to invoke the
    confirmation page.
  5. Create a confirmation page that extracts the token from the URL parameter and that lets the user enter a new password.
  6. When the user submits the new password,call the ResetPassword(String,String) method and pass the password reset token
    and the new password.
    If the token is valid,the password will be
    reset. If the token is not valid (for example,it has expired),
    display an error message.

突出显示是我的.基本上你不需要用户名.该框架为您完成了所有繁重的工作.

解决你的评论,我不建议自动登录用户.这是一个很好的做法,他们手动记录检查这个密码更改的东西实际上是否有效,而不是发现它不仅仅是下一次.

无论如何,你可以这样做:

SimpleMembershipProvider provider = (SimpleMembershipProvider)Membership.Provider;
string username = provider.GetUserNameFromId(userId);

参考:GetUserNameFromId.

猜你在找的C#相关文章