Visual
一句话的事儿
- 在User的基础进行分类,
- 对角色进行CRUD(增加,删除,更新,查询)
Role Manager
- 创建,删除 Role
- 把用户添加到 Role
- 对 Role 进行授权
[Authorize(Roles = "xxxRle")]
要启用默认的 IdentityRole,在 Startup 里面配置时就不能使用 AddDefaultIdentity 了。需要使用 AddIdentity 并指定 User 和 Role:
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireNonAlphanumeric = false;
...
})
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
Role Controller
通过注入的 UserManager 和 RoleManager 操作角色。
单独操作 Role 的代码和 UserController 相似,主要不同在于修改 User 的 Role:
using Heavy.Web.Models;
using Heavy.Web.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Heavy.Web.Controllers
{
[Authorize]
public class RoleController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public RoleController(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
/// <summary>
/// 获取所有角色
/// </summary>
/// <returns></returns>
public async Task<IActionResult> Index()
{
var roles = await _roleManager.Roles.ToListAsync();
return View(roles);
}
public IActionResult AddRole()
{
return View();
}
/// <summary>
/// 增加一个角色
/// </summary>
/// <param name="roleAddViewModel">新增角色的UI</param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> AddRole(RoleAddViewModel roleAddViewModel)
{
if (!ModelState.IsValid)
{
return View(roleAddViewModel);
}
var role = new IdentityRole { Name = roleAddViewModel.RoleName };
var result = await _roleManager.CreateAsync(role);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return View(roleAddViewModel);
}
/// <summary>
/// 编辑角色[HttpGet]
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<IActionResult> EditRole(string id)
{
var role = await _roleManager.FindByIdAsync(id);
if (role == null)
{
return RedirectToAction("Index");
}
var roleEditViewModel = new RoleEditViewModel
{
Id = id,
RoleName = role.Name,
Users = new List<string>()
};
var users = await _userManager.Users.ToListAsync();
foreach (var user in users)
{
if (await _userManager.IsInRoleAsync(user, role.Name))
{
roleEditViewModel.Users.Add(user.UserName);
}
}
return View(roleEditViewModel);
}
/// <summary>
/// 编辑角色[HttpPost]
/// </summary>
/// <param name="roleEditViewModel"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> EditRole(RoleEditViewModel roleEditViewModel)
{
var role = await _roleManager.FindByIdAsync(roleEditViewModel.Id);
if (role != null)
{
role.Name = roleEditViewModel.RoleName;
var result = await _roleManager.UpdateAsync(role);
if (result.Succeeded)
{
RedirectToAction("Index");
}
ModelState.AddModelError(string.Empty, "更新角色时发生错误。");
return View(roleEditViewModel);
}
return RedirectToAction("Index");
}
/// <summary>
/// 删除某一角色
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<IActionResult> DeleteRole(string id)
{
var role = await _roleManager.FindByNameAsync(id);
if (role != null)
{
var result = await _roleManager.DeleteAsync(role);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
ModelState.AddModelError(string.Empty, "删除角色发生错误");
}
ModelState.AddModelError(string.Empty, "未找到对应的角色");
return View("Index", await _roleManager.Roles.ToListAsync());
}
/// <summary>
/// 在角色中添加一个用户[HttpGet]
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public async Task<IActionResult> AddUserToRole(string roleId)
{
var role = await _roleManager.FindByIdAsync(roleId);
if (role == null)
{
return RedirectToAction("Index");
}
var vm = new UserRoleViewModel { RoleId = role.Id };
var users = await _userManager.Users.ToListAsync();
//添加的用户不在这个角色中
foreach (var user in users)
{
if (!await _userManager.IsInRoleAsync(user, role.Name))
{
vm.Users.Add(user);
}
}
return View(vm);
}
/// <summary>
/// 在角色中添加一名用户[HttpPost]
/// </summary>
/// <param name="userRoleViewModel"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> AddUserToRole(UserRoleViewModel userRoleViewModel)
{
var user = await _userManager.FindByIdAsync(userRoleViewModel.UserId);
var role = await _roleManager.FindByIdAsync(userRoleViewModel.RoleId);
if (user != null && role != null)
{
var result = await _userManager.AddToRoleAsync(user, role.Name);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return View(userRoleViewModel);
}
ModelState.AddModelError(string.Empty, "用户或角色没有找到");
return View(userRoleViewModel);
}
/// <summary>
/// 从角色中删除某一用户[HttpGet]
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public async Task<IActionResult> DeleteUserFromRole(string roleId)
{
var role = await _roleManager.FindByIdAsync(roleId);
if (role == null)
{
return RedirectToAction("Index");
}
var vm = new UserRoleViewModel
{
RoleId = role.Id
};
var users = await _userManager.Users.ToListAsync();
foreach (var user in users)
{
if (await _userManager.IsInRoleAsync(user, role.Name))
{
vm.Users.Add(user);
}
}
return View(vm);
}
/// <summary>
/// 从角色中删除某一用户[HttpPost]
/// </summary>
/// <param name="userRoleViewModel"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> DeleteUserFromRole(UserRoleViewModel userRoleViewModel)
{
var user = await _userManager.FindByIdAsync(userRoleViewModel.UserId);
var role = await _roleManager.FindByIdAsync(userRoleViewModel.RoleId);
if (user != null && role != null)
{
if (await _userManager.IsInRoleAsync(user, role.Name))
{
var result = await _userManager.RemoveFromRoleAsync(user, role.Name);
if (result.Succeeded)
{
return RedirectToAction("EditRole", new { id = role.Id });
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return View(userRoleViewModel);
}
ModelState.AddModelError(string.Empty, "用户不在角色里");
return View(userRoleViewModel);
}
ModelState.AddModelError(string.Empty, "用户或角色未找到");
return View(userRoleViewModel);
}
}
}
对RoleManager的客制化
首先查看源代码,其目的在于查看哪些是现成的,然后决定要客制化哪些新的属性
using System;
namespace Microsoft.AspNetCore.Identity
{
//
// Summary:
// Represents a role in the identity system
//
// Type parameters:
// TKey:
// The type used for the primary key for the role.
public class IdentityRole<TKey> where TKey : IEquatable<TKey>
{
//
// Summary:
// Initializes a new instance of Microsoft.AspNetCore.Identity.IdentityRole`1.
public IdentityRole();
//
// Summary:
// Initializes a new instance of Microsoft.AspNetCore.Identity.IdentityRole`1.
//
// Parameters:
// roleName:
// The role name.
public IdentityRole(string roleName);
//
// Summary:
// Gets or sets the primary key for this role.
public virtual TKey Id { get; set; }
//
// Summary:
// Gets or sets the name for this role.
public virtual string Name { get; set; }
//
// Summary:
// Gets or sets the normalized name for this role.
public virtual string NormalizedName { get; set; }
//
// Summary:
// A random value that should change whenever a role is persisted to the store
public virtual string ConcurrencyStamp { get; set; }
//
// Summary:
// Returns the name of the role.
//
// Returns:
// The name of the role.
public override string ToString();
}
}
牛刀小试,客制化一个超级管理员角色
using Microsoft.AspNetCore.Identity;
namespace Heavy.Web.Models
{
public class ApplicationRole : IdentityRole
{
public string SuperAdminstartor { get; set; }
}
}
测试案例
测试00.测试[Authorize(Roles =”Administrators”)]
- 首先验证用户Felix@126.com在不是管理员的情况,能否访问用户管理
- 添加用户管理
添加Administrator
- 验证成功
:::info Tips:若不成功,请LogOut! :::