Ben*_*iFB 34 c# asp.net-mvc asp.net-identity
最新的ASP.NET身份位(2.0 beta)包含确认用户电子邮件地址的基础.NuGet包"Microsoft Asp.Net Identity Samples"包含显示此流程的示例.但在该示例中,即使EmailConfirmed = false在用户体验中也没有不同的行为.
如何在用户尚未确认电子邮件地址时阻止用户登录?我知道我可以让用户登录,然后执行对该EmailConfirmed字段的检查,但是如果我可以阻止用户成功登录时效果会更好EmailConfirmed == false
Kev*_*ans 44
您需要在Login操作(POST方法)中添加几行以验证用户是否已确认其电子邮件.您要检查的方法是UserManager.IsEmailConfirmed.以下是您的登录操作的样子.
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
//Add this to check if the email was confirmed.
if (!await UserManager.IsEmailConfirmedAsync(user.Id))
{
ModelState.AddModelError("", "You need to confirm your email.");
return View(model);
}
if (await UserManager.IsLockedOutAsync(user.Id))
{
return View("Lockout");
}
if (await UserManager.CheckPasswordAsync(user, model.Password))
{
// Uncomment to enable lockout when password login fails
//await UserManager.ResetAccessFailedCountAsync(user.Id);
return await LoginCommon(user, model.RememberMe, returnUrl);
}
else
{
// Uncomment to enable lockout when password login fails
//await UserManager.AccessFailedAsync(user.Id);
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,我只是将用户返回到登录视图并显示错误消息.您可以将它们返回到另一个视图,该视图提供有关确认其电子邮件的后续步骤的更多详细信息,或者甚至为他们提供重新发送电子邮件确认的选项.
ile*_*eff 11
在ApplicationOAuthProvider.cs中
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
if (!user.EmailConfirmed)
{
context.SetError("invalid_grant", "Account pending approval.");
return;
}
}
Run Code Online (Sandbox Code Playgroud)
e4r*_*dog 10
我只是在登录成功时修改了案例:
case SignInStatus.Success:
if (!await UserManager.IsEmailConfirmedAsync((await UserManager.FindByNameAsync(model.Email)).Id))
{
Session.Abandon();
AuthenticationManager.SignOut();
ModelState.AddModelError("", "You need to confirm your email address");
return View(model);
}
return RedirectToLocal(returnUrl);
Run Code Online (Sandbox Code Playgroud)