Try our conversational search powered by Generative AI!

Binh Nguyen Thi
Apr 24, 2020
  9475
(1 votes)

Lock and Unlock account using AspNet Identity

You are using AspNet Identity for authentication and want to configure to block user if he/she inputs wrong password over a certainly allowed login attempts. I have had an experience to implement this function in EpiServer version 11 and Microsoft.AspNet.Identity 2.2

Here are steps:

1. Configure user lockout in your ApplicationUserManager as mentioned in https://world.episerver.com/documentation/developer-guides/CMS/security/episerver-aspnetidentity/

// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true; //This flag is true it means will enable lockout when users are created. Noticed that a user is locked if LockEnable flag is true and LockoutEndDateUtc is set and greater than now
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(60); //User will be locked in 60 minutes
manager.MaxFailedAccessAttemptsBeforeLockout = 5; //User will be locked after 5 continuesly failed attempts

2. Pass shouldLockout is true when you call to validate user for login

  var signInStatus = await _signInManager.PasswordSignInAsync(username, password, isPersistent, shouldLockout:true);

3. If there are a lot of existed users that created before turning on user lockout functionality then you should migrate all existed user to enable lockout for them if you want to apply user lockout for all existed users too. You can create an Episerver migration step to do that like this:

    [ServiceConfiguration(typeof(IMigrationStep))]
    public class EnableUserLockOutMigrationStep : IMigrationStep
    {
        private readonly IConnectionStringHandler _connectionHandler;

        public EnableUserLockOutMigrationStep(IConnectionStringHandler connectionHandler)
        {
            this._connectionHandler = connectionHandler;
        }

        public bool Execute(IProgressMessenger progressMessenger)
        {
            progressMessenger.AddProgressMessageText("Enabling user lockout...", false, 0);
            try
            {
              
                using (SqlConnection connection = new SqlConnection(this._connectionHandler.Commerce.ConnectionString))
                {
                    connection.Open();
                    using (SqlTransaction transaction = connection.BeginTransaction())
                    {
                        try
                        {
                            this.CreateCommand(transaction, @"UPDATE [dbo].[AspNetUsers] SET [LockoutEnabled] = 1", 300).ExecuteNonQuery();
                            transaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            connection.Close();

                            throw new Exception((string)null, ex);
                        }
                    }
                    connection.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                progressMessenger.AddProgressMessageText(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Enable user lockout has failed with exception '{0}'.", (object)ex), true, 0);
            }
            return false;
        }

        public int Order => 1000;
        public string Name => "Enable User Lockout";
        public string Description => "This is used to turn on Enable User Lockout for existed users";

        private SqlCommand CreateCommand(
            SqlTransaction transaction,
            string query,
            int timeout = 30)
        {
            return new SqlCommand
            {
                Connection = transaction.Connection,
                Transaction = transaction,
                CommandType = CommandType.Text,
                CommandText = query,
                CommandTimeout = timeout
            };
        }
    }

Tada, it is not too complicated to enable lockout account, right? So what about if you want to unblock account somewhere? I see that we can do that in editing user view in admin mode like that:

But it seems this function works well if we use Membership Provider for authentication. It does not works if I use Aspnet Identity.

I found that the episerver is using IsLockedOut to check lockout status and unblock user by changing IsLockedOut to false. But currently Aspnet Identity uses the LockEnable flag and LockoutEndDateUtc to check lockout status. So the solution that I use to unblock user in Aspnet Identity is creating a custom user that inherited from Application and over IsLockedOut property like this:

        public override bool IsLockedOut
        {
            get => LockoutEnabled && LockoutEndDateUtc != null && LockoutEndDateUtc >= DateTime.UtcNow;
            set
            {
                if (!LockoutEnabled || value) return;

                if (LockoutEndDateUtc != null && LockoutEndDateUtc > DateTime.UtcNow)
                {
                    LastLockoutDate = LockoutEndDateUtc = DateTime.UtcNow;
                }
                AccessFailedCount = 0;
            }
        }

That is all. Now you can unblock account in Episerver admin mode as usual.

Apr 24, 2020

Comments

Please login to comment.
Latest blogs
From Procrastination to Proficiency: Navigating Your Journey to Web Experimentation Certification

Hey there, Optimizely enthusiasts!   Join me in celebrating a milestone – I'm officially a certified web experimentation expert! It's an exhilarati...

Silvio Pacitto | May 17, 2024

GPT-4o Now Available for Optimizely via the AI-Assistant plugin!

I am excited to announce that GPT-4o is now available for Optimizely users through the Epicweb AI-Assistant integration. This means you can leverag...

Luc Gosso (MVP) | May 17, 2024 | Syndicated blog

The downside of being too fast

Today when I was tracking down some changes, I came across this commit comment Who wrote this? Me, almost 5 years ago. I did have a chuckle in my...

Quan Mai | May 17, 2024 | Syndicated blog

Optimizely Forms: Safeguarding Your Data

With the rise of cyber threats and privacy concerns, safeguarding sensitive information has become a top priority for businesses across all...

K Khan | May 16, 2024

The Experimentation Process

This blog is part of the series -   Unlocking the Power of Experimentation: A Marketer's Insight. Welcome back, to another insightful journey into...

Holly Quilter | May 16, 2024

Azure AI Language – Sentiment Analysis in Optimizely CMS

In the following article, I showcase how sentiment analysis, which is part of the Azure AI Language service, can be used to detect the sentiment of...

Anil Patel | May 15, 2024 | Syndicated blog