2016-11-18 3 views

答えて

4

ロール、クレームなどを設定する最も良い方法は、アプリの起動時です。新しいASP.NET Core Dependency Injectionは、自分が何をしているのかを知っていれば、これを簡単に設定できます。ほとんどの作業は、プロジェクトのルートにあるStartup.csファイルで行われます。

1.セットアップユーザ秘密

共有することができるレポジトリにそれらをハードコーディングすることによって世界と新しいユーザーの秘密を共有しないでください。幸運なことに、マイクロソフトはこのための素晴らしいツールを提供しています。この記事では詳細にそれを説明する:

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を設定したアプリケーションデータベース

私は」:Safe Storage of App Secrets

Startup.csStartupコンストラクタメソッドを確認し、このサービスは、後に利用可能であることを確認するには私の永続ストア用にEntity Framework Coreを使用しています。このコードは、Webアプリケーションテンプレートを使用してアプリケーションを作成したときに自動的に生成されました。しかし、私は参照とトラブルシューティング(まだ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方法

にフックを作成します。完全な管理者特権を持つ役割を構成し、その役割に最初のユーザーを割り当てる必要があります。私はConfigureメソッドから呼び出すStartup.csのプライベートメソッドにそのコードを入れることにしました。まず、呼び出しコード:

// 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です。あなたの名前は違うかもしれません。あなたの新しいスーパーユーザー

さて、セットアップ管理者を作成するのに使われているメソッドを作成します

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.:Startup.csファイルの最後に、これらのメソッドを追加します。ユーザーがまだ存在しないことを確認します。ユーザー名は、上記の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

関連する問題