2017-10-28 76 views
0

我用的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]與該令牌限制的服務。我的方法有什麼問題?

回答

0

問題是我沒有在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); 

}