Search code examples
c#asp.netwebformsasp.net-identity

How to prevent auto login after registration in ASP.Net Web Forms (Identity)?


After account registration the user is automatically logged-in to the site. How can I prevent this process by sending an confirmation email first to the user and then after the account is confirmed the user can login?

Basically no user is allowed to access the site without being confirmed.

Register.aspx.cs

namespace Web_WebApp.Account
{
    public partial class Register : Page
    {
        protected void CreateUser_Click(object sender, EventArgs e)
        {

            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
            //var user = new ApplicationUser() { UserName = UserName.Text, Email = Email.Text, FirstName = FirstName.Text, MiddleName = MiddleName.Text, LastName = LastName.Text, RegistrationDate = DateTime.Now };


            var user = new ApplicationUser()
            {
                UserName = UserName.Text,
                Email = Email.Text,
                FirstName = FirstName.Text,
                MiddleName = MiddleName.Text,
                LastName = LastName.Text,
                RegistrationDate = DateTime.Now,

            };


            IdentityResult result = manager.Create(user, Password.Text );

            if (result.Succeeded)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771


                string code = manager.GenerateEmailConfirmationToken(user.Id);
                string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");

                signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else 
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
    }
}

I appreciate your efforts in reaching a solution for my question.


Solution

  • I would remove the line:

    signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);
    

    This will prevent the user from being logged in before receiving the email, and confirming the user account.

    Then I would redirect the user to a page where it says that he/she should check their inbox for a confirmation e-mail.

    PS: Remember to check for user.EmailConfirmed when logging in a user, then present them the "An email has been sent..." if they try to log in without confirming the account.