Author avatar

Peter Mbanugo

Securing ASP.NET MVC Applications with Log In, Email Confirmation, and Password Reset, Using MembershipReboot

Peter Mbanugo

  • Dec 15, 2018
  • 23 Min read
  • Dec 15, 2018
  • 23 Min read

Security and simplicity

We've always wanted to have an easy, secure way to manage users' accounts and authentication. Thanks to the ASP.NET team, ways of doing this keep getting better everyday, and we can see, over the years, the libraries been released for this purpose. We have moved from ASP.NET Membership, to SimpleMembership, and now ASP.NET Identity. I can look back early on in my career and see myself struggling trying to extend or add extra configuration to the then ASP.NET Membership. With this evolution, we have also moved from Role-based authorization to Claims-based authorization.

MembershipReboot (MR) is a Claims-based user account and identity management framework that makes it easy for you to manage users accounts. It encapsulates important security logic while being highly configurable and extensible. Some of its features are listed below:

  • Extensible templating for email notifications
  • Single- or multi-tenant account management
  • Account linking with external identity providers (enterprise or social)
  • Notification system for account activity and updates
  • Claims-aware user identities
  • Flexible account storage design (you can choose to store your data in a relational or non-relational data store)

In this tutorial, I am going to show you how to secure your ASP.NET MVC apps using MR. I will cover setup, user account creation, enabling email verification, and password setting. I will be doing this with a new project, but for existing apps, you can skip to the section about installing the needed nuget packages.

Creating a new MVC Web Application

  1. Select File > New Project > ASP.NET Web Application. Enter a name and click OK.
  2. Select the MVC template.
  3. Click on the Change Authentication button, choose No Authentication, and then click OK
  4. Now we have the project set-up and we're ready to roll

Installing the nuget packages

NuGet (nuget) is a free package manager for the Microsoft development platform. We need to install the following nuget packages:

  • Install-Package BrockAllen.MembershipReboot.WebHost

This is the Web Host package that performs the job of issuing cookies to track the user who is logged in, performing two-factor authentication, and handling the ApplicationInformation details. It has dependencies on BrockAllen.MembershipReboot(the core of the framework). As a result, these nuget packages were installed when we ran the above command.

  • Install-Package BrockAllen.MembershipReboot.Ef

This is the Entity Framework persistence implementation, responsible for persisting data to a SQL datastore. This is because it has a flexible storage design, where you can choose to store your data in either SQL or NoSQL database. For this tutorial, I've chosen to work with a SQL datastore using this package.

  • Install-Package SimpleInjector.Integration.Web.Mvc
  • Install-Package SimpleInjector.Extensions.ExecutionContextScoping

As you can see, we've downloaded SimpleInjector packages. We will be using SimpleInjector as our Dependency Injector (DI) container.

Replace Forms Authentication with Session Authentication Module (SAM)

Because MR is claims-based, we need to add settings for claims-based identity and Session Authentication Module (SAM) to the web.config. To do this, we need to:

  • First add references to System.IdentityModel and System.IdentityModel.Services.
  • Add some <configSections> elements to the web.config
1<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
2<section name="" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
  • Add configuration section for federation configuration
3<cookieHandler requireSsl="false" /> <!-- // set to true before deploying to production server // -->
  • Under <system.webServer>.<modules>, add the SAM (session authentication module) to the http modules list:
1<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />

Add settings for connecting to the database

MembershipReboot allows for flexible storage of the user account data, like I mentioned earlier. There is an EntityFramework package that implements the appropriate persistence interface, which we have installed already. For this, we need to set the connection string value, which by default, it looks for a connectionString named MembershipReboot. I'm going to use this default for this tutorial.

Adding this in your web.config file would look similar to:

1<add name="MembershipReboot" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=MembershipReboot;Integrated Security=True" providerName="System.Data.SqlClient" />

Configure email and security settings for MR

There are three important classes used for configuring MembershipReboot:

  • SecuritySettings

    The SecuritySettings class contains settings to configure MembershipReboot for certain security settings (such as account lockout duration and if email verification is required).

  • ApplicationInformation

    ApplicationInformation is a class that lets MembershipReboot know the name of the application and what URLs the application provides for various account related functions. This information is mainly used when sending emails or SMSs to the user.

  • MembershipRebootConfiguration

    MembershipRebootConfiguration is the main configuration class used by the UserAccountService. It contains the SecuritySettings and provides extensibility points for adding any custom logic related to validation or event notifications when account related data changes.

Configure the security settings for the application.

