gpt4 book ai didi

c# - 如何使用 ASP.NET MVC Core 初始设置角色和用户(如站点管理员)?

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:43 26 4
gpt4 key购买 nike

关闭。这个问题需要更多 focused .它目前不接受答案。












想改进这个问题?更新问题,使其仅关注一个问题 editing this post .

5年前关闭。




Improve this question




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

最佳答案

配置角色、声明等的最佳方式是在您的应用启动时。如果您知道自己在做什么,那么新的 ASP.NET Core 依赖注入(inject)使设置变得轻而易举。您的大部分工作将发生在 Startup.cs项目根目录下的文件。

1.设置用户密码

不要通过将您的新用户 secret 硬编码到可能共享的存储库中来与世界分享您的新用户 secret 。幸运的是,微软为此提供了一个很好的工具。本文详细讲解: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. 设置您的应用程序数据库

我将 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中创建钩子(Hook)方法

这是真正的工作开始的地方。您需要配置一个具有完全管理权限的角色并将第一个用户分配给该角色。我选择将该代码放在 Startup.cs 中的私有(private)方法中。我从 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. 创建你的新 super 用户

现在我们设置用于创建管理员的方法。我们检查以确保用户还不存在。用户名是使用上面提到的 dotnet 用户 secret 存储的。我们还检查以确保我们的主要管理员角色已创建,以便我们可以立即将此用户分配给该角色。
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.享受!

我希望这对你有所帮助。我花了很长时间才找到散布在网络上的所有这些信息。如果您有任何改进建议,请告诉我!

关于c# - 如何使用 ASP.NET MVC Core 初始设置角色和用户(如站点管理员)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40686699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com