26

When I create user by Register action whe application is running the application user gets SecurityStamp. When I add user by:

if (!context.Users.Any()) {
                System.Diagnostics.Debug.WriteLine("INSIDE");
                var hasher = new PasswordHasher();
                try {
                    var users = new List<ApplicationUser> { 
                        new ApplicationUser{PasswordHash = hasher.HashPassword("TestPass44!"), Email = "informatyka4444@wp.pl", UserName = "informatyka4444@wp.pl"},
                        new ApplicationUser{PasswordHash = hasher.HashPassword("TestPass44!"), Email = "informatyka4445@wp.pl", UserName = "informatyka4445@wp.pl"}
                        };

                    users.ForEach(user => context.Users.AddOrUpdate(user));

                    context.SaveChanges();
                } catch (DbEntityValidationException e) {
                    System.Diagnostics.Debug.WriteLine("EXC: ");
                    foreach (DbEntityValidationResult result in e.EntityValidationErrors) {
                        foreach (DbValidationError error in result.ValidationErrors) {
                            System.Diagnostics.Debug.WriteLine(error.ErrorMessage);
                        }
                    }

                }
            }

user doesn't get security stamp:

enter image description here

and then when I want to login I get:

enter image description here

Question: How to generate SecurityStamp for user?

Yoda
  • 17,363
  • 67
  • 204
  • 344
  • Why don't you use `UserManager.CreateAsync();` instead? – Moe Bataineh Aug 18 '14 at 02:45
  • @MohamadBataineh UserManager didn't work for me. Maybe I have done mistake somewhere: here is the topic --> http://stackoverflow.com/questions/25354751/no-users-have-been-created-during-seed-method-using-usermanager-in-asp-net-mvc?noredirect=1#comment39533134_25354751 – Yoda Aug 18 '14 at 02:48

2 Answers2

42

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 = "informatyka4444@wp.pl", 
                            UserName = "informatyka4444@wp.pl", 
                            SecurityStamp = Guid.NewGuid().ToString()
                        },
                    new ApplicationUser
                        {
                            PasswordHash = hasher.HashPassword("TestPass44!"),
                            Email = "informatyka4445@wp.pl", 
                            UserName = "informatyka4445@wp.pl", 
                            SecurityStamp = Guid.NewGuid().ToString()
                         }
                };
Nick Jones
  • 4,395
  • 6
  • 33
  • 44
Horizon_Net
  • 5,959
  • 4
  • 31
  • 34
  • 3
    It worked do you know why I couldn't login without this SequirtyStamp set? – Yoda Aug 20 '14 at 16:13
  • 1
    @Yoda I had the same problem some time ago, but I can only guess. I think that this property will be checked by the framework during the login process to make sure your database wasn't corrupted (or something like this). According to this [post](http://stackoverflow.com/questions/19487322/what-is-asp-net-identitys-iusersecuritystampstoretuser-interface) it is used to invalidate cookies. – Horizon_Net Aug 20 '14 at 16:27
  • 2
    The security stamp is used to invalidate a users login cookie and force them to re-login. http://stackoverflow.com/a/19505060/749626 – CowboyBebop Nov 11 '15 at 19:53
  • 3
    If it's null, your password reset may not work - "Invalid token." error – Savage Apr 21 '16 at 15:28
3

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.

Christos Lytras
  • 36,310
  • 4
  • 80
  • 113