Razor 页面为用户分配角色

Bog*_*dan 5 asp.net-roles razor-pages

我想知道如何在 Razor Pages 2.1 中创建和分配角色。应用。

我已经找到了如何为 MVC 应用程序制作它们(如何在 asp.net core 中创建角色并将它们分配给用户http://hishambinateya.com/role-based-authorization-in-razor-pages),但是它确实如此不适用于剃刀页面,因为我没有 IServicesProvider 实例。

我想要的只是创建管理员角色并将其分配给种子管理员帐户。在本教程https://docs.microsoft.com/en-us/aspnet/core/security/authorization/secure-data?view=aspnetcore-2.1 中已经做了类似的事情,但它似乎适用于 MVC 而没有在我将它应用到我的应用程序后正常工作。请帮助我了解如何在 Razor Pages 中创建和播种角色。

将非常有帮助!

Bog*_*dan 5

我接下来处理任务。首先,我使用了 Paul Madson 在How to create roles in asp.net core 中提出的代码并将其分配给用户。上面提到的方法我已经插入到 Startup.cs 中。它创建管理员角色并将其分配给种子用户。

    private void CreateRoles(IServiceProvider serviceProvider)
    {
        var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        Task<IdentityResult> roleResult;
        string email = "someone@somewhere.com";

        //Check that there is an Administrator role and create if not
        Task<bool> hasAdminRole = roleManager.RoleExistsAsync("Administrator");
        hasAdminRole.Wait();

        if (!hasAdminRole.Result)
        {
            roleResult = roleManager.CreateAsync(new IdentityRole("Administrator"));
            roleResult.Wait();
        }

        //Check if the admin user exists and create it if not
        //Add to the Administrator role

        Task<ApplicationUser> testUser = userManager.FindByEmailAsync(email);
        testUser.Wait();

        if (testUser.Result == null)
        {
            ApplicationUser administrator = new ApplicationUser
            {
            Email = email,
            UserName = email,
            Name = email
            };

            Task<IdentityResult> newUser = userManager.CreateAsync(administrator, "_AStrongP@ssword!123");
            newUser.Wait();

            if (newUser.Result.Succeeded)
            {
                Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(administrator, "Administrator");
                newUserRole.Wait();
            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

然后,在 Configure 方法的同一个文件中,我添加了参数 (IServiceProvider serviceProvider),所以你应该有类似 Configure(..., IServiceProvider serviceProvider) 的东西。在配置方法的末尾我添加

CreateRoles(serviceProvider).
Run Code Online (Sandbox Code Playgroud)

要使此代码起作用,请在某处创建 ApplicationUser 类,例如在 Data 文件夹中:

using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sobopedia.Data
{
    public class ApplicationUser: IdentityUser
    {
        public string Name { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,在 ConfigureServices 方法中替换

services.AddIdentity<ApplicationUser>()
            .AddEntityFrameworkStores<SobopediaContext>()
            .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<SobopediaContext>()
            .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

因此,在表 AspNetRoles 中启动程序后,您将获得一个新角色,而在表 AspNetUsers 中,您将获得一个新的用户管理管理员角色。

不幸的是,添加以下代码后

services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<SobopediaContext>()
            .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

页面登录和注册停止工作。为了处理这个问题,您可以按照以下步骤操作:

  1. 脚手架标识如下(https://docs.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.1&tabs=visual-studio)。

  2. 然后在整个解决方案中用 IdentityUser 替换 ApplicationUser。在 ApplicationUser 类中仅保留 IdentityUser 继承。

  3. 如果没有实现,则从 Areas/identity/Pages/Account/Register.cs 中删除与 EmailSerder 相关的所有内容。

为了检查角色系统的正确性,您可以执行以下操作。在 Startup.cs 的 ConfigureServices 方法的末尾添加以下代码:

 services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
            });

    services.AddMvc().AddRazorPagesOptions(options =>
                {
options.Conventions.AuthorizeFolder("/Contact","RequireAdministratorRole");
                }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
Run Code Online (Sandbox Code Playgroud)

如果它不起作用,那么只需将 [Authorize(Roles = "Administrator")] 添加到 Contact Page 模型,它看起来像这样:

namespace Sobopedia.Pages
{
    [Authorize(Roles = "Administrator")]
    public class ContactModel : PageModel
    {
        public string Message { get; set; }

        public void OnGet()
        {
            Message = "Your contact page.";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,为了打开联系页面,您应该使用登录名someone@somewhere.com 和密码_AStrongP@ssword!123 登录。