2016-11-18 40 views

回答

4

配置角色,聲明等的最佳方式是在您的應用程序啓動中。如果您知道自己在做什麼,新的ASP.NET核心依賴注入可以輕鬆完成設置。您的大部分工作將發生在項目根目錄的Startup.cs文件中。

1.設置用戶祕密

不要被硬編碼到它們可以共享資源庫與世界分享你的新用戶的祕密。幸運的是,微軟爲此提供了一個很好的工具。這篇文章解釋得很詳細:Safe Storage of App Secrets

爲了確保該服務可用以後,檢查Startup構造方法在Startup.cs

public Startup(IHostingEnvironment env) { 
    ... 
    if (env.IsDevelopment()) { 
     // BELOW IS THE IMPORTANT LINE 
     builder.AddUserSecrets(); 
    } 
    ... 
    // This is important, too. It sets up a readonly property 
    // that you can use to access your user secrets. 
    Configuration = builder.Build(); 
} 

// This is the read-only property 
public IConfigurationRoot Configuration { get; } 

2.設置應用程序的數據庫

我m使用實體框架核心爲我的持久性存儲。當我使用Web App模板創建我的應用程序時,此代碼是自動生成的。但我會在這裏包括以供參考和故障排除(仍在Startup.cs):

public void ConfigureServices(IServiceCollection services) 
{ 
    // My Db Context is named "ApplicationDbContext", which is the 
    // default name. Yours might be something different. 
    // Additionally, if you're using a persistence store other than 
    // MSSQL Server, you might have a different set of options here. 
    services.AddDbContext<ApplicationDbContext>(options => 
     options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 

    // This sets up the basics of the Identity code. "ApplicationUser" 
    // is the name of the model that I use for my basic user. It's simply 
    // a POCO that can be modified like any EF model, and it's the default 
    // name for a user in the template. "ApplicationRole" is a class that I 
    // wrote that inherits from the "IdentityRole" base class. I use it to 
    // add a role description, and any other future data I might want to 
    // include with my role. I then tell the Identity code to store it's 
    // data in the "ApplicationDbContext" that I just setup. 
    services.AddIdentity<ApplicationUser, ApplicationRole>() 
     .AddEntityFrameworkStores<ApplicationDbContext>() 
     .AddDefaultTokenProvider(); 

    // This sets up the MVC framework. 
    services.AddMvc(); 
    ... 
} 

3. Configure方法

這是真正的工作開始在那裏創建掛鉤。您需要配置具有完全管理權限的角色並將第一個用戶分配給該角色。我選擇在Startup.cs中的私有方法中使用該代碼,我從Configure方法中調用該代碼。首先,調用代碼:

// This method is not async out-of-the-box. Add the `async` modifier 
// but keep the return type as `void`, since the signature needs to 
// stay the same or you'll get a 500 error. We mark it as async because 
// the Identity methods are mostly async methods. 
public async void Configure(
    IApplicationBuilder app, 
    IHostingEnvironment env, 
    ILoggerFactory loggerFactory) 
{ 
    ... 
    // Default ASP.NET Core route (generated out of the box) 
    // I've included this so you know where to put your code! 
    app.UseMvc(routes => 
    { 
     routes.MapRoute(
      name: "default", 
      template: "{controller=Home}/{action=Index}/{id?}"); 
    }); 

    // Her, we call the code that setups up our roles and our first user. 
    // These are methods added to the `Startup` class. We use the 
    // IApplicationBuilder variable to pass in a User and Role 
    // Manager instance from the application services. 
    await CreateRoles(
     app.ApplicationServices 
      .GetRequiredService<RoleManager<ApplicationRole>>()); 
    await ConfigureSiteAdmin(
     app.ApplicationServices 
      .GetRequiredService<RoleManager<ApplicationRole>>(), 
     app.ApplicationServices 
      .GetRequiredService<UserManager<ApplicationUser>>() 
    ); 
} 

我發現設置一個存儲我的角色名稱的靜態類很有用。這使我可以在編譯時檢查名稱,並且當我需要在其他地方調用角色名稱時,在整個代碼中爲我提供Intellisense幫助。它看起來像這樣:

public static class RoleNames 
{ 
    public const string SiteAdmin = "Site Admin"; 
    public const string CompanyAdmin = "Company Admin"; 
    ... 
} 

4.設置你的角色

已經這樣做了,現在我們要建立我們的角色。請記住,我使用ApplicationUser作爲我的用戶類型,並使用ApplicationRole作爲我的角色類型。你可以用不同的名稱命名你的。這些方法添加到Startup.cs文件的底部:

private async Task CreateRoles(RoleManager<ApplicationRole> roleManager) 
{ 
    var roles = new List<ApplicationRole> 
    { 
     // These are just the roles I made up. You can make your own! 
     new ApplicationRole {Name = RoleName.SiteAdmin, 
          Description = "Full access to all features."}, 
     new ApplicationRole {Name = RoleName.CompanyAdmin, 
          Description = "Full access to features within their company."} 
    }; 

    foreach (var role in roles) 
    { 
     if (await roleManager.RoleExistsAsync(role.Name)) continue; 
     var result = await roleManager.CreateAsync(role); 
     if (result.Succeeded) continue; 

     // If we get here, something went wrong. 
     throw new Exception($"Could not create '{role.Name}' role."); 
    } 
} 

5.創建新的超級用戶

現在我們設置的是被用於創建管理方法。我們檢查以確保用戶不存在。用戶名使用上面提到的dotnet用戶機密來存儲。我們還檢查以確保我們的主管理員角色已創建,以便我們可以立即將此用戶分配給該角色。

private async Task ConfigureSiteAdmin(
    RoleManager<ApplicationRole> roleManager, 
    UserManager<ApplicationUser> userManager) 
{ 
    if (await userManager.FindByEmailAsync(Configuration["SiteAdminEmail"]) != null) 
     return; 
    if (!await roleManager.RoleExistsAsync(RoleName.SiteAdmin)) 
     throw new Exception($"The {RoleName.SiteAdmin} role has not yet been created."); 

    var user = new ApplicationUser 
    { 
     UserName = Configuration["SiteAdminEmail"], 
     Email = Configuration["SiteAdminEmail"], 
    }; 

    await userManager.CreateAsync(user, Configuration["SiteAdminPassword"]); 
    await userManager.AddToRoleAsync(user, RoleName.SiteAdmin); 
} 

6.享受!

我希望這對你有所幫助。我花了大量的時間來查找散佈在整個網絡中的所有這些信息。如果您有任何改進建議,請告訴我!

+1

歡迎來到StackOverflow。您應該考慮將這些內容中的一部分添加到StackOverflow的_Documentation_部分。查看頁面頂部的標籤。 –

+1

考慮使用此模式(http://stackoverflow.com/documentation/asp.net-core/1949/dependency-injection/17400/using-scoped-services-during-application-startup-database-seeding#t=201611182214295112758)用於種子或在應用程序啓動時使用範圍內的服務,因爲此時不存在範圍。 – Tseng

相關問題