参考这位大神的博客:https://www.cnblogs.com/fonour/p/5848933.html,实现了简单的RBAC权限管理系统,但文章没有提到对权限的过滤,直接输入url还是可以访问未授权功能,在这刚学过滤器,简单实现如下:
1. 首先根据他写博客里的MenuAppService,写一个函数根据用户获取所有菜单和按钮:
/// <summary>
/// 根据用户获取功能菜单
/// </summary>
/// <param name="userId">用户ID</param>
/// <returns></returns>
public List<MenuDto> GetFunctsByUser(Guid userId)
{
List<MenuDto> result = new List<MenuDto>();
var allMenus = _menuRepository.GetAllList().OrderBy(it => it.SerialNumber);
if (userId == Guid.Empty) //超级管理员
return Mapper.Map<List<MenuDto>>(allMenus);
var user = _userRepository.GetWithRoles(userId);
if (user == null)
return result;
var userRoles = user.UserRoles;
List<Guid> menuIds = new List<Guid>();
foreach (var role in userRoles)
{
menuIds = menuIds.Union(_roleRepository.GetAllMenuListByRole(role.RoleId)).ToList();
}
allMenus = allMenus.Where(it => menuIds.Contains(it.Id)).OrderBy(it => it.SerialNumber);
return Mapper.Map<List<MenuDto>>(allMenus);
}
2. 写一个ActionFilter,根据当前路由数据和当前用户id,判断权限:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RBACCore.Application.MenuApp;
using RBACCore.Utility;
namespace RBACCore.MVC.Filters
{
public class PermissionFilter : IActionFilter
{
private readonly IMenuAppService menuService;
public PermissionFilter(IMenuAppService menuAppService)
{
menuService = menuAppService;
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
//获取当前用户
byte[] result;
context.HttpContext.Session.TryGetValue("CurrentUser", out result);
//如果用户不存在,调到登录页
if (result == null)
{
context.Result = new RedirectResult("/Login/Index");
return;
}
else
{
//获取当前area,controller,action名称
var routedata = context.RouteData;
var areaName = routedata.Values["area"];
var controllerName = routedata.Values["controller"].ToString();
var actionName = routedata.Values["action"].ToString();
var curruser = ByteConvertHelper.Bytes2Object<Domain.Entities.User>(result);
var allmenus = menuService.GetFunctsByUser(curruser.Id);
if (curruser == null)
{
context.Result = new RedirectResult("/Login/Index");
return;
}
bool authoried = false;
foreach (var item in allmenus)
{
var controllerIndex = item.Url.ToLower().IndexOf(controllerName.ToLower());
var actionIndex = item.Url.ToLower().IndexOf(actionName.ToLower());
if (areaName == null)
{
if (controllerName == "Home")
{
return;
}
if (controllerIndex > -1 && actionIndex > -1 && actionIndex > controllerIndex)
{
authoried = true;
return;
}
}
else
{
var areaIndex = item.Url.IndexOf(areaName.ToString().ToLower());
if (controllerIndex > -1 && actionIndex > -1 && areaIndex > -1 && actionIndex > controllerIndex && controllerIndex > actionIndex)
{
authoried = true;
return;
}
}
}
if (authoried == false)
{
context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
return;
}
}
}
}
}
3. 由于上面定义的过滤器需要服务注入,所以不能像特性那样直接写在BaseController头上,而是利用TypeFilter
[TypeFilter(typeof(PermissionFilter))]
public abstract class AlexBaseController : Controller
{
/// <summary>
/// 获取服务端验证的第一条错误信息
/// </summary>
/// <returns></returns>
public string GetModelStateError()
{
foreach (var item in ModelState.Values)
{
if (item.Errors.Count > 0)
{
return item.Errors[0].ErrorMessage;
}
}
return "";
}
}
4. 在页面中定义权限,安装area/controller/action默认路由形式,定义功能权限。这里有限制,使用的默认路由,以后再改。