Uladz Kha
Uladz Kha

Reputation: 2364

How to add new user to database using sql in .net core 3.0 application?

In my application i want just user login without registration,to disable registration i was following this article.

To add new user into database i use sql:

INSERT INTO AspNetUsers
(
[UserName],
[Email],
[EmailConfirmed],
[PasswordHash],
[AccessFailedCount],
[Id],
[PhoneNumberConfirmed],
[TwoFactorEnabled],
[LockoutEnabled]
)VALUES
(
'Uladz',
'test@gmailcom',
'true',
'adm1nPassWorD*_',
'3',
'1',
'false',
'false',
'true'
)

but i have problem with [PasswordHash] insert it as regular string makes no sense it has to be encrypted by identity.

Could you please tell me how can i get it or i have to use another way to do it ?

Upvotes: 0

Views: 524

Answers (1)

Xueli Chen
Xueli Chen

Reputation: 12705

You could try Data seeding to set the user data.

1.add a new class called MyIdentityDataSeeder

 public static class MyIdentityDataSeeder
    {
        public static void SeedData(UserManager<IdentityUser> userManager)
        {
            SeedUsers(userManager); 
        }

        public static void SeedUsers(UserManager<IdentityUser> userManager)
        {
            if (userManager.FindByNameAsync("Uladz").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.UserName = "Uladz";
                user.Email = "test@gmailcom";
                user.EmailConfirmed = true;
                user.AccessFailedCount = 3;
                user.Id = "1";
                user.PhoneNumberConfirmed = false;
                user.TwoFactorEnabled = false;
                user.LockoutEnabled = true;

                IdentityResult result = userManager.CreateAsync(user, "adm1nPassWorD*_").Result;

            }
        }
    }

2.modify your Configure() method signature as shown below

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<IdentityUser> userManager)
    {
        ...
        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();


        MyIdentityDataSeeder.SeedData(userManager);

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });
    }

Reference: http://www.bipinjoshi.net/articles/5e180dfa-4438-45d8-ac78-c7cc11735791.aspx

Upvotes: 2

Related Questions