These values can be set via a custom configuration element in the configuration file, using the SecuritySettings class which then will passed to the MembershipRebootConfiguration class or, alternatively, passed during the creation of the MembershipRebootConfiguration class. I'm going to use the last option here.

To do that, we add a class that returns an instance of MembershipRebootConfiguration class, with the desired settings.

1public class MembershipRebootConfig
3    public static MembershipRebootConfiguration Create()
4    {
5        var config = new MembershipRebootConfiguration();
6        config.RequireAccountVerification = true;
7        config.EmailIsUsername = false;
9        return config;
10    }

Above, I set the RequireAccountVerification property to true, because I want accounts to be verified. I left the other settings to their default. This page shows other setting options you can set/configure and also their default value.

Add settings for sending emails

Email notifications are handled as part of MR's eventing system. As operations occur on the UserAccount class, an event is raised to indicate the operation. There is an event handler class for handling email events from the package we installed. It is called EmailAccountEventsHandler. The registration of this class is performed on the MembershipRebootConfiguration class via the AddEventHandler API. To instantiate the EmailAccountEventsHandler class, an instance of EmailMessageFormatter is needed. EmailMessageFormatter class reads templated text files that are embedded within the MembershipReboot assembly itself, and the EmailAccountEventsHandler class reads text that will be contained in the email from this class. This text is customizable by either deriving from EmailMessageFormatter or defining a new class that implements IMessageFormatter.

When sending emails, the EmailMessageFormatter needs to embed URLs back into the application. These endpoints are expected to be implemented by the application itself. To inform the EmailMessageFormatter of the URLs, the AspNetApplicationInformation class or the OwinApplicationInformation (used for owin based applications) can be used. It allows indicating relative paths for the various URLs. If more customization is required, the base ApplicationInformation class can be used instead.

For our solution, we're going to use the AspNetApplicationInformation class, so we need to update the code that creates a new instance of the MembershipRebootConfiguration class. Below is the update made to this class:

1public class MembershipRebootConfig
3    public static MembershipRebootConfiguration Create()
4    {
5        var config = new MembershipRebootConfiguration();
6        config.RequireAccountVerification = true;
7        config.EmailIsUsername = false;
9        var appInfo = new AspNetApplicationInformation(
10            "Test",
11            "Test tutorials",
12            "Account/Login/",
13            "Account/ConfirmEmail/",
14            "UserAccount/CancelRegistration/",
15            "Account/ConfirmPasswordReset/");
17        var emailFormatter = new EmailMessageFormatter(appInfo);
18        config.AddEventHandler(new EmailAccountEventsHandler(emailFormatter));
20        return config;
21    }

On instantiating the AspNetApplicationInformation class, we added URLs to actions which we will implement shortly. These URLs include links to log in, confirm account, and reset password.

For the emails to work, we need to add SMTP settings in the web.config file. Add this to your web.config:

2    <mailSettings>
3      <smtp from="###">
4         <network host="###" userName="###" password="#" port="#" />
5      </smtp>      
6    </mailSettings>
7  </>

Configure SimpleInjector

Next up, configure SimpleInjector to resolve instances of the needed classes of MR in the application. I'll be using the Dependency Injection (DI) pattern; any other DI library can be used, but I've chosen to use SimpleInjector for this tutorial. How these services are resolved will differ for other DI containers if they have other ways of configuring services to be injected.

To do this, I will add a class called SimpleInjectorConfig in the App_Start folder. I have this class here as I prefer to have my start-up configurations in this file, so it's a matter of preference, and how you do this is up to you. In there I will add a static method with settings for how the needed MR classes will be resolved, and will be called in the Application_Start of the Global.asax.cs. below, is how i've configured this class:

1public class SimpleInjectorConfig
3    public static void Register()
4    {
5        // Create the container as usual.
6        var container = new Container();
7        container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
9        // Register types:
10        container.RegisterSingleton<MembershipRebootConfiguration>(MembershipRebootConfig.Create);
11        container.RegisterPerWebRequest<DefaultMembershipRebootDatabase>(() => new DefaultMembershipRebootDatabase());
12        container.Register<UserAccountService>(() => new UserAccountService(container.GetInstance<MembershipRebootConfiguration>(), container.GetInstance<IUserAccountRepository>()));//Or make it InstancePerHttpRequest
13        container.Register<AuthenticationService, SamAuthenticationService>();
15        var defaultAccountRepositoryRegistration =
16            Lifestyle.Scoped.CreateRegistration<DefaultUserAccountRepository>(container);
18        container.AddRegistration(typeof(IUserAccountQuery), defaultAccountRepositoryRegistration);
19        container.AddRegistration(typeof(IUserAccountRepository), defaultAccountRepositoryRegistration);
22        // This is an extension method from the integration package.
23        container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
24        // This is an extension method from the integration package as well.
25        container.RegisterMvcIntegratedFilterProvider();
27        container.Verify();
28        //Set dependency resolver for MVC
29        DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
30    }

