Manually initialize Asp.Net Identity tables?

2019-09-17 19:55发布

I created a website and published it to Azure. Now I want to protect some pages with authentication so I added the following code in the method Seed of Migrations.Configuration and published it to Azure.

However, the code is run even on local. The table AspNetRoles is still empty on both local and Azure SQL server. I tried to use Update-Database -Script -SourceMigration:0 to generate all the SQL statements but there is no SQL inserting the initial data to these tables of Asp.Net identity.

// Create role
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string roleName = "CanEdit";

var role = roleManager.FindByName(roleName);
if (role == null)
{
    role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(roleName);
    var roleresult = roleManager.Create(role);
}

var memberEmails = Properties.Settings.Default.CanEditMembers.Split(';');
foreach (var email in memberEmails)
{
    var user = userManager.FindByName(email.Trim());
    if (user != null)
    {
        var rolesForUser = userManager.GetRoles(user.Id);
        if (!rolesForUser.Contains(role.Name))
        {
            var result = userManager.AddToRole(user.Id, role.Name);
        }
    }
}

Basically I want to insert 'CanEdit' to the AspNetRoles (I guess) and insert some other values (Users and their associations with the role) to these AspNetUser.... tables. Some of my Controls are already decorated with attribute [Authorize(Roles = "CanEdit")].

0条回答
登录 后发表回答