使用受授权的用户数据创建 ASP.NET Core 应用Create an ASP.NET Core app with user data protected by authorization

本文内容

作者:Rick AndersonJoe Audette

请参阅此 PDF ASP.NET Core MVC 版本。本教程的 ASP.NET Core 1.1 版本是文件夹。ASP.NET Core 示例是在 1.1示例

请参阅此 pdf

本教程演示如何使用受授权的用户数据创建 ASP.NET Core web 应用。它显示的身份验证 (注册) 的用户的联系人列表已创建。有三个安全组:

  • 注册用户可以查看所有已批准的数据还可以编辑/删除其自己的数据。
  • 管理器可以批准或拒绝的联系人数据。仅已批准的联系人是对用户可见。
  • 管理员可以批准/拒绝和编辑/删除的任何数据。

此文档中的图像与最新模板并不完全匹配。

在下图中,用户 Rick (rick@example.com) 登录。Rick 只能查看允许的联系人和编辑/删除/新建其联系人的链接。只有最后一个记录,创建由 Rick,显示编辑删除链接。其他用户不会看到的最后一个记录,直到经理或管理员的状态更改为"已批准"。

屏幕截图显示 Rick 登录

在下图中,manager@contoso.com 已登录,并在管理器的角色中:

屏幕截图显示manager@contoso.com登录

下图显示在管理器的联系人的详细信息视图:

联系人的经理的视图

批准拒绝按钮仅显示经理和管理员。

在下图中,admin@contoso.com 以管理员角色登录:

屏幕截图显示admin@contoso.com登录

管理员具有所有权限。她可以读取、 编辑或删除任何联系,并更改联系人的状态。

通过创建该应用基架以下Contact模型:

  1. public class Contact
  2. {
  3. public int ContactId { get; set; }
  4. public string Name { get; set; }
  5. public string Address { get; set; }
  6. public string City { get; set; }
  7. public string State { get; set; }
  8. public string Zip { get; set; }
  9. [DataType(DataType.EmailAddress)]
  10. public string Email { get; set; }
  11. }

此示例包含以下授权处理程序:

  • ContactIsOwnerAuthorizationHandler:确保用户只能编辑其数据。
  • ContactManagerAuthorizationHandler:允许经理批准或拒绝联系人。
  • ContactAdministratorsAuthorizationHandler:允许管理员批准或拒绝联系人以及编辑/删除联系人。

系统必备Prerequisites

本教程被高级。您应熟悉:

Starter 和已完成应用程序The starter and completed app

下载完成应用。测试已完成的应用,使你熟悉其安全功能。

入门级应用The starter app

下载初学者应用。

运行应用,点击ContactManager链接,并验证是否可以创建、 编辑和删除联系人。

保护用户数据Secure user data

以下部分介绍了所有主要的步骤以创建安全的用户数据应用程序。您可能会发现引用的已完成项目很有帮助。

将绑定到用户的联系人数据Tie the contact data to the user

使用 ASP.NET标识用户 ID,以确保用户可以编辑其数据,而不是其他用户数据。添加OwnerIDContactStatusContact模型:

  1. public class Contact
  2. {
  3. public int ContactId { get; set; }
  4. // user ID from AspNetUser table.
  5. public string OwnerID { get; set; }
  6. public string Name { get; set; }
  7. public string Address { get; set; }
  8. public string City { get; set; }
  9. public string State { get; set; }
  10. public string Zip { get; set; }
  11. [DataType(DataType.EmailAddress)]
  12. public string Email { get; set; }
  13. public ContactStatus Status { get; set; }
  14. }
  15. public enum ContactStatus
  16. {
  17. Submitted,
  18. Approved,
  19. Rejected
  20. }

OwnerID 是从用户的 IDAspNetUser表中标识数据库。Status字段确定是否可由普通用户查看联系人。

创建新的迁移并更新数据库:

  1. dotnet ef migrations add userID_Status
  2. dotnet ef database update

将角色服务添加到标识Add Role services to Identity

追加AddRoles添加角色服务:

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddDbContext<ApplicationDbContext>(options =>
  4. options.UseSqlServer(
  5. Configuration.GetConnectionString("DefaultConnection")));
  6. services.AddDefaultIdentity<IdentityUser>(
  7. options => options.SignIn.RequireConfirmedAccount = true)
  8. .AddRoles<IdentityRole>()
  9. .AddEntityFrameworkStores<ApplicationDbContext>();

需要身份验证的用户Require authenticated users

设置默认身份验证策略以要求用户进行身份验证:

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddDbContext<ApplicationDbContext>(options =>
  4. options.UseSqlServer(
  5. Configuration.GetConnectionString("DefaultConnection")));
  6. services.AddDefaultIdentity<IdentityUser>(
  7. options => options.SignIn.RequireConfirmedAccount = true)
  8. .AddRoles<IdentityRole>()
  9. .AddEntityFrameworkStores<ApplicationDbContext>();
  10. services.AddRazorPages();
  11. services.AddControllers(config =>
  12. {
  13. // using Microsoft.AspNetCore.Mvc.Authorization;
  14. // using Microsoft.AspNetCore.Authorization;
  15. var policy = new AuthorizationPolicyBuilder()
  16. .RequireAuthenticatedUser()
  17. .Build();
  18. config.Filters.Add(new AuthorizeFilter(policy));
  19. });

可以选择在 Razor 页面、 控制器或操作方法级别使用的身份验证禁用[AllowAnonymous]属性。设置默认身份验证策略以要求用户进行身份验证来保护新添加的 Razor 页面和控制器。默认情况下所需的身份验证是比依赖于新的控制器和 Razor 页,以包含更安全[Authorize]属性。

AllowAnonymous添加到 "索引" 和 "隐私" 页,以便匿名用户在注册之前可以获取有关站点的信息。

  1. using Microsoft.AspNetCore.Authorization;
  2. using Microsoft.AspNetCore.Mvc.RazorPages;
  3. using Microsoft.Extensions.Logging;
  4. namespace ContactManager.Pages
  5. {
  6. [AllowAnonymous]
  7. public class IndexModel : PageModel
  8. {
  9. private readonly ILogger<IndexModel> _logger;
  10. public IndexModel(ILogger<IndexModel> logger)
  11. {
  12. _logger = logger;
  13. }
  14. public void OnGet()
  15. {
  16. }
  17. }
  18. }

配置测试帐户Configure the test account

SeedData类创建两个帐户: 管理员和管理员。使用机密管理器工具设置这些帐户的密码。从项目目录中设置密码 (目录包含Program.cs):

  1. dotnet user-secrets set SeedUserPW <PW>

如果未指定强密码,将引发异常时SeedData.Initialize调用。

更新Main使用测试密码:

  1. public class Program
  2. {
  3. public static void Main(string[] args)
  4. {
  5. var host = CreateHostBuilder(args).Build();
  6. using (var scope = host.Services.CreateScope())
  7. {
  8. var services = scope.ServiceProvider;
  9. try
  10. {
  11. var context = services.GetRequiredService<ApplicationDbContext>();
  12. context.Database.Migrate();
  13. // requires using Microsoft.Extensions.Configuration;
  14. var config = host.Services.GetRequiredService<IConfiguration>();
  15. // Set password with the Secret Manager tool.
  16. // dotnet user-secrets set SeedUserPW <pw>
  17. var testUserPw = config["SeedUserPW"];
  18. SeedData.Initialize(services, testUserPw).Wait();
  19. }
  20. catch (Exception ex)
  21. {
  22. var logger = services.GetRequiredService<ILogger<Program>>();
  23. logger.LogError(ex, "An error occurred seeding the DB.");
  24. }
  25. }
  26. host.Run();
  27. }
  28. public static IHostBuilder CreateHostBuilder(string[] args) =>
  29. Host.CreateDefaultBuilder(args)
  30. .ConfigureWebHostDefaults(webBuilder =>
  31. {
  32. webBuilder.UseStartup<Startup>();
  33. });
  34. }

创建测试帐户和更新联系人Create the test accounts and update the contacts

