最初如何使用ASP.NET MVC Core设置角色和用户(如站点管理员)? [英] How do I initially setup roles and users (like a site admin) with ASP.NET MVC Core?

查看:97
本文介绍了最初如何使用ASP.NET MVC Core设置角色和用户(如站点管理员)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然似乎有很多关于使用ASP.NET Core验证角色,声明等的文档,但关于在我的应用程序中最初设置这些内容的信息很少.

While there seems to be a lot of documentation about verifying roles, claims, etc with ASP.NET Core, there is little information about initially setting these things up in my app.

推荐答案

配置角色,声明等的最佳方法是在应用程序启动时.如果您知道自己在做什么,新的ASP.NET Core依赖注入将使设置起来变得轻而易举.您的大部分工作将在项目根目录的Startup.cs文件中进行.

The best way to configure roles, claims, etc, is in your app startup. The new ASP.NET Core Dependency Injection makes setting this up a breeze if you know what you're doing. Most of your work will happen in the Startup.cs file at the root of your project.

不要通过将新的用户密码硬编码到可以共享的存储库中来与世界共享.幸运的是,Microsoft为此提供了一个很好的工具.本文对其进行了详细说明:安全存储应用程序秘密

Don't share your new user secrets with the world by hard-coding them into repositories that may be shared. Luckily, Microsoft has provided a great tool for this. This article explains it in detail: Safe Storage of App Secrets

要确保以后可以使用此服务,请检查Startup.cs中的Startup构造方法:

To make sure this service is available later on, check the Startup constructor method in 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.设置您的应用程序数据库

我将Entity Framework Core用于我的持久性存储.当我使用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方法中调用的.首先,调用代码:

3. Create hooks in Configure method

This is where the real work starts. You'll want to configure a role with full administrative privileges and assign a first user to that role. I have chosen to put that code in a private method in Startup.cs that I call from within the Configure method. First, the calling code:

// 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帮助.看起来像这样:

I have found it useful to setup a static class that stores my role names. This allows me to check the names at compiletime, and gives me Intellisense help throughout my code when I need to invoke the role name elsewhere. It looks like this:

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

4.设置您的角色

已经做到了,现在我们要设置角色.记住,我使用ApplicationUser作为我的用户类型,并使用ApplicationRole作为我的角色类型.您可以使用不同的名称.将这些方法添加到Startup.cs文件的底部:

4. Set up Your Roles

Having done that, now we get to set up our roles. Remember, I used ApplicationUser as my user type and ApplicationRole as my role type. You may name yours differently. Add these methods to the bottom of the Startup.cs file:

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用户密码存储的.我们还检查以确保创建了我们的主要管理员角色,以便我们可以立即将此用户分配给该角色.

5. Create your new super user

Now we setup the method that's used to create the admin. We check to make sure that the user doesn't exist yet. The user name is stored using the dotnet user secrets mentioned above. We also check to make sure that our primary admin role is created so that we can immediately assign this user to that role.

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.享受吧!

希望这对您有所帮助.我真想找时间散布在网络上的所有这些信息.如果您有任何改进建议,请告诉我!

6. Enjoy!

I hope this helped you. I had a heck of a time finding all this information scattered throughout the web. If you have any suggestions for improvement, please let me know!

这篇关于最初如何使用ASP.NET MVC Core设置角色和用户(如站点管理员)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