Generate A Custom Password Using SqlMembership Provider

membership  •  c#  •  .net

We use SQLMembership provider a lot; however, we always add custom logic and extended fields in the database for the user (relating the login in the membership provider to our tables). Recently we had a request that the client wanted to "reset" their user's passwords and give be able to tell them their new password verbally.

To the page where they edit their users, i added some logic and a button for them to "Reset Password" which called the MembershipUser.ResetPassword() method.

This worked but it generated something like qS2xh&^23dtg as the password. They wanted this to be shorter and easier to remember (as a temporary password). This was easy, and gave me the chance to do something creative for once.

We decided to generate two random words and concatenate them for the new password. Since we are use the SQLMembershipProvider and not our own we had to override the GeneratePassword() function and place our logic in there.

First, I created a new class called ExtSQLMembershipProvider

public class ExtMembershipProvider : System.Web.Security.SqlMembershipProvider
    public ExtMembershipProvider()
        : base()


    public override string GeneratePassword()
        AppDataContext db = new AppDataContext();

        var words = db.Words.GetRandom(2).ToArray();

        return words[0].Word + words[1].Word;

You will notice I'm creating a call via LINQ to get two random words from the database and returning the first and second word. That is it... well, I did have to create the GetRandom extension method, but it was trivial – here is the code for that.

public static class Extenders
    public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> target, int count)
        Random r = new Random();
        for (int i = 0; i < count; i++)
            int position = r.Next(target.Count<T>());
            yield return target.ElementAt<T>(position);

Bam, set up a table with a bunch of random 4 or 5 letter words and you get passwords like houseball, much easier to remember than qS2xh&^23dtg!

The only thing that needs to change in the web.config is the membership provider type needs to be set to the assembly of your extended SQLMembershipProvider. In this case we have

<membership  defaultProvider="sqlProvider">
        <add name="sqlProvider" type="MyNamespace.ExtMembershipProvider" />

Easy 10 minute solution that made the client very happy!

comments powered by Disqus