更新Initialize中的方法SeedData类,以创建测试帐户:

  1. public static async Task Initialize(IServiceProvider serviceProvider, string testUserPw)
  2. {
  3. using (var context = new ApplicationDbContext(
  4. serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
  5. {
  6. // For sample purposes seed both with the same password.
  7. // Password is set with the following:
  8. // dotnet user-secrets set SeedUserPW <pw>
  9. // The admin user can do anything
  10. var adminID = await EnsureUser(serviceProvider, testUserPw, "admin@contoso.com");
  11. await EnsureRole(serviceProvider, adminID, Constants.ContactAdministratorsRole);
  12. // allowed user can create and edit contacts that they create
  13. var managerID = await EnsureUser(serviceProvider, testUserPw, "manager@contoso.com");
  14. await EnsureRole(serviceProvider, managerID, Constants.ContactManagersRole);
  15. SeedDB(context, adminID);
  16. }
  17. }
  18. private static async Task<string> EnsureUser(IServiceProvider serviceProvider,
  19. string testUserPw, string UserName)
  20. {
  21. var userManager = serviceProvider.GetService<UserManager<IdentityUser>>();
  22. var user = await userManager.FindByNameAsync(UserName);
  23. if (user == null)
  24. {
  25. user = new IdentityUser {
  26. UserName = UserName,
  27. EmailConfirmed = true
  28. };
  29. await userManager.CreateAsync(user, testUserPw);
  30. }
  31. if (user == null)
  32. {
  33. throw new Exception("The password is probably not strong enough!");
  34. }
  35. return user.Id;
  36. }
  37. private static async Task<IdentityResult> EnsureRole(IServiceProvider serviceProvider,
  38. string uid, string role)
  39. {
  40. IdentityResult IR = null;
  41. var roleManager = serviceProvider.GetService<RoleManager<IdentityRole>>();
  42. if (roleManager == null)
  43. {
  44. throw new Exception("roleManager null");
  45. }
  46. if (!await roleManager.RoleExistsAsync(role))
  47. {
  48. IR = await roleManager.CreateAsync(new IdentityRole(role));
  49. }
  50. var userManager = serviceProvider.GetService<UserManager<IdentityUser>>();
  51. var user = await userManager.FindByIdAsync(uid);
  52. if(user == null)
  53. {
  54. throw new Exception("The testUserPw password was probably not strong enough!");
  55. }
  56. IR = await userManager.AddToRoleAsync(user, role);
  57. return IR;
  58. }

添加管理员用户 ID 和ContactStatus到联系人。先创建一个"已提交"和一个"已拒绝"的联系人。将用户 ID 和状态添加到所有联系人。只能有一个联系人所示:

  1. public static void SeedDB(ApplicationDbContext context, string adminID)
  2. {
  3. if (context.Contact.Any())
  4. {
  5. return; // DB has been seeded
  6. }
  7. context.Contact.AddRange(
  8. new Contact
  9. {
  10. Name = "Debra Garcia",
  11. Address = "1234 Main St",
  12. City = "Redmond",
  13. State = "WA",
  14. Zip = "10999",
  15. Email = "debra@example.com",
  16. Status = ContactStatus.Approved,
  17. OwnerID = adminID
  18. },

创建所有者、 经理和管理员授权处理程序Create owner, manager, and administrator authorization handlers

创建ContactIsOwnerAuthorizationHandler类中授权文件夹。ContactIsOwnerAuthorizationHandler验证对资源进行操作的用户拥有的资源。

  1. using ContactManager.Models;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Authorization.Infrastructure;
  4. using Microsoft.AspNetCore.Identity;
  5. using System.Threading.Tasks;
  6. namespace ContactManager.Authorization
  7. {
  8. public class ContactIsOwnerAuthorizationHandler
  9. : AuthorizationHandler<OperationAuthorizationRequirement, Contact>
  10. {
  11. UserManager<IdentityUser> _userManager;
  12. public ContactIsOwnerAuthorizationHandler(UserManager<IdentityUser>
  13. userManager)
  14. {
  15. _userManager = userManager;
  16. }
  17. protected override Task
  18. HandleRequirementAsync(AuthorizationHandlerContext context,
  19. OperationAuthorizationRequirement requirement,
  20. Contact resource)
  21. {
  22. if (context.User == null || resource == null)
  23. {
  24. return Task.CompletedTask;
  25. }
  26. // If not asking for CRUD permission, return.
  27. if (requirement.Name != Constants.CreateOperationName &&
  28. requirement.Name != Constants.ReadOperationName &&
  29. requirement.Name != Constants.UpdateOperationName &&
  30. requirement.Name != Constants.DeleteOperationName )
  31. {
  32. return Task.CompletedTask;
  33. }
  34. if (resource.OwnerID == _userManager.GetUserId(context.User))
  35. {
  36. context.Succeed(requirement);
  37. }
  38. return Task.CompletedTask;
  39. }
  40. }
  41. }

ContactIsOwnerAuthorizationHandler调用上下文。成功当前经过身份验证的用户是否联系所有者。授权处理程序通常:

  • 返回context.Succeed满足的要求。
  • 返回Task.CompletedTask时不符合要求。Task.CompletedTask 不是成功或失败—它允许其他授权处理程序运行。

如果你需要将显式失败,返回上下文。失败

应用程序允许联系所有者到编辑/删除/创建他们自己的数据。ContactIsOwnerAuthorizationHandler 不需要检查要求参数中传递该操作。

创建管理器授权处理程序Create a manager authorization handler

创建ContactManagerAuthorizationHandler类中授权文件夹。ContactManagerAuthorizationHandler验证对资源进行操作的用户是管理员。只有经理们才可以批准或拒绝内容的更改 (新的或已更改)。

  1. using System.Threading.Tasks;
  2. using ContactManager.Models;
  3. using Microsoft.AspNetCore.Authorization;
  4. using Microsoft.AspNetCore.Authorization.Infrastructure;
  5. using Microsoft.AspNetCore.Identity;
  6. namespace ContactManager.Authorization
  7. {
  8. public class ContactManagerAuthorizationHandler :
  9. AuthorizationHandler<OperationAuthorizationRequirement, Contact>
  10. {
  11. protected override Task
  12. HandleRequirementAsync(AuthorizationHandlerContext context,
  13. OperationAuthorizationRequirement requirement,
  14. Contact resource)
  15. {
  16. if (context.User == null || resource == null)
  17. {
  18. return Task.CompletedTask;
  19. }
  20. // If not asking for approval/reject, return.
  21. if (requirement.Name != Constants.ApproveOperationName &&
  22. requirement.Name != Constants.RejectOperationName)
  23. {
  24. return Task.CompletedTask;
  25. }
  26. // Managers can approve or reject.
  27. if (context.User.IsInRole(Constants.ContactManagersRole))
  28. {
  29. context.Succeed(requirement);
  30. }
  31. return Task.CompletedTask;
  32. }
  33. }
  34. }

创建管理员授权处理程序Create an administrator authorization handler

创建ContactAdministratorsAuthorizationHandler类中授权文件夹。ContactAdministratorsAuthorizationHandler验证对资源进行操作的用户是管理员。管理员可以执行所有操作。

  1. using System.Threading.Tasks;
  2. using ContactManager.Models;
  3. using Microsoft.AspNetCore.Authorization;
  4. using Microsoft.AspNetCore.Authorization.Infrastructure;
  5. namespace ContactManager.Authorization
  6. {
  7. public class ContactAdministratorsAuthorizationHandler
  8. : AuthorizationHandler<OperationAuthorizationRequirement, Contact>
  9. {
  10. protected override Task HandleRequirementAsync(
  11. AuthorizationHandlerContext context,
  12. OperationAuthorizationRequirement requirement,
  13. Contact resource)
  14. {
  15. if (context.User == null)
  16. {
  17. return Task.CompletedTask;
  18. }
  19. // Administrators can do anything.
  20. if (context.User.IsInRole(Constants.ContactAdministratorsRole))
  21. {
  22. context.Succeed(requirement);
  23. }
  24. return Task.CompletedTask;
  25. }
  26. }
  27. }

注册授权处理程序Register the authorization handlers

Entity Framework Core 使用 AddScoped 的服务必须使用注册以进行依赖关系注入ContactIsOwnerAuthorizationHandler使用 ASP.NET Core标识,这基于实体框架核心。注册服务集合的处理程序,以便它们可供ContactsController通过依赖关系注入将以下代码添加到末尾ConfigureServices:

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddDbContext<ApplicationDbContext>(options =>
  4. options.UseSqlServer(
  5. Configuration.GetConnectionString("DefaultConnection")));
  6. services.AddDefaultIdentity<IdentityUser>(
  7. options => options.SignIn.RequireConfirmedAccount = true)
  8. .AddRoles<IdentityRole>()
  9. .AddEntityFrameworkStores<ApplicationDbContext>();
  10. services.AddRazorPages();
  11. services.AddControllers(config =>
  12. {
  13. // using Microsoft.AspNetCore.Mvc.Authorization;
  14. // using Microsoft.AspNetCore.Authorization;
  15. var policy = new AuthorizationPolicyBuilder()
  16. .RequireAuthenticatedUser()
  17. .Build();
  18. config.Filters.Add(new AuthorizeFilter(policy));
  19. });
  20. // Authorization handlers.
  21. services.AddScoped<IAuthorizationHandler,
  22. ContactIsOwnerAuthorizationHandler>();
  23. services.AddSingleton<IAuthorizationHandler,
  24. ContactAdministratorsAuthorizationHandler>();
  25. services.AddSingleton<IAuthorizationHandler,
  26. ContactManagerAuthorizationHandler>();
  27. }

ContactAdministratorsAuthorizationHandlerContactManagerAuthorizationHandler添加为单一实例。它们是单一实例,因为它们不使用 EF 和所需的所有信息都位于Context参数的HandleRequirementAsync方法。

支持授权Support authorization

在本部分中,将更新 Razor 页面和添加操作要求类。

查看联系人操作要求类Review the contact operations requirements class

查看ContactOperations类。此类包含要求应用支持:

  1. using Microsoft.AspNetCore.Authorization.Infrastructure;
  2. namespace ContactManager.Authorization
  3. {
  4. public static class ContactOperations
  5. {
  6. public static OperationAuthorizationRequirement Create =
  7. new OperationAuthorizationRequirement {Name=Constants.CreateOperationName};
  8. public static OperationAuthorizationRequirement Read =
  9. new OperationAuthorizationRequirement {Name=Constants.ReadOperationName};
  10. public static OperationAuthorizationRequirement Update =
  11. new OperationAuthorizationRequirement {Name=Constants.UpdateOperationName};
  12. public static OperationAuthorizationRequirement Delete =
  13. new OperationAuthorizationRequirement {Name=Constants.DeleteOperationName};
  14. public static OperationAuthorizationRequirement Approve =
  15. new OperationAuthorizationRequirement {Name=Constants.ApproveOperationName};
  16. public static OperationAuthorizationRequirement Reject =
  17. new OperationAuthorizationRequirement {Name=Constants.RejectOperationName};
  18. }
  19. public class Constants
  20. {
  21. public static readonly string CreateOperationName = "Create";
  22. public static readonly string ReadOperationName = "Read";
  23. public static readonly string UpdateOperationName = "Update";
  24. public static readonly string DeleteOperationName = "Delete";
  25. public static readonly string ApproveOperationName = "Approve";
  26. public static readonly string RejectOperationName = "Reject";
  27. public static readonly string ContactAdministratorsRole =
  28. "ContactAdministrators";
  29. public static readonly string ContactManagersRole = "ContactManagers";
  30. }
  31. }

创建联系人 Razor 页面的基类Create a base class for the Contacts Razor Pages

创建一个包含在联系人 Razor 页面使用的服务的基类。基类将初始化代码放在一个位置:

  1. using ContactManager.Data;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Identity;
  4. using Microsoft.AspNetCore.Mvc.RazorPages;
  5. namespace ContactManager.Pages.Contacts
  6. {
  7. public class DI_BasePageModel : PageModel
  8. {
  9. protected ApplicationDbContext Context { get; }
  10. protected IAuthorizationService AuthorizationService { get; }
  11. protected UserManager<IdentityUser> UserManager { get; }
  12. public DI_BasePageModel(
  13. ApplicationDbContext context,
  14. IAuthorizationService authorizationService,
  15. UserManager<IdentityUser> userManager) : base()
  16. {
  17. Context = context;
  18. UserManager = userManager;
  19. AuthorizationService = authorizationService;
  20. }
  21. }
  22. }

前面的代码:

  • 添加IAuthorizationService服务对授权处理程序的访问权限。
  • 将标识添加UserManager服务。
  • 添加 ApplicationDbContext

更新 CreateModelUpdate the CreateModel

更新创建页面模型构造函数以使用DI_BasePageModel基类:

  1. public class CreateModel : DI_BasePageModel
  2. {
  3. public CreateModel(
  4. ApplicationDbContext context,
  5. IAuthorizationService authorizationService,
  6. UserManager<IdentityUser> userManager)
  7. : base(context, authorizationService, userManager)
  8. {
  9. }

更新CreateModel.OnPostAsync方法:

  • 添加到的用户 IDContact模型。
  • 调用授权处理程序,以验证用户有权创建联系人。
  1. public async Task<IActionResult> OnPostAsync()
  2. {
  3. if (!ModelState.IsValid)
  4. {
  5. return Page();
  6. }
  7. Contact.OwnerID = UserManager.GetUserId(User);
  8. // requires using ContactManager.Authorization;
  9. var isAuthorized = await AuthorizationService.AuthorizeAsync(
  10. User, Contact,
  11. ContactOperations.Create);
  12. if (!isAuthorized.Succeeded)
  13. {
  14. return Forbid();
  15. }
  16. Context.Contact.Add(Contact);
  17. await Context.SaveChangesAsync();
  18. return RedirectToPage("./Index");
  19. }

更新 IndexModelUpdate the IndexModel

更新OnGetAsync方法,以便仅被批准的联系人显示为普通用户:

  1. public class IndexModel : DI_BasePageModel
  2. {
  3. public IndexModel(
  4. ApplicationDbContext context,
  5. IAuthorizationService authorizationService,
  6. UserManager<IdentityUser> userManager)
  7. : base(context, authorizationService, userManager)
  8. {
  9. }
  10. public IList<Contact> Contact { get; set; }
  11. public async Task OnGetAsync()
  12. {
  13. var contacts = from c in Context.Contact
  14. select c;
  15. var isAuthorized = User.IsInRole(Constants.ContactManagersRole) ||
  16. User.IsInRole(Constants.ContactAdministratorsRole);
  17. var currentUserId = UserManager.GetUserId(User);
  18. // Only approved contacts are shown UNLESS you're authorized to see them
  19. // or you are the owner.
  20. if (!isAuthorized)
  21. {
  22. contacts = contacts.Where(c => c.Status == ContactStatus.Approved
  23. || c.OwnerID == currentUserId);
  24. }
  25. Contact = await contacts.ToListAsync();
  26. }
  27. }

更新 EditModelUpdate the EditModel

添加授权处理程序以验证的用户拥有联系人。正在验证资源授权,因为[Authorize]属性不能满足。评估属性时,应用程序不具有对资源的访问。基于资源的授权必须是命令性。应用程序页面模型中加载或加载处理程序本身内获得资源的访问权限,则必须执行检查。您经常访问的资源,通过传入的资源键。

  1. public class EditModel : DI_BasePageModel
  2. {
  3. public EditModel(
  4. ApplicationDbContext context,
  5. IAuthorizationService authorizationService,
  6. UserManager<IdentityUser> userManager)
  7. : base(context, authorizationService, userManager)
  8. {
  9. }
  10. [BindProperty]
  11. public Contact Contact { get; set; }
  12. public async Task<IActionResult> OnGetAsync(int id)
  13. {
  14. Contact = await Context.Contact.FirstOrDefaultAsync(
  15. m => m.ContactId == id);
  16. if (Contact == null)
  17. {
  18. return NotFound();
  19. }
  20. var isAuthorized = await AuthorizationService.AuthorizeAsync(
  21. User, Contact,
  22. ContactOperations.Update);
  23. if (!isAuthorized.Succeeded)
  24. {
  25. return Forbid();
  26. }
  27. return Page();
  28. }
  29. public async Task<IActionResult> OnPostAsync(int id)
  30. {
  31. if (!ModelState.IsValid)
  32. {
  33. return Page();
  34. }
  35. // Fetch Contact from DB to get OwnerID.
  36. var contact = await Context
  37. .Contact.AsNoTracking()
  38. .FirstOrDefaultAsync(m => m.ContactId == id);
  39. if (contact == null)
  40. {
  41. return NotFound();
  42. }
  43. var isAuthorized = await AuthorizationService.AuthorizeAsync(
  44. User, contact,
  45. ContactOperations.Update);
  46. if (!isAuthorized.Succeeded)
  47. {
  48. return Forbid();
  49. }
  50. Contact.OwnerID = contact.OwnerID;
  51. Context.Attach(Contact).State = EntityState.Modified;
  52. if (Contact.Status == ContactStatus.Approved)
  53. {
  54. // If the contact is updated after approval,
  55. // and the user cannot approve,
  56. // set the status back to submitted so the update can be
  57. // checked and approved.
  58. var canApprove = await AuthorizationService.AuthorizeAsync(User,
  59. Contact,
  60. ContactOperations.Approve);
  61. if (!canApprove.Succeeded)
  62. {
  63. Contact.Status = ContactStatus.Submitted;
  64. }
  65. }
  66. await Context.SaveChangesAsync();
  67. return RedirectToPage("./Index");
  68. }
  69. }

更新 DeleteModelUpdate the DeleteModel

更新要使用授权处理程序来验证用户具有 delete 权限 contact 上的删除页面模型。

  1. public class DeleteModel : DI_BasePageModel
  2. {
  3. public DeleteModel(
  4. ApplicationDbContext context,
  5. IAuthorizationService authorizationService,
  6. UserManager<IdentityUser> userManager)
  7. : base(context, authorizationService, userManager)
  8. {
  9. }
  10. [BindProperty]
  11. public Contact Contact { get; set; }
  12. public async Task<IActionResult> OnGetAsync(int id)
  13. {
  14. Contact = await Context.Contact.FirstOrDefaultAsync(
  15. m => m.ContactId == id);
  16. if (Contact == null)
  17. {
  18. return NotFound();
  19. }
  20. var isAuthorized = await AuthorizationService.AuthorizeAsync(
  21. User, Contact,
  22. ContactOperations.Delete);
  23. if (!isAuthorized.Succeeded)
  24. {
  25. return Forbid();
  26. }
  27. return Page();
  28. }
  29. public async Task<IActionResult> OnPostAsync(int id)
  30. {
  31. var contact = await Context
  32. .Contact.AsNoTracking()
  33. .FirstOrDefaultAsync(m => m.ContactId == id);
  34. if (contact == null)
  35. {
  36. return NotFound();
  37. }
  38. var isAuthorized = await AuthorizationService.AuthorizeAsync(
  39. User, contact,
  40. ContactOperations.Delete);
  41. if (!isAuthorized.Succeeded)
  42. {
  43. return Forbid();
  44. }
  45. Context.Contact.Remove(contact);
  46. await Context.SaveChangesAsync();
  47. return RedirectToPage("./Index");
  48. }
  49. }

将授权服务注入到视图Inject the authorization service into the views

目前,此 UI 显示编辑和删除的用户无法修改的联系人的链接。

将授权服务注入Pages/_ViewImports cshtml文件,使其可供所有视图使用:

  1. @using Microsoft.AspNetCore.Identity
  2. @using ContactManager
  3. @using ContactManager.Data
  4. @namespace ContactManager.Pages
  5. @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
  6. @using ContactManager.Authorization;
  7. @using Microsoft.AspNetCore.Authorization
  8. @using ContactManager.Models
  9. @inject IAuthorizationService AuthorizationService

上述标记添加了多种using语句。

更新编辑删除中的链接Pages/Contacts/Index.cshtml以便仅在呈现具有适当权限的用户:

  1. @page
  2. @model ContactManager.Pages.Contacts.IndexModel
  3. @{
  4. ViewData["Title"] = "Index";
  5. }
  6. <h2>Index</h2>
  7. <p>
  8. <a asp-page="Create">Create New</a>
  9. </p>
  10. <table class="table">
  11. <thead>
  12. <tr>
  13. <th>
  14. @Html.DisplayNameFor(model => model.Contact[0].Name)
  15. </th>
  16. <th>
  17. @Html.DisplayNameFor(model => model.Contact[0].Address)
  18. </th>
  19. <th>
  20. @Html.DisplayNameFor(model => model.Contact[0].City)
  21. </th>
  22. <th>
  23. @Html.DisplayNameFor(model => model.Contact[0].State)
  24. </th>
  25. <th>
  26. @Html.DisplayNameFor(model => model.Contact[0].Zip)
  27. </th>
  28. <th>
  29. @Html.DisplayNameFor(model => model.Contact[0].Email)
  30. </th>
  31. <th>
  32. @Html.DisplayNameFor(model => model.Contact[0].Status)
  33. </th>
  34. <th></th>
  35. </tr>
  36. </thead>
  37. <tbody>
  38. @foreach (var item in Model.Contact)
  39. {
  40. <tr>
  41. <td>
  42. @Html.DisplayFor(modelItem => item.Name)
  43. </td>
  44. <td>
  45. @Html.DisplayFor(modelItem => item.Address)
  46. </td>
  47. <td>
  48. @Html.DisplayFor(modelItem => item.City)
  49. </td>
  50. <td>
  51. @Html.DisplayFor(modelItem => item.State)
  52. </td>
  53. <td>
  54. @Html.DisplayFor(modelItem => item.Zip)
  55. </td>
  56. <td>
  57. @Html.DisplayFor(modelItem => item.Email)
  58. </td>
  59. <td>
  60. @Html.DisplayFor(modelItem => item.Status)
  61. </td>
  62. <td>
  63. @if ((await AuthorizationService.AuthorizeAsync(
  64. User, item,
  65. ContactOperations.Update)).Succeeded)
  66. {
  67. <a asp-page="./Edit" asp-route-id="@item.ContactId">Edit</a>
  68. <text> | </text>
  69. }
  70. <a asp-page="./Details" asp-route-id="@item.ContactId">Details</a>
  71. @if ((await AuthorizationService.AuthorizeAsync(
  72. User, item,
  73. ContactOperations.Delete)).Succeeded)
  74. {
  75. <text> | </text>
  76. <a asp-page="./Delete" asp-route-id="@item.ContactId">Delete</a>
  77. }
  78. </td>
  79. </tr>
  80. }
  81. </tbody>
  82. </table>

警告

隐藏用户没有权限更改的数据中的链接不会保护应用。隐藏链接使应用更加友好的用户显示唯一有效的链接。用户可以 hack 生成的 Url 以调用编辑和删除操作上不拥有的数据。Razor 页面或控制器必须强制执行访问检查,以保护数据。

更新详细信息Update Details

更新的详细信息视图,使管理员可以批准或拒绝联系人:

  1. @*Precedng markup omitted for brevity.*@
  2. <dt>
  3. @Html.DisplayNameFor(model => model.Contact.Email)
  4. </dt>
  5. <dd>
  6. @Html.DisplayFor(model => model.Contact.Email)
  7. </dd>
  8. <dt>
  9. @Html.DisplayNameFor(model => model.Contact.Status)
  10. </dt>
  11. <dd>
  12. @Html.DisplayFor(model => model.Contact.Status)
  13. </dd>
  14. </dl>
  15. </div>
  16. @if (Model.Contact.Status != ContactStatus.Approved)
  17. {
  18. @if ((await AuthorizationService.AuthorizeAsync(
  19. User, Model.Contact, ContactOperations.Approve)).Succeeded)
  20. {
  21. <form style="display:inline;" method="post">
  22. <input type="hidden" name="id" value="@Model.Contact.ContactId" />
  23. <input type="hidden" name="status" value="@ContactStatus.Approved" />
  24. <button type="submit" class="btn btn-xs btn-success">Approve</button>
  25. </form>
  26. }
  27. }
  28. @if (Model.Contact.Status != ContactStatus.Rejected)
  29. {
  30. @if ((await AuthorizationService.AuthorizeAsync(
  31. User, Model.Contact, ContactOperations.Reject)).Succeeded)
  32. {
  33. <form style="display:inline;" method="post">
  34. <input type="hidden" name="id" value="@Model.Contact.ContactId" />
  35. <input type="hidden" name="status" value="@ContactStatus.Rejected" />
  36. <button type="submit" class="btn btn-xs btn-danger">Reject</button>
  37. </form>
  38. }
  39. }
  40. <div>
  41. @if ((await AuthorizationService.AuthorizeAsync(
  42. User, Model.Contact,
  43. ContactOperations.Update)).Succeeded)
  44. {
  45. <a asp-page="./Edit" asp-route-id="@Model.Contact.ContactId">Edit</a>
  46. <text> | </text>
  47. }
  48. <a asp-page="./Index">Back to List</a>
  49. </div>

更新详细信息页模型:

  1. public class DetailsModel : DI_BasePageModel
  2. {
  3. public DetailsModel(
  4. ApplicationDbContext context,
  5. IAuthorizationService authorizationService,
  6. UserManager<IdentityUser> userManager)
  7. : base(context, authorizationService, userManager)
  8. {
  9. }
  10. public Contact Contact { get; set; }
  11. public async Task<IActionResult> OnGetAsync(int id)
  12. {
  13. Contact = await Context.Contact.FirstOrDefaultAsync(m => m.ContactId == id);
  14. if (Contact == null)
  15. {
  16. return NotFound();
  17. }
  18. var isAuthorized = User.IsInRole(Constants.ContactManagersRole) ||
  19. User.IsInRole(Constants.ContactAdministratorsRole);
  20. var currentUserId = UserManager.GetUserId(User);
  21. if (!isAuthorized
  22. && currentUserId != Contact.OwnerID
  23. && Contact.Status != ContactStatus.Approved)
  24. {
  25. return Forbid();
  26. }
  27. return Page();
  28. }
  29. public async Task<IActionResult> OnPostAsync(int id, ContactStatus status)
  30. {
  31. var contact = await Context.Contact.FirstOrDefaultAsync(
  32. m => m.ContactId == id);
  33. if (contact == null)
  34. {
  35. return NotFound();
  36. }
  37. var contactOperation = (status == ContactStatus.Approved)
  38. ? ContactOperations.Approve
  39. : ContactOperations.Reject;
  40. var isAuthorized = await AuthorizationService.AuthorizeAsync(User, contact,
  41. contactOperation);
  42. if (!isAuthorized.Succeeded)
  43. {
  44. return Forbid();
  45. }
  46. contact.Status = status;
  47. Context.Contact.Update(contact);
  48. await Context.SaveChangesAsync();
  49. return RedirectToPage("./Index");
  50. }
  51. }

添加或删除角色对用户的Add or remove a user to a role

请参阅本期有关的信息:

  • 从用户删除的特权。例如,在聊天应用中对用户进行静音。
  • 将权限添加到用户。

质询和禁止之间的差异Differences between Challenge and Forbid

此应用将默认策略设置为 "需要经过身份验证的用户"。以下代码允许匿名用户。允许匿名用户显示质询与禁止之间的差异。

  1. [AllowAnonymous]
  2. public class Details2Model : DI_BasePageModel
  3. {
  4. public Details2Model(
  5. ApplicationDbContext context,
  6. IAuthorizationService authorizationService,
  7. UserManager<IdentityUser> userManager)
  8. : base(context, authorizationService, userManager)
  9. {
  10. }
  11. public Contact Contact { get; set; }
  12. public async Task<IActionResult> OnGetAsync(int id)
  13. {
  14. Contact = await Context.Contact.FirstOrDefaultAsync(m => m.ContactId == id);
  15. if (Contact == null)
  16. {
  17. return NotFound();
  18. }
  19. if (!User.Identity.IsAuthenticated)
  20. {
  21. return Challenge();
  22. }
  23. var isAuthorized = User.IsInRole(Constants.ContactManagersRole) ||
  24. User.IsInRole(Constants.ContactAdministratorsRole);
  25. var currentUserId = UserManager.GetUserId(User);
  26. if (!isAuthorized
  27. && currentUserId != Contact.OwnerID
  28. && Contact.Status != ContactStatus.Approved)
  29. {
  30. return Forbid();
  31. }
  32. return Page();
  33. }
  34. }

在上述代码中:

  • 如果用户未通过身份验证,将返回 ChallengeResult。返回 ChallengeResult 后,用户将重定向到登录页。
  • 如果用户已通过身份验证,但未获得授权,则返回 ForbidResult。返回 ForbidResult 后,用户将被重定向到 "拒绝访问" 页。

测试已完成的应用程序Test the completed app

如果你尚未设置设定为种子的用户帐户的密码,使用机密管理器工具设置密码:

  • 选择强密码:使用八个或更多字符,并且至少使用一个大写字符、数字和符号。例如,Passw0rd!符合强密码要求。

  • 执行以下命令从项目的文件夹,其中<PW>的密码:

  1. dotnet user-secrets set SeedUserPW <PW>

如果应用了联系人:

  • 删除所有记录中Contact表。
  • 重新启动应用以设定数据库种子。

测试已完成的应用程序的简单方法是启动三个不同的浏览器 (或 incognito/InPrivate 会话)。在一个浏览器中注册一个新用户 (例如, test@example.com)。登录到每个浏览器使用不同的用户。验证以下操作:

  • 已注册的用户可以查看所有已批准的联系人数据。
  • 已注册的用户可以编辑/删除其自己的数据。
  • 经理可以批准/拒绝的联系人数据。Details视图视图将显示批准拒绝按钮。
  • 管理员可以批准/拒绝和编辑/删除所有数据。
用户由应用程序进行种子设定选项
test@example.comNo编辑/删除自己的数据。
manager@contoso.com批准/拒绝和编辑/删除拥有的数据。
admin@contoso.com批准/拒绝和编辑/删除所有数据。

在管理员的浏览器中创建联系人。删除 URL 复制并编辑从管理员的联系信息。将下面的链接粘贴到测试用户的浏览器以验证测试用户不能执行这些操作。

创建入门级应用Create the starter app

  • 创建名为"ContactManager"Razor 页面应用

    • 创建包含应用单个用户帐户
    • 它命名为"ContactManager"使命名空间匹配的示例中使用的命名空间。
    • -uld 指定 LocalDB,而不是 SQLite
  1. dotnet new webapp -o ContactManager -au Individual -uld
  • 添加模型/联系方式
  1. public class Contact
  2. {
  3. public int ContactId { get; set; }
  4. public string Name { get; set; }
  5. public string Address { get; set; }
  6. public string City { get; set; }
  7. public string State { get; set; }
  8. public string Zip { get; set; }
  9. [DataType(DataType.EmailAddress)]
  10. public string Email { get; set; }
  11. }
  • 基架Contact模型。

  • 创建初始迁移并更新数据库:

  1. dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
  2. dotnet tool install -g dotnet-aspnet-codegenerator
  3. dotnet aspnet-codegenerator razorpage -m Contact -udl -dc ApplicationDbContext -outDir Pages\Contacts --referenceScriptLibraries
  4. dotnet ef database drop -f
  5. dotnet ef migrations add initial
  6. dotnet ef database update

如果使用 dotnet aspnet-codegenerator razorpage 命令时遇到 bug,请参阅此 GitHub 问题

  • 更新Pages/Shared/_Layout cshtml文件中的ContactManager定位点:
  1. <a class="navbar-brand" asp-area="" asp-page="/Contacts/Index">ContactManager</a>
  • 测试应用程序的创建、 编辑和删除联系人

设定数据库种子Seed the database

SeedData类添加到Data文件夹:

using ContactManager.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Threading.Tasks;

// dotnet aspnet-codegenerator razorpage -m Contact -dc ApplicationDbContext -udl -outDir Pages\Contacts --referenceScriptLibraries

namespace ContactManager.Data
{
    public static class SeedData
    {
        public static async Task Initialize(IServiceProvider serviceProvider, string testUserPw)
        {
            using (var context = new ApplicationDbContext(
                serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
            {              
                SeedDB(context, "0");
            }
        }        

        public static void SeedDB(ApplicationDbContext context, string adminID)
        {
            if (context.Contact.Any())
            {
                return;   // DB has been seeded
            }

            context.Contact.AddRange(
                new Contact
                {
                    Name = "Debra Garcia",
                    Address = "1234 Main St",
                    City = "Redmond",
                    State = "WA",
                    Zip = "10999",
                    Email = "debra@example.com"
                },
                new Contact
                {
                    Name = "Thorsten Weinrich",
                    Address = "5678 1st Ave W",
                    City = "Redmond",
                    State = "WA",
                    Zip = "10999",
                    Email = "thorsten@example.com"
                },
             new Contact
             {
                 Name = "Yuhong Li",
                 Address = "9012 State st",
                 City = "Redmond",
                 State = "WA",
                 Zip = "10999",
                 Email = "yuhong@example.com"
             },
             new Contact
             {
                 Name = "Jon Orton",
                 Address = "3456 Maple St",
                 City = "Redmond",
                 State = "WA",
                 Zip = "10999",
                 Email = "jon@example.com"
             },
             new Contact
             {
                 Name = "Diliana Alexieva-Bosseva",
                 Address = "7890 2nd Ave E",
                 City = "Redmond",
                 State = "WA",
                 Zip = "10999",
                 Email = "diliana@example.com"
             }
             );
            context.SaveChanges();
        }

    }
}

调用SeedData.InitializeMain:

using ContactManager.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;

namespace ContactManager
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.GetRequiredService<ApplicationDbContext>();
                    context.Database.Migrate();
                    SeedData.Initialize(services, "not used");
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

测试应用程序设定数据库种子。如果联系人 DB 中有任何行,则不会运行 seed 方法。

本教程演示如何使用受授权的用户数据创建 ASP.NET Core web 应用。它显示的身份验证 (注册) 的用户的联系人列表已创建。有三个安全组:

  • 注册用户可以查看所有已批准的数据还可以编辑/删除其自己的数据。
  • 管理器可以批准或拒绝的联系人数据。仅已批准的联系人是对用户可见。
  • 管理员可以批准/拒绝和编辑/删除的任何数据。

在下图中,用户 Rick (rick@example.com) 登录。Rick 只能查看允许的联系人和编辑/删除/新建其联系人的链接。只有最后一个记录,创建由 Rick,显示编辑删除链接。其他用户不会看到的最后一个记录,直到经理或管理员的状态更改为"已批准"。

屏幕截图显示 Rick 登录

在下图中,manager@contoso.com 已登录,并在管理器的角色中:

屏幕截图显示manager@contoso.com登录

下图显示在管理器的联系人的详细信息视图:

联系人的经理的视图

批准拒绝按钮仅显示经理和管理员。

在下图中,admin@contoso.com 以管理员角色登录:

屏幕截图显示admin@contoso.com登录

管理员具有所有权限。她可以读取、 编辑或删除任何联系,并更改联系人的状态。

通过创建该应用基架以下Contact模型:

public class Contact
{
    public int ContactId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
}

此示例包含以下授权处理程序:

  • ContactIsOwnerAuthorizationHandler:确保用户只能编辑其数据。
  • ContactManagerAuthorizationHandler:允许经理批准或拒绝联系人。
  • ContactAdministratorsAuthorizationHandler:允许管理员批准或拒绝联系人以及编辑/删除联系人。

系统必备Prerequisites

本教程被高级。您应熟悉:

Starter 和已完成应用程序The starter and completed app

下载完成应用。测试已完成的应用,使你熟悉其安全功能。

入门级应用The starter app

下载初学者应用。

运行应用,点击ContactManager链接,并验证是否可以创建、 编辑和删除联系人。

保护用户数据Secure user data

以下部分介绍了所有主要的步骤以创建安全的用户数据应用程序。您可能会发现引用的已完成项目很有帮助。

将绑定到用户的联系人数据Tie the contact data to the user

使用 ASP.NET标识用户 ID,以确保用户可以编辑其数据,而不是其他用户数据。添加OwnerIDContactStatusContact模型:

public class Contact
{
    public int ContactId { get; set; }

    // user ID from AspNetUser table.
    public string OwnerID { get; set; }

    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    public ContactStatus Status { get; set; }
}

public enum ContactStatus
{
    Submitted,
    Approved,
    Rejected
}

OwnerID 是从用户的 IDAspNetUser表中标识数据库。Status字段确定是否可由普通用户查看联系人。

创建新的迁移并更新数据库:

dotnet ef migrations add userID_Status
dotnet ef database update

将角色服务添加到标识Add Role services to Identity

追加AddRoles添加角色服务:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
         .AddEntityFrameworkStores<ApplicationDbContext>();

需要身份验证的用户Require authenticated users

设置默认身份验证策略以要求用户进行身份验证:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
         .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddMvc(config =>
    {
        // using Microsoft.AspNetCore.Mvc.Authorization;
        // using Microsoft.AspNetCore.Authorization;
        var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    })                
       .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

可以选择在 Razor 页面、 控制器或操作方法级别使用的身份验证禁用[AllowAnonymous]属性。设置默认身份验证策略以要求用户进行身份验证来保护新添加的 Razor 页面和控制器。默认情况下所需的身份验证是比依赖于新的控制器和 Razor 页,以包含更安全[Authorize]属性。

添加AllowAnonymous到索引中,因此匿名用户可以获取有关站点的信息注册有关,和联系人页面。

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace ContactManager.Pages
{
    [AllowAnonymous]
    public class IndexModel : PageModel
    {
        public void OnGet()
        {

        }
    }
}

配置测试帐户Configure the test account

SeedData类创建两个帐户: 管理员和管理员。使用机密管理器工具设置这些帐户的密码。从项目目录中设置密码 (目录包含Program.cs):

dotnet user-secrets set SeedUserPW <PW>

如果未指定强密码,将引发异常时SeedData.Initialize调用。

更新Main使用测试密码:

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            var context = services.GetRequiredService<ApplicationDbContext>();
            context.Database.Migrate();

            // requires using Microsoft.Extensions.Configuration;
            var config = host.Services.GetRequiredService<IConfiguration>();
            // Set password with the Secret Manager tool.
            // dotnet user-secrets set SeedUserPW <pw>

            var testUserPw = config["SeedUserPW"];
            try
            {
                SeedData.Initialize(services, testUserPw).Wait();
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex.Message, "An error occurred seeding the DB.");
            }
        }

        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

创建测试帐户和更新联系人Create the test accounts and update the contacts

更新Initialize中的方法SeedData类,以创建测试帐户:

public static async Task Initialize(IServiceProvider serviceProvider, string testUserPw)
{
    using (var context = new ApplicationDbContext(
        serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
    {
        // For sample purposes seed both with the same password.
        // Password is set with the following:
        // dotnet user-secrets set SeedUserPW <pw>
        // The admin user can do anything

        var adminID = await EnsureUser(serviceProvider, testUserPw, "admin@contoso.com");
        await EnsureRole(serviceProvider, adminID, Constants.ContactAdministratorsRole);

        // allowed user can create and edit contacts that they create
        var managerID = await EnsureUser(serviceProvider, testUserPw, "manager@contoso.com");
        await EnsureRole(serviceProvider, managerID, Constants.ContactManagersRole);

        SeedDB(context, adminID);
    }
}

private static async Task<string> EnsureUser(IServiceProvider serviceProvider,
                                            string testUserPw, string UserName)
{
    var userManager = serviceProvider.GetService<UserManager<IdentityUser>>();

    var user = await userManager.FindByNameAsync(UserName);
    if (user == null)
    {
        user = new IdentityUser { UserName = UserName };
        await userManager.CreateAsync(user, testUserPw);
    }

    return user.Id;
}

private static async Task<IdentityResult> EnsureRole(IServiceProvider serviceProvider,
                                                              string uid, string role)
{
    IdentityResult IR = null;
    var roleManager = serviceProvider.GetService<RoleManager<IdentityRole>>();

    if (roleManager == null)
    {
        throw new Exception("roleManager null");
    }

    if (!await roleManager.RoleExistsAsync(role))
    {
        IR = await roleManager.CreateAsync(new IdentityRole(role));
    }

    var userManager = serviceProvider.GetService<UserManager<IdentityUser>>();

    var user = await userManager.FindByIdAsync(uid);

    if(user == null)
    {
        throw new Exception("The testUserPw password was probably not strong enough!");
    }

    IR = await userManager.AddToRoleAsync(user, role);

    return IR;
}

添加管理员用户 ID 和ContactStatus到联系人。先创建一个"已提交"和一个"已拒绝"的联系人。将用户 ID 和状态添加到所有联系人。只能有一个联系人所示:

public static void SeedDB(ApplicationDbContext context, string adminID)
{
    if (context.Contact.Any())
    {
        return;   // DB has been seeded
    }

    context.Contact.AddRange(
        new Contact
        {
            Name = "Debra Garcia",
            Address = "1234 Main St",
            City = "Redmond",
            State = "WA",
            Zip = "10999",
            Email = "debra@example.com",
            Status = ContactStatus.Approved,
            OwnerID = adminID
        },

创建所有者、 经理和管理员授权处理程序Create owner, manager, and administrator authorization handlers

创建一个授权文件夹,并在其中创建一个 ContactIsOwnerAuthorizationHandler 类。ContactIsOwnerAuthorizationHandler验证对资源进行操作的用户拥有的资源。

using System.Threading.Tasks;
using ContactManager.Data;
using ContactManager.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Identity;

namespace ContactManager.Authorization
{
    public class ContactIsOwnerAuthorizationHandler
                : AuthorizationHandler<OperationAuthorizationRequirement, Contact>
    {
        UserManager<IdentityUser> _userManager;

        public ContactIsOwnerAuthorizationHandler(UserManager<IdentityUser> 
            userManager)
        {
            _userManager = userManager;
        }

        protected override Task
            HandleRequirementAsync(AuthorizationHandlerContext context,
                                   OperationAuthorizationRequirement requirement,
                                   Contact resource)
        {
            if (context.User == null || resource == null)
            {
                // Return Task.FromResult(0) if targeting a version of
                // .NET Framework older than 4.6:
                return Task.CompletedTask;
            }

            // If we're not asking for CRUD permission, return.

            if (requirement.Name != Constants.CreateOperationName &&
                requirement.Name != Constants.ReadOperationName   &&
                requirement.Name != Constants.UpdateOperationName &&
                requirement.Name != Constants.DeleteOperationName )
            {
                return Task.CompletedTask;
            }

            if (resource.OwnerID == _userManager.GetUserId(context.User))
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }
}

ContactIsOwnerAuthorizationHandler调用上下文。成功当前经过身份验证的用户是否联系所有者。授权处理程序通常:

  • 返回context.Succeed满足的要求。
  • 返回Task.CompletedTask时不符合要求。Task.CompletedTask 不是成功或失败—它允许其他授权处理程序运行。

如果你需要将显式失败,返回上下文。失败

应用程序允许联系所有者到编辑/删除/创建他们自己的数据。ContactIsOwnerAuthorizationHandler 不需要检查要求参数中传递该操作。

创建管理器授权处理程序Create a manager authorization handler

创建ContactManagerAuthorizationHandler类中授权文件夹。ContactManagerAuthorizationHandler验证对资源进行操作的用户是管理员。只有经理们才可以批准或拒绝内容的更改 (新的或已更改)。

using System.Threading.Tasks;
using ContactManager.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Identity;

namespace ContactManager.Authorization
{
    public class ContactManagerAuthorizationHandler :
        AuthorizationHandler<OperationAuthorizationRequirement, Contact>
    {
        protected override Task
            HandleRequirementAsync(AuthorizationHandlerContext context,
                                   OperationAuthorizationRequirement requirement,
                                   Contact resource)
        {
            if (context.User == null || resource == null)
            {
                return Task.CompletedTask;
            }

            // If not asking for approval/reject, return.
            if (requirement.Name != Constants.ApproveOperationName &&
                requirement.Name != Constants.RejectOperationName)
            {
                return Task.CompletedTask;
            }

            // Managers can approve or reject.
            if (context.User.IsInRole(Constants.ContactManagersRole))
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }
}

创建管理员授权处理程序Create an administrator authorization handler

创建ContactAdministratorsAuthorizationHandler类中授权文件夹。ContactAdministratorsAuthorizationHandler验证对资源进行操作的用户是管理员。管理员可以执行所有操作。

using System.Threading.Tasks;
using ContactManager.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;

namespace ContactManager.Authorization
{
    public class ContactAdministratorsAuthorizationHandler
                    : AuthorizationHandler<OperationAuthorizationRequirement, Contact>
    {
        protected override Task HandleRequirementAsync(
                                              AuthorizationHandlerContext context,
                                    OperationAuthorizationRequirement requirement, 
                                     Contact resource)
        {
            if (context.User == null)
            {
                return Task.CompletedTask;
            }

            // Administrators can do anything.
            if (context.User.IsInRole(Constants.ContactAdministratorsRole))
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }
}

注册授权处理程序Register the authorization handlers

Entity Framework Core 使用 AddScoped 的服务必须使用注册以进行依赖关系注入ContactIsOwnerAuthorizationHandler使用 ASP.NET Core标识,这基于实体框架核心。注册服务集合的处理程序,以便它们可供ContactsController通过依赖关系注入将以下代码添加到末尾ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
         .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddMvc(config =>
    {
        // using Microsoft.AspNetCore.Mvc.Authorization;
        // using Microsoft.AspNetCore.Authorization;
        var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    })                
       .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Authorization handlers.
    services.AddScoped<IAuthorizationHandler,
                          ContactIsOwnerAuthorizationHandler>();

    services.AddSingleton<IAuthorizationHandler,
                          ContactAdministratorsAuthorizationHandler>();

    services.AddSingleton<IAuthorizationHandler,
                          ContactManagerAuthorizationHandler>();
}

ContactAdministratorsAuthorizationHandlerContactManagerAuthorizationHandler添加为单一实例。它们是单一实例,因为它们不使用 EF 和所需的所有信息都位于Context参数的HandleRequirementAsync方法。

支持授权Support authorization

在本部分中,将更新 Razor 页面和添加操作要求类。

查看联系人操作要求类Review the contact operations requirements class

查看ContactOperations类。此类包含要求应用支持:

using Microsoft.AspNetCore.Authorization.Infrastructure;

namespace ContactManager.Authorization
{
    public static class ContactOperations
    {
        public static OperationAuthorizationRequirement Create =   
          new OperationAuthorizationRequirement {Name=Constants.CreateOperationName};
        public static OperationAuthorizationRequirement Read = 
          new OperationAuthorizationRequirement {Name=Constants.ReadOperationName};  
        public static OperationAuthorizationRequirement Update = 
          new OperationAuthorizationRequirement {Name=Constants.UpdateOperationName}; 
        public static OperationAuthorizationRequirement Delete = 
          new OperationAuthorizationRequirement {Name=Constants.DeleteOperationName};
        public static OperationAuthorizationRequirement Approve = 
          new OperationAuthorizationRequirement {Name=Constants.ApproveOperationName};
        public static OperationAuthorizationRequirement Reject = 
          new OperationAuthorizationRequirement {Name=Constants.RejectOperationName};
    }

    public class Constants
    {
        public static readonly string CreateOperationName = "Create";
        public static readonly string ReadOperationName = "Read";
        public static readonly string UpdateOperationName = "Update";
        public static readonly string DeleteOperationName = "Delete";
        public static readonly string ApproveOperationName = "Approve";
        public static readonly string RejectOperationName = "Reject";

        public static readonly string ContactAdministratorsRole = 
                                                              "ContactAdministrators";
        public static readonly string ContactManagersRole = "ContactManagers";
    }
}

创建联系人 Razor 页面的基类Create a base class for the Contacts Razor Pages

创建一个包含在联系人 Razor 页面使用的服务的基类。基类将初始化代码放在一个位置:

using ContactManager.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace ContactManager.Pages.Contacts
{
    public class DI_BasePageModel : PageModel
    {
        protected ApplicationDbContext Context { get; }
        protected IAuthorizationService AuthorizationService { get; }
        protected UserManager<IdentityUser> UserManager { get; }

        public DI_BasePageModel(
            ApplicationDbContext context,
            IAuthorizationService authorizationService,
            UserManager<IdentityUser> userManager) : base()
        {
            Context = context;
            UserManager = userManager;
            AuthorizationService = authorizationService;
        } 
    }
}

前面的代码:

  • 添加IAuthorizationService服务对授权处理程序的访问权限。
  • 将标识添加UserManager服务。
  • 添加 ApplicationDbContext

更新 CreateModelUpdate the CreateModel

更新创建页面模型构造函数以使用DI_BasePageModel基类:

public class CreateModel : DI_BasePageModel
{
    public CreateModel(
        ApplicationDbContext context,
        IAuthorizationService authorizationService,
        UserManager<IdentityUser> userManager)
        : base(context, authorizationService, userManager)
    {
    }

更新CreateModel.OnPostAsync方法:

  • 添加到的用户 IDContact模型。
  • 调用授权处理程序,以验证用户有权创建联系人。
public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    Contact.OwnerID = UserManager.GetUserId(User);

    // requires using ContactManager.Authorization;
    var isAuthorized = await AuthorizationService.AuthorizeAsync(
                                                User, Contact,
                                                ContactOperations.Create);
    if (!isAuthorized.Succeeded)
    {
        return new ChallengeResult();
    }

    Context.Contact.Add(Contact);
    await Context.SaveChangesAsync();

    return RedirectToPage("./Index");
}

更新 IndexModelUpdate the IndexModel

更新OnGetAsync方法,以便仅被批准的联系人显示为普通用户:

public class IndexModel : DI_BasePageModel
{
    public IndexModel(
        ApplicationDbContext context,
        IAuthorizationService authorizationService,
        UserManager<IdentityUser> userManager)
        : base(context, authorizationService, userManager)
    {
    }

    public IList<Contact> Contact { get; set; }

    public async Task OnGetAsync()
    {
        var contacts = from c in Context.Contact
                       select c;

        var isAuthorized = User.IsInRole(Constants.ContactManagersRole) ||
                           User.IsInRole(Constants.ContactAdministratorsRole);

        var currentUserId = UserManager.GetUserId(User);

        // Only approved contacts are shown UNLESS you're authorized to see them
        // or you are the owner.
        if (!isAuthorized)
        {
            contacts = contacts.Where(c => c.Status == ContactStatus.Approved
                                        || c.OwnerID == currentUserId);
        }

        Contact = await contacts.ToListAsync();
    }
}

更新 EditModelUpdate the EditModel

添加授权处理程序以验证的用户拥有联系人。正在验证资源授权,因为[Authorize]属性不能满足。评估属性时,应用程序不具有对资源的访问。基于资源的授权必须是命令性。应用程序页面模型中加载或加载处理程序本身内获得资源的访问权限,则必须执行检查。您经常访问的资源,通过传入的资源键。

public class EditModel : DI_BasePageModel
{
    public EditModel(
        ApplicationDbContext context,
        IAuthorizationService authorizationService,
        UserManager<IdentityUser> userManager)
        : base(context, authorizationService, userManager)
    {
    }

    [BindProperty]
    public Contact Contact { get; set; }

    public async Task<IActionResult> OnGetAsync(int id)
    {
        Contact = await Context.Contact.FirstOrDefaultAsync(
                                             m => m.ContactId == id);

        if (Contact == null)
        {
            return NotFound();
        }

        var isAuthorized = await AuthorizationService.AuthorizeAsync(
                                                  User, Contact,
                                                  ContactOperations.Update);
        if (!isAuthorized.Succeeded)
        {
            return new ChallengeResult();
        }

        return Page();
    }

    public async Task<IActionResult> OnPostAsync(int id)
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        // Fetch Contact from DB to get OwnerID.
        var contact = await Context
            .Contact.AsNoTracking()
            .FirstOrDefaultAsync(m => m.ContactId == id);

        if (contact == null)
        {
            return NotFound();
        }

        var isAuthorized = await AuthorizationService.AuthorizeAsync(
                                                 User, contact,
                                                 ContactOperations.Update);
        if (!isAuthorized.Succeeded)
        {
            return new ChallengeResult();
        }

        Contact.OwnerID = contact.OwnerID;

        Context.Attach(Contact).State = EntityState.Modified;

        if (contact.Status == ContactStatus.Approved)
        {
            // If the contact is updated after approval, 
            // and the user cannot approve,
            // set the status back to submitted so the update can be
            // checked and approved.
            var canApprove = await AuthorizationService.AuthorizeAsync(User,
                                    contact,
                                    ContactOperations.Approve);

            if (!canApprove.Succeeded)
            {
                contact.Status = ContactStatus.Submitted;
            }
        }

        await Context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }

    private bool ContactExists(int id)
    {
        return Context.Contact.Any(e => e.ContactId == id);
    }
}

更新 DeleteModelUpdate the DeleteModel

更新要使用授权处理程序来验证用户具有 delete 权限 contact 上的删除页面模型。

public class DeleteModel : DI_BasePageModel
{
    public DeleteModel(
        ApplicationDbContext context,
        IAuthorizationService authorizationService,
        UserManager<IdentityUser> userManager)
        : base(context, authorizationService, userManager)
    {
    }

    [BindProperty]
    public Contact Contact { get; set; }

    public async Task<IActionResult> OnGetAsync(int id)
    {
        Contact = await Context.Contact.FirstOrDefaultAsync(
                                             m => m.ContactId == id);

        if (Contact == null)
        {
            return NotFound();
        }

        var isAuthorized = await AuthorizationService.AuthorizeAsync(
                                                 User, Contact,
                                                 ContactOperations.Delete);
        if (!isAuthorized.Succeeded)
        {
            return new ChallengeResult();
        }

        return Page();
    }

    public async Task<IActionResult> OnPostAsync(int id)
    {
        Contact = await Context.Contact.FindAsync(id);

        var contact = await Context
            .Contact.AsNoTracking()
            .FirstOrDefaultAsync(m => m.ContactId == id);

        if (contact == null)
        {
            return NotFound();
        }

        var isAuthorized = await AuthorizationService.AuthorizeAsync(
                                                 User, contact,
                                                 ContactOperations.Delete);
        if (!isAuthorized.Succeeded)
        {
            return new ChallengeResult();
        }

        Context.Contact.Remove(Contact);
        await Context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }
}

将授权服务注入到视图Inject the authorization service into the views

目前,此 UI 显示编辑和删除的用户无法修改的联系人的链接。

注入中的授权服务views/_viewimports.cshtml文件,以便它可供所有视图:

@using Microsoft.AspNetCore.Identity
@using ContactManager
@using ContactManager.Data
@namespace ContactManager.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using ContactManager.Authorization;
@using Microsoft.AspNetCore.Authorization
@using ContactManager.Models
@inject IAuthorizationService AuthorizationService

上述标记添加了多种using语句。

更新编辑删除中的链接Pages/Contacts/Index.cshtml以便仅在呈现具有适当权限的用户:

@page
@model ContactManager.Pages.Contacts.IndexModel

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-page="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Contact[0].Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Contact[0].Address)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Contact[0].City)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Contact[0].State)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Contact[0].Zip)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Contact[0].Email)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Contact[0].Status)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.Contact)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Address)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.City)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.State)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Zip)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Email)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Status)
                </td>
                <td>
                    @if ((await AuthorizationService.AuthorizeAsync(
                     User, item,
                     ContactOperations.Update)).Succeeded)
                    {
                        <a asp-page="./Edit" asp-route-id="@item.ContactId">Edit</a>
                        <text> | </text>
                    }

                    <a asp-page="./Details" asp-route-id="@item.ContactId">Details</a>

                    @if ((await AuthorizationService.AuthorizeAsync(
                     User, item,
                     ContactOperations.Delete)).Succeeded)
                    {
                        <text> | </text>
                        <a asp-page="./Delete" asp-route-id="@item.ContactId">Delete</a>
                    }
                </td>
            </tr>
        }
    </tbody>
</table>

警告

隐藏用户没有权限更改的数据中的链接不会保护应用。隐藏链接使应用更加友好的用户显示唯一有效的链接。用户可以 hack 生成的 Url 以调用编辑和删除操作上不拥有的数据。Razor 页面或控制器必须强制执行访问检查,以保护数据。

更新详细信息Update Details

更新的详细信息视图,使管理员可以批准或拒绝联系人:

        @*Precedng markup omitted for brevity.*@
        <dt>
            @Html.DisplayNameFor(model => model.Contact.Email)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Contact.Email)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Contact.Status)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Contact.Status)
        </dd>
    </dl>
</div>

@if (Model.Contact.Status != ContactStatus.Approved)
{
    @if ((await AuthorizationService.AuthorizeAsync(
     User, Model.Contact, ContactOperations.Approve)).Succeeded)
    {
        <form style="display:inline;" method="post">
            <input type="hidden" name="id" value="@Model.Contact.ContactId" />
            <input type="hidden" name="status" value="@ContactStatus.Approved" />
            <button type="submit" class="btn btn-xs btn-success">Approve</button>
        </form>
    }
}

@if (Model.Contact.Status != ContactStatus.Rejected)
{
    @if ((await AuthorizationService.AuthorizeAsync(
     User, Model.Contact, ContactOperations.Reject)).Succeeded)
    {
        <form style="display:inline;" method="post">
            <input type="hidden" name="id" value="@Model.Contact.ContactId" />
            <input type="hidden" name="status" value="@ContactStatus.Rejected" />
            <button type="submit" class="btn btn-xs btn-success">Reject</button>
        </form>
    }
}

<div>
    @if ((await AuthorizationService.AuthorizeAsync(
         User, Model.Contact,
         ContactOperations.Update)).Succeeded)
    {
        <a asp-page="./Edit" asp-route-id="@Model.Contact.ContactId">Edit</a>
        <text> | </text>
    }
    <a asp-page="./Index">Back to List</a>
</div>

更新详细信息页模型:

public class DetailsModel : DI_BasePageModel
{
    public DetailsModel(
        ApplicationDbContext context,
        IAuthorizationService authorizationService,
        UserManager<IdentityUser> userManager)
        : base(context, authorizationService, userManager)
    {
    }

    public Contact Contact { get; set; }

    public async Task<IActionResult> OnGetAsync(int id)
    {
        Contact = await Context.Contact.FirstOrDefaultAsync(m => m.ContactId == id);

        if (Contact == null)
        {
            return NotFound();
        }

        var isAuthorized = User.IsInRole(Constants.ContactManagersRole) ||
                           User.IsInRole(Constants.ContactAdministratorsRole);

        var currentUserId = UserManager.GetUserId(User);

        if (!isAuthorized 
            &&  currentUserId != Contact.OwnerID
            && Contact.Status != ContactStatus.Approved) 
        {
            return new ChallengeResult();
        }

        return Page();
    }

    public async Task<IActionResult> OnPostAsync(int id, ContactStatus status)
    {
        var contact = await Context.Contact.FirstOrDefaultAsync(
                                                  m => m.ContactId == id);

        if (contact == null)
        {
            return NotFound();
        }

        var contactOperation = (status == ContactStatus.Approved)
                                                   ? ContactOperations.Approve
                                                   : ContactOperations.Reject;

        var isAuthorized = await AuthorizationService.AuthorizeAsync(User, contact,
                                    contactOperation);
        if (!isAuthorized.Succeeded)
        {
            return new ChallengeResult();
        }
        contact.Status = status;
        Context.Contact.Update(contact);
        await Context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }
}

添加或删除角色对用户的Add or remove a user to a role

请参阅本期有关的信息:

  • 从用户删除的特权。例如,在聊天应用中对用户进行静音。
  • 将权限添加到用户。

测试已完成的应用程序Test the completed app

如果你尚未设置设定为种子的用户帐户的密码,使用机密管理器工具设置密码:

  • 选择强密码:使用八个或更多字符,并且至少使用一个大写字符、数字和符号。例如,Passw0rd!符合强密码要求。

  • 执行以下命令从项目的文件夹,其中<PW>的密码:

dotnet user-secrets set SeedUserPW <PW>
  • 删除和更新数据库
dotnet ef database drop -f
dotnet ef database update  
  • 重新启动应用以设定数据库种子。

测试已完成的应用程序的简单方法是启动三个不同的浏览器 (或 incognito/InPrivate 会话)。在一个浏览器中注册一个新用户 (例如, test@example.com)。登录到每个浏览器使用不同的用户。验证以下操作:

  • 已注册的用户可以查看所有已批准的联系人数据。
  • 已注册的用户可以编辑/删除其自己的数据。
  • 经理可以批准/拒绝的联系人数据。Details视图视图将显示批准拒绝按钮。
  • 管理员可以批准/拒绝和编辑/删除所有数据。
用户由应用程序进行种子设定选项
test@example.comNo编辑/删除自己的数据。
manager@contoso.com批准/拒绝和编辑/删除拥有的数据。
admin@contoso.com批准/拒绝和编辑/删除所有数据。

在管理员的浏览器中创建联系人。删除 URL 复制并编辑从管理员的联系信息。将下面的链接粘贴到测试用户的浏览器以验证测试用户不能执行这些操作。

创建入门级应用Create the starter app

  • 创建名为"ContactManager"Razor 页面应用

    • 创建包含应用单个用户帐户
    • 它命名为"ContactManager"使命名空间匹配的示例中使用的命名空间。
    • -uld 指定 LocalDB,而不是 SQLite
dotnet new webapp -o ContactManager -au Individual -uld
  • 添加模型/联系方式
public class Contact
{
    public int ContactId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
}
  • 基架Contact模型。

  • 创建初始迁移并更新数据库:

dotnet aspnet-codegenerator razorpage -m Contact -udl -dc ApplicationDbContext -outDir Pages\Contacts --referenceScriptLibraries
dotnet ef database drop -f
dotnet ef migrations add initial
dotnet ef database update
  • 更新ContactManager中的定位点pages/_layout.cshtml文件:
<a asp-page="/Contacts/Index" class="navbar-brand">ContactManager</a>
  • 测试应用程序的创建、 编辑和删除联系人

设定数据库种子Seed the database

添加SeedData类来数据文件夹。

调用SeedData.InitializeMain:

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;

            try
            {
                var context = services.GetRequiredService<ApplicationDbContext>();
                context.Database.Migrate();
                SeedData.Initialize(services, "not used");
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred seeding the DB.");
            }
        }

        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

测试应用程序设定数据库种子。如果联系人 DB 中有任何行,则不会运行 seed 方法。

其他资源Additional resources