Now update your Global.asax.cs class to call the SimpleInjectorConfig.Register() method and add code to tell EntityFramework to add/create the needed tables for MR when the application starts.

1protected void Application_Start()
3    Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());
5    SimpleInjectorConfig.Register();
7    AreaRegistration.RegisterAllAreas();
8    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
9    RouteConfig.RegisterRoutes(RouteTable.Routes);
10    BundleConfig.RegisterBundles(BundleTable.Bundles);

Now we have this all set up. It's time to move on to the real deal.

Allow users create an account

We need to provide a means for the users to register/create an account. To do this:

  • We need add a class that to accept user input. So let's create a class called RegisterInputModel
1public class RegisterInputModel
3    [Required]
4    public string Username { get; set; }
6    [Required]
7    [EmailAddress]
8    public string Email { get; set; }
10    [Required]
11    [DataType(DataType.Password)]
12    public string Password { get; set; }
14    [Required]
15    [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "Password confirmation must match password.")]
16    [DataType(DataType.Password)]
17    public string ConfirmPassword { get; set; }
  • Then Add a conroller and add actions to handle the request for creating an account, confirming their email, and cancel the account creation request. Create a controller called Account and add the following code:
1public class AccountController : Controller
3    private readonly AuthenticationService _authenticationService;
4    private readonly UserAccountService _userAccountService;
6    public AccountController(AuthenticationService authenticationService)
7    {
8        _authenticationService = authenticationService;
9        _userAccountService = authenticationService.UserAccountService;
10    }
12    public ActionResult Register()
13    {
14        return View(new RegisterInputModel());
15    }
17    [ValidateAntiForgeryToken]
18    [HttpPost]
19    public ActionResult Register(RegisterInputModel model)
20    {
21        if (ModelState.IsValid)
22        {
23            try
24            {
25                _userAccountService.CreateAccount(model.Username, model.Password, model.Email);
27                return View("Success", model);
28            }
29            catch (ValidationException ex)
30            {
31                ModelState.AddModelError("", ex.Message);
32            }
33        }
34        return View(model);
35    }
37    public ActionResult Cancel(string id)
38    {
39        try
40        {
41            _userAccountService.CancelVerification(id);
42            return View("Cancel");
43        }
44        catch (ValidationException ex)
45        {
46            ModelState.AddModelError("", ex.Message);
47        }
48        return View("Error");
49    }

In this class, I have method that handle creating and account and also an action method to cancel/delete an account when the user who get's the email feels they didn't create an account on the application. So this deletes the account from the database. Also, you noticed that we used the UserAccountService class. This class has methods to create an account, delete an account, and more. We'll see these methods in this tutorial.

I have omitted the exact code I used for the views. You should add this to your code and design the UI how you want it.

Now when the user registers, an email is sent to them. Now, we need to add logic to verify their account.

Verify Account

Now we need to add logic for account verification.

  • Create a class called ChangeEmailFromKeyInputModel
1public class ChangeEmailFromKeyInputModel
3    [Required]
4    [DataType(DataType.Password)]
5    public string Password { get; set; }
7    [HiddenInput]
8    public string Key { get; set; }
  • Add the following code to the Account controller
2public ActionResult ConfirmEmail(string id)
4        var vm = new ChangeEmailFromKeyInputModel();
5        vm.Key = id;
6        return View("ConfirmEmail", vm);
12public ActionResult ConfirmEmail(ChangeEmailFromKeyInputModel model)
14    if (ModelState.IsValid)
15    {
16        try
17        {
18            UserAccount account;
19            _userAccountService.VerifyEmailFromKey(model.Key, model.Password, out account);
21            _authenticationService.SignIn(account);
22            return RedirectToAction("ConfirmSuccess");
23        }
24        catch (ValidationException ex)
25        {
26            ModelState.AddModelError("", ex.Message);
27        }
28    }
30    return View("ConfirmEmail", model);

Also, I would expect you create the views for this classes on your own, as they are simply input forms and success pages.

Reset Password

