erk*_*mir 28 .net c# asp.net-identity
我正在编写MVC 5并使用Identity 2.0.
现在我想重置密码.但我总是收到重置密码令牌的"无效令牌"错误.
public class AccountController : Controller
{
public UserManager<ApplicationUser> UserManager { get; private set; }
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
Run Code Online (Sandbox Code Playgroud)
我设置了DataProtectorTokenProvider,
public AccountController(UserManager<ApplicationUser> userManager)
{
//usermanager config
userManager.PasswordValidator = new PasswordValidator { RequiredLength = 5 };
userManager.EmailService = new IddaaWebSite.Controllers.MemberShip.MemberShipComponents.EmailService();
var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider();
userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<ApplicationUser>(provider.Create("UserToken"))
as IUserTokenProvider<ApplicationUser, string>;
UserManager = userManager;
}
Run Code Online (Sandbox Code Playgroud)
我在发送邮件之前生成密码重置
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ManagePassword(ManageUserViewModel model)
{
if (Request.Form["email"] != null)
{
var email = Request.Form["email"].ToString();
var user = UserManager.FindByEmail(email);
var token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
//mail send
}
}
Run Code Online (Sandbox Code Playgroud)
我点击邮件链接,我得到密码重置令牌和使用
var result = await UserManager.ResetPasswordAsync(model.UserId, model.PasswordToken, model.NewPassword);
Run Code Online (Sandbox Code Playgroud)
结果总是错误的,它说"无效令牌".我应该在哪里修理?
Mat*_*sek 36
UserManager.GeneratePasswordResetTokenAsync()经常返回包含"+"字符的字符串.如果按查询字符串传递参数,则这是原因('+'字符是URL中查询字符串中的空格).
尝试model.PasswordToken用'+'字符替换空格字符.
小智 20
[HttpPost]
[ValidateAntiForgeryToken]
publicasync Task<ActionResult> ManagePassword(ManageUserViewModel model)
{
if (Request.Form["email"] != null)
{
var email = Request.Form["email"].ToString();
var user = UserManager.FindByEmail(email);
var token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
//before send mail
token = HttpUtility.UrlEncode(token);
//mail send
}
}
Run Code Online (Sandbox Code Playgroud)
并在密码重置动作解码令牌 HttpUtility.UrlDecode(token);
sto*_*ree 13
我发现当数据库中的AspNetUsers表中的用户的SecurityStamp列为NULL时,也会出现"无效令牌"错误.使用开箱即用的MVC 5 Identity 2.0代码,SecurityStamp不会为NULL,但是在我们的代码中进行一些自定义的AccountController时会出现一个错误,该错误清除了SecurityStamp字段中的值.