Creating Simple Authentication Module for Sitecore Site – Part 1 (Registration)

Creating the Authentication Module for Sitecore Site requires below pages and functionalities:

  1. Registration Page
  2. Login Page
  3. Reset Password
  4. Update Profile

The above functionalities help the end customers to login to site and access the pages.

Let’s assume that you have a Sitecore SXA website and all the pages are gated. To setup the login for SXA website, you can refer this link.

In Part one, we will see how to create a Registration Page:

The idea behind creating a Registration page is taken from here, the only difference is we have simplified the approach by not setting any parameters.

Steps are as follows:

  1. Create a Sitecore Forms with the required fields:
    a. Full Name
    b. Email
    c. Password
  2. Create a custom submit action.
  3. Add the TryParse method so that your custom submit action is called, this step is very important as the link shared above expects parameters and we are not passing any.
  4. Submitting the Form creates a user in Sitecore Users.

Create Sitecore Form for Registration:

Create 3 Fields (FullName – Single Line, Email – Email and Password – Confirm Password) and a Submit button and add a custom submit action which we will create in next step.

Create custom Submit Action:

Create a .cs file and add a logic to register a user in Sitecore as an extranet user:

using Sitecore;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Models;
using Sitecore.ExperienceForms.Processing;
using Sitecore.ExperienceForms.Processing.Actions;
using Sitecore.Security.Accounts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TestApplication.Models;

namespace TestApplication.SubmitAction
{
	public class Registration : SubmitActionBase<string>
	{
		public Registration(ISubmitActionData submitActionData) : base(submitActionData)
		{
		}

		protected override bool TryParse(string value, out string target)
		{
			target = string.Empty;
			return true;
		}

		protected override bool Execute(string data, FormSubmitContext formSubmitContext)
		{
			Assert.ArgumentNotNull(data, nameof(data));
			Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));

			var fields = GetFormFields(formSubmitContext);

			Assert.IsNotNull(fields, nameof(fields));

			if (EmailOrPasswordFieldsIsNull(fields))
			{
				return AbortForm(formSubmitContext);
			}

			var result = Register(fields.Email, fields.Password, fields.FullName, Guid.NewGuid().ToString());

			if (!result)
			{
				return AbortForm(formSubmitContext);
			}

			return true;
		}

		protected virtual bool Register(string email, string password, string name, string profileId)
		{
			Assert.ArgumentNotNullOrEmpty(email, nameof(email));
			Assert.ArgumentNotNullOrEmpty(password, nameof(password));

			try
			{
				var user = User.Create(Context.Domain.GetFullName(email), password);
				user.Profile.Email = email;

				if (!string.IsNullOrEmpty(profileId))
				{
					user.Profile.ProfileItemId = profileId;
				}

				user.Profile.FullName = name;
				user.Profile.Save();
			}
			catch (Exception ex)
			{
				Log.SingleError("Register user failed", ex);
				return false;
			}

			return true;
		}

		private string GetValue(object field)
		{
			return field?.GetType().GetProperty("Value")?.GetValue(field, null)?.ToString() ?? string.Empty;
		}

		private RegisterUserFormFields GetFormFields(FormSubmitContext formSubmitContext)
		{
			Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));

			return new RegisterUserFormFields
			{
				Email = GetValue(formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals("Email"))),
				Password = GetValue(formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals("PasswordConfirmation"))),
				FullName = GetValue(formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals("FullName")))
			};
		}

		private bool EmailOrPasswordFieldsIsNull(RegisterUserFormFields field)
		{
			Assert.ArgumentNotNull(field, nameof(field));
			return field.Email == null || field.Password == null;
		}

		private bool EmailOrPasswordsIsNull(RegisterUserFieldValues values)
		{
			Assert.ArgumentNotNull(values, nameof(values));
			return string.IsNullOrEmpty(values.Email) || string.IsNullOrEmpty(values.Password);
		}

		private bool AbortForm(FormSubmitContext formSubmitContext)
		{
			formSubmitContext.Abort();
			return false;
		}

		internal class RegisterUserFormFields
		{
			public string Email { get; set; }
			public string Password { get; set; }
			public string FullName { get; set; }

			public RegisterUserFieldValues GetFieldValues()
			{
				return new RegisterUserFieldValues
				{
					Email = FieldHelper.GetValue(Email),
					Password = FieldHelper.GetValue(Password),
					FullName = FieldHelper.GetValue(FullName)
				};
			}
		}

		internal class RegisterUserFieldValues
		{
			public string Email { get; set; }
			public string Password { get; set; }
			public string FullName { get; set; }
		}
	}

}

Add submit action under Settings:

Add a Try Parse Empty string in your code (Custom Submit Action) [P.S. Ignore if you have directly copied the above code]:

protected override bool TryParse(string value, out string target)
		{
			target = string.Empty;
			return true;
		}

Form submission should create a user in Sitecore Users:

The Form will look something like this:

Once you submit with a valid email address and password policy, a user will be created in the Sitecore:

Hope it helps!! Lets meet in next part to understand how we can set up Login for this Authentication piece.

Thank you.. Keep Learning.. Keep Sitecoring.. đŸ™‚

One thought on “Creating Simple Authentication Module for Sitecore Site – Part 1 (Registration)

  1. Pingback: Creating Simple Authentication Module for Sitecore Site – Part 1 (Login) | Sitecore Diaries

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s