How to create SecurityStamp for AspNetUser in ASP .NET MVC 5

If we look inside IdentityUser table AspNetUsers data, we'll see that SecurityStamp has a different form than a normal GUID:

Identity AspNetUsers

This is because the GUID is converted to a HEX map string.

We can create a function to generate new Security Stamps, that it will generate a new GUID and convert it to a HEX map string:

Func<string> GenerateSecurityStamp = delegate()
{
    var guid = Guid.NewGuid();
    return String.Concat(Array.ConvertAll(guid.ToByteArray(), b => b.ToString("X2")));
};

You can check it running to this .NET Fiddle.

So, if we want to seed Identity Users, we can use it to generate the SecurityStamp:

modelBuilder.Entity<IdentityUser>().HasData(new ApplicationUser
{
    ...

    // Security stamp is a GUID bytes to HEX string
    SecurityStamp = GenerateSecurityStamp(),
});

Warning: Be very careful and don't use the above example for seeding, because it will change the data every time we create a new migration. Seeding data should always be pre-generated when using HasData and not dynamic inline generated.


The security stamp can be anything you want. It is often mistaken to be a timestamp, but it is not. It will be overriden by ASP.NET Identity if something changes on the user entity. If you're working on the context directly the best way would to generate a new Guid and use it as the stamp. Here's a simple example:

var users = new List<ApplicationUser> 
                { 
                    new ApplicationUser
                        {
                            PasswordHash = hasher.HashPassword("TestPass44!"), 
                            Email = "[email protected]", 
                            UserName = "[email protected]", 
                            SecurityStamp = Guid.NewGuid().ToString()
                        },
                    new ApplicationUser
                        {
                            PasswordHash = hasher.HashPassword("TestPass44!"),
                            Email = "[email protected]", 
                            UserName = "[email protected]", 
                            SecurityStamp = Guid.NewGuid().ToString()
                         }
                };