London Dev Meetup Rescheduled! Due to unavoidable reasons, the event has been moved to 21st May. Speakers remain the same—any changes will be communicated. Seats are limited—register here to secure your spot!

Loading...
Applies to versions: 10-13
Other versions:
ARCHIVED This content is retired and no longer maintained. See the version selector for other versions of this topic.

ASP.NET Identity Registrar [Legacy]

The following examples show how to use the ASP.NET Identity Registrar in Episerver Commerce. See ASP.NET Identity.

Note: This configuration requires the EPiServer.Commerce.Security NuGet package as dependency.

using EPiServer.Commerce.Security;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using EPiServer.Web;
using log4net;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Routing;
using System.Web.Security;

namespace WebApplication1
  {
    [InitializableModule]
    [ModuleDependency(typeof(Mediachase.Commerce.Initialization.CommerceInitialization),
                      typeof(EPiServer.Commerce.Initialization.InitializationModule))]
    public class InitializeCommerceSiteModule : IConfigurableModule
      {
        public void Initialize(InitializationEngine context)
          {
          }
        public void Preload(string[] parameters)
          {
          }
        public void Uninitialize(InitializationEngine context)
          {
          }
        public void ConfigureContainer(ServiceConfigurationContext context)
          {
            context.Container.Configure(ce =>
              {
                ce.For<IRegistrar>().Singleton().Use(() => 
                  new IdentityRegistrar<ApplicationUser>(new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()))));
              });
          }
      }
  }

When using the ASP.NET Identity registrar with MVC, you need to make all action results async since all ASP.NET Identity methods are async. The following example shows this when creating a new user.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task Register(FormCollection model)
  {
    if (ModelState.IsValid)
      {
        string firstName = model["Email"];
        string lastName = model["Email"];
        string emailAddress = model["Email"];
        string password = model["Password"];
        var principal = await Task.Run(() => _registrar.CreateUser(emailAddress, password, emailAddress));
                
        // Now create an account in the ECF 
        CustomerContact customerContact;
        if (_registrar is CustomerContactRegistrar)
          {
            customerContact = CustomerContext.Current.GetContactByUserId(
              new MapUserKey(s => new ConvertStringUserKey()).ToTypedString(principal.Identity.Name));
          }
        else
          {
            customerContact = CustomerContact.CreateInstance(principal);
          }
        customerContact.FirstName = firstName;
        customerContact.LastName = lastName;
        customerContact.RegistrationSource = String.Format("{0}, {1}", this.Request.Url.Host, SiteContext.Current);
        customerContact["Email"] = emailAddress;
        customerContact.SaveChanges();
        await Task.Run(() =>_registrar.SignIn
          (
            new AuthenticationProperties()
              {
                IsPersistent = false
              },
              principal.Identity as ClaimsIdentity
          );
        return RedirectToAction("Index");
      }

    // If we got this far, something failed, redisplay form
    return View(model);
  }

Last updated: Mar 31, 2021