Next up, a common feature required in all apps, is the reset password feature, for resetting password to an account, just in case it's forgotten. For this:

  • Add a class for accepting the email of the account to reset
1public class PasswordResetInputModel
3    [Required]
4    [EmailAddress]
5    public string Email { get; set; }
  • And another class for accepting the new password to update the account
1public class ChangePasswordFromResetKeyInputModel
3    [Required]
4    [DataType(DataType.Password)]
5    public string Password { get; set; }
7    [Required]
8    [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "Password confirmation must match password.")]
9    [DataType(DataType.Password)]
10    public string ConfirmPassword { get; set; }
12    [HiddenInput]
13    public string Key { get; set; }
  • Then, add the following actions to the Account controller
1public ActionResult RequestPasswordReset()
3    return View();
8public ActionResult RequestPasswordReset(PasswordResetInputModel model)
10    if (ModelState.IsValid)
11    {
12        try
13        {
14            var account = _userAccountService.GetByEmail(model.Email);
15            if (account != null)
16            {
17                _userAccountService.ResetPassword(model.Email);
18                return View("ResetSuccess");
19            }
20            else
21            {
22                ModelState.AddModelError("", "Invalid email");
23            }
24        }
25        catch (ValidationException ex)
26        {
27            ModelState.AddModelError("", ex.Message);
28        }
29    }
30    return View(model);
33public ActionResult ConfirmPasswordReset(string id)
35    var vm = new ChangePasswordFromResetKeyInputModel()
36    {
37        Key = id
38    };
39    return View(vm);
44public ActionResult ConfirmPasswordReset(ChangePasswordFromResetKeyInputModel model)
46    if (ModelState.IsValid)
47    {
48        try
49        {
50            UserAccount account;
51            if (_userAccountService.ChangePasswordFromResetKey(model.Key, model.Password, out account))
52            {
53                if (account.IsLoginAllowed && !account.IsAccountClosed)
54                {
55                    _authenticationService.SignIn(account);
56                    return RedirectToAction("Index", "Home");
57                }
59                return View("PasswordUpdated");
60            }
61            else
62            {
63                ModelState.AddModelError("", "Error changing password. The key might be invalid.");
64            }
65        }
66        catch (ValidationException ex)
67        {
68            ModelState.AddModelError("", ex.Message);
69        }
70    }
71    return View();

With this, we have the reset password feature rolled out. Now we want to allow the users to log in to the application.

Allow users Login and Logout

And for the last part we add logic to allow users log in and out of the system. To start with, add a class for accepting users name and password

1public class LoginInputModel
3    [Required]
4    public string Username { get; set; }
5    [Required]
6    [DataType(DataType.Password)]
7    public string Password { get; set; }
9    public bool RememberMe { get; set; }
11    [ScaffoldColumn(false)]
12    public string ReturnUrl { get; set; }

Then add the follwoing action methods:

2public ActionResult Login()
4    return View(new LoginInputModel());
8public ActionResult Login(LoginInputModel model)
10    if (ModelState.IsValid)
11    {
12        UserAccount account;
13        if (_userAccountService.Authenticate(model.Username, model.Password, out account))
14        {
15            _authenticationService.SignIn(account, model.RememberMe);
17            if (Url.IsLocalUrl(model.ReturnUrl))
18            {
19                return Redirect(model.ReturnUrl);
20            }
22            return RedirectToAction("Index", "Home");
23        }
25        ModelState.AddModelError("", "Invalid Email or Password");
26    }
28    return View(model);
31public ActionResult Logout()
33    if (User.Identity.IsAuthenticated)
34    {
35        _authenticationService.SignOut();
36        return RedirectToAction("Login");
37    }
39    return RedirectToAction("Index", "Home");

For LoginInputModel, we have to validate the username and password and we do this with the UserAccountService.Authenticate() method. This method has various overloads but the one I've chosen checks against the username and passowrd. If this check is valid, we log the user in by calling AuthenticationService.SignIn() method, and log the user out by calling the SignOut() method on that same class.

The AuthenticationService class is a helper that bridges the gap between MembershipReboot and the running web application. It will perform the work of issuing cookies to track the logged in user. It also provides the assistance for performing two-factor authentication and supporting external login providers.


Hopefully I have sufficiently covered the basics of securing web application using MR, or MembershipReboot and explained a little about the framework. Future posts will show more use cases, such as two factor SMS authentication.

If you have any questions or problems running this, open an issue on the GitHub Repository. I hope you enjoyed my tutorial.