Tuesday, September 15, 2015

Implementing Forgot Password and Email Confirmation in ASP.NET Identity

This is one of those tasks that is not very difficult to actually accomplish but exceedingly difficult to find good instructions on how to do it.  Forgot Password is simply a page where the user can enter his or her email address if he has forgotten his/her password.  He/she then receives an email containing a link where the password can be reset.  Email Confirmation means that when a user first registers, he/she cannot log in until the email is confirmed.  How is the email confirmed?  The person is sent an email containing a link to click that will mark the address as confirmed.  This all sounds complicated, but ASP.NET Identity builds all of this for you when you create an ASP.NET web application with Individual Accounts.  However, the code in the AccountController is commented out initially.  Because email is a central part of these operations, you must first configure your email.

To configure your email, just open up the IdentityConfig.vb file.  Find the EmailService class and add code to the SendAsync method.  The code below illustrates some code that sends an email using a traditional SMTP server:

Public Class EmailService
    Implements IIdentityMessageService

    Public Function SendAsync(message As IdentityMessage) As Task Implements IIdentityMessageService.SendAsync
        ' Plug in your email service here to send an email.

        Dim SmtpServer As String

        If System.Configuration.ConfigurationManager.AppSettings("SmtpServer") Is Nothing Then
            Throw New Exception("The SmtpServer key is not present in the web.config file.")
        Else
            SmtpServer = System.Configuration.ConfigurationManager.AppSettings("SmtpServer")
        End If

        Dim FromAddress As String

        If System.Configuration.ConfigurationManager.AppSettings("ConfirmationEmailFrom") Is Nothing Then
            Throw New Exception("The ConfirmationEmailFrom key is not present in the web.config file.")
        Else
            FromAddress = System.Configuration.ConfigurationManager.AppSettings("ConfirmationEmailFrom")
        End If

        Dim MyClient As New System.Net.Mail.SmtpClient(SmtpServer)

        Dim MyMessage As New System.Net.Mail.MailMessage

        MyMessage.From = New Net.Mail.MailAddress(FromAddress)

        MyMessage.Subject = message.Subject

        MyMessage.Body = message.Body
        MyMessage.IsBodyHtml = True

        MyMessage.To.Add(message.Destination)

        MyClient.Send(MyMessage)

        Return Task.FromResult(0)

    End Function

End Class

Once this is configured, go back to your AccountController and uncomment out the appropriate lines.

No comments:

Post a Comment