【问题标题】:Razor pages assign roles to usersRazor 页面为用户分配角色
【发布时间】:2018-12-31 04:44:27
【问题描述】:

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

我已经找到了如何为 MVC 应用程序(How to create roles in asp.net core and assign them to usershttp://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 页面中创建和播种角色。

将非常感谢您的帮助!

【问题讨论】:

    标签: razor-pages asp.net-roles


    【解决方案1】:

    接下来我会处理任务。首先,我使用了 Paul Madson 在How to create roles in asp.net core and assign them to users 中提出的代码。上述方法我已插入 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();
                }
            }
    
        }
    

    然后,在 Configure 方法的同一个文件中,我添加了参数 (IServiceProvider serviceProvider),因此您应该有类似 Configure(..., IServiceProvider serviceProvider) 的内容。在配置方法的末尾我添加了

    CreateRoles(serviceProvider).
    

    要使此代码正常工作,请在某个位置创建 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; }
        }
    }
    

    最后,在 ConfigureServices 内部方法替换

    services.AddIdentity<ApplicationUser>()
                .AddEntityFrameworkStores<SobopediaContext>()
                .AddDefaultTokenProviders();
    

    services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<SobopediaContext>()
                .AddDefaultTokenProviders();
    

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

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

    services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<SobopediaContext>()
                .AddDefaultTokenProviders();
    

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

    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 中删除所有与 EmailSernder 相关的内容。

    为了检查角色系统的正确性,您可以执行以下操作。在 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);
    

    如果它不起作用,那么只需将 [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.";
            }
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2010-10-09
      • 2020-07-23
      • 2020-10-16
      • 2016-03-09
      • 2018-08-21
      • 2020-11-24
      • 1970-01-01
      • 2019-06-04
      • 2017-11-23
      相关资源
      最近更新 更多