获得令牌中的ASP.NET Web API未验证的电子邮件有两个因素认证功能

问题描述:

我用的ASP.NET Web API工作,我启用了双因素身份验证来验证用户的电子邮件:获得令牌中的ASP.NET Web API未验证的电子邮件有两个因素认证功能

public class ApplicationUserManager : UserManager<ApplicationUser> 
{ 
    // ... 
    manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser> 
    { 
     Subject = "Security Code", 
     BodyFormat = "Your security code is {0}" 
    }); 
    manager.EmailService = new EmailService(); 

    var dataProtectionProvider = options.DataProtectionProvider; 
    if (dataProtectionProvider != null) 
    { 
     manager.UserTokenProvider = 
     new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")) 
      { 
       //Code for email confirmation and reset password life time 
       TokenLifespan = TimeSpan.FromHours(24) 
      }; 
    } 
} 

我加了一个类命名EmailService以发送电子邮件验证链接项目和它的作品罚款:在数据库

public class EmailService : IIdentityMessageService 
{ 
    public Task SendAsync(IdentityMessage message) 
    { 
     SmtpClient client = new SmtpClient 
     { 
      Port = 25, 
      DeliveryMethod = SmtpDeliveryMethod.Network, 
      UseDefaultCredentials = false, 
      Host = "mail.myserver.com", 
      Credentials = new System.Net.NetworkCredential("[email protected]", "secret") 
     }; 

     MailMessage mail = new MailMessage("[email protected]", message.Destination); 
     mail.Subject = message.Subject; 
     mail.Body = message.Body; 
     return client.SendMailAsync(mail); 
    } 

截图为新注册的用户记录:

enter image description here

的问题是,在我的Android客户端,我可以确认邮件后,得到Access Token和我能够调用与[Authorize]与该令牌限制的服务。我的方法有什么问题?

问题是我没有在ApplicationOAuthProvider类中检查EmailConfirmed。新if声明说解决了这个问题:

公众覆盖异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext上下文) {VAR 的UserManager = context.OwinContext.GetUserManager();

ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); 

if (user == null) 
{ 
    context.SetError("invalid_grant", "The user name or password is incorrect."); 
    return; 
} 

// This if was required: 
if (!user.EmailConfirmed) 
{ 
    context.SetError("email_not_confirmed", "You did not confirm your email."); 
    return; 
} 

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, 
    OAuthDefaults.AuthenticationType); 
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, 
    CookieAuthenticationDefaults.AuthenticationType); 

AuthenticationProperties properties = CreateProperties(user.UserName); 
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); 
context.Validated(ticket); 
context.Request.Context.Authentication.SignIn(cookiesIdentity); 

}