大、小项目都要设计权限,都想设计一个通用的权限,把权限做的比较复杂,现在了解了ABP的设计思路,觉得设计很简单,但实现方法与思路耐人寻味。
本篇只介绍AbpPermissions的数据库设计,其它表结构参考源代码即可[Name(资源文件唯一Id)]、[IsGranted(是否授权)]、[RoleId、UserId(授权于角色或用户)]
ABP所有常量数据,都是程序启动时通过 AbpKernelModule 一次性加载完成,用的时候直接从内存中读取即可
public override void PostInitialize() { RegisterMissingComponents(); IocManager.Resolve<LocalizationManager>().Initialize(); //初始化资源文件 IocManager.Resolve<NavigationManager>().Initialize(); //初始化导航权限 IocManager.Resolve<PermissionManager>().Initialize(); //初始化操作权限 IocManager.Resolve<SettingDefinitionManager>().Initialize(); }
权限分为前台权限判断和后台权限判断两种情况JS判断权限是通过引用 <script src="~/AbpScripts/GetScripts" type="text/javascript"></script> 这个脚本,把相关JS对象与方法加载到JS文件
上图中有两个红框,是后台构建的两个导航,MainMenu是系统默认的属性,Test是自定义属性,如下代码
public class ModuleZeroSampleProjectNavigationProvider : NavigationProvider { public override void SetNavigation(INavigationProviderContext context) { SetNavigation1(context); SetTestNavigation(context); } private void SetNavigation1(INavigationProviderContext context) { context.Manager.MainMenu //默认导航属性 .AddItem( new MenuItemDefinition( "Questions", new LocalizableString("Questions", ModuleZeroSampleProjectConsts.LocalizationSourceName), url: "#/questions", icon: "fa fa-question", requiredPermissionName: "Questions" //根据变量进行权限判断 ) ).AddItem( new MenuItemDefinition( "Users", new LocalizableString("Users", ModuleZeroSampleProjectConsts.LocalizationSourceName), url: "#/users", icon: "fa fa-users" ) ); } public const string TestName = "Test"; //自定义导航属性 private void SetTestNavigation(INavigationProviderContext context) { var testMenu = new MenuDefinition(TestName, new FixedLocalizableString("Frontend menu")); context.Manager.Menus[TestName] = testMenu; testMenu .AddItem( new MenuItemDefinition( "Questions", new LocalizableString("Questions", ModuleZeroSampleProjectConsts.LocalizationSourceName), url: "#/questions", icon: "fa fa-question" ) ).AddItem( new MenuItemDefinition( "Users", new LocalizableString("Users", ModuleZeroSampleProjectConsts.LocalizationSourceName), url: "#/users", icon: "fa fa-users" ) ); } }View Code
JS代码是通过 NavigationScriptManager 类的 GetScriptAsync()进行加载与权限进行判断,获取导航数据通过 abp.nav.menus.MainMenu
public async Task<IReadOnlyList<UserMenu>> GetMenusAsync(long? userId) //根据当前用户加载相关导航 { var userMenus = new List<UserMenu>(); foreach (var menu in _navigationManager.Menus.Values) // 默认初始化的所有 导航属性 { userMenus.Add(await GetMenuAsync(menu.Name, userId)); } return userMenus; } private async Task<int> FillUserMenuItems(long? userId, IList<MenuItemDefinition> menuItemDefinitions, IList<UserMenuItem> userMenuItems) { var addedMenuItemCount = 0; foreach (var menuItemDefinition in menuItemDefinitions) { if (menuItemDefinition.RequiresAuthentication && !userId.HasValue) { continue; } if (!string.IsNullOrEmpty(menuItemDefinition.RequiredPermissionName) && (!userId.HasValue || !(await PermissionChecker.IsGrantedAsync(userId.Value, menuItemDefinition.RequiredPermissionName)))) //根据当前用户Id和权限判断当前用户是否有导航权限 { continue; } var userMenuItem = new UserMenuItem(menuItemDefinition); if (menuItemDefinition.IsLeaf || (await FillUserMenuItems(userId, menuItemDefinition.Items, userMenuItem.Items)) > 0) //递归加载层级导航 { userMenuItems.Add(userMenuItem); ++addedMenuItemCount; } } return addedMenuItemCount; }View Code
abp.js 定义了很多方法与属性,用户判断权限的是 abp.auth.hasPermission(),该方法的参数是 后台Action对应的操作权限,如果该方法返回值为True,则说明当前用户被授予了权限。
前台JS通过 AuthorizationScriptManager 类的 GetScript 方法 加载所有权限及当前用户的权限
public async Task<string> GetScriptAsync() { var allPermissionNames = _permissionManager.GetAllPermissions(false).Select(p => p.Name).ToList(); //获取所有权限 var grantedPermissionNames = new List<string>(); if (AbpSession.UserId.HasValue) { foreach (var permissionName in allPermissionNames) { if (await PermissionChecker.IsGrantedAsync(AbpSession.UserId.Value, permissionName)) { grantedPermissionNames.Add(permissionName); // 获取当前用户的权限 } } } var script = new StringBuilder(); script.AppendLine("(function(){"); script.AppendLine(); script.AppendLine(" abp.auth = abp.auth || {};"); script.AppendLine(); AppendPermissionList(script, "allPermissions", allPermissionNames); script.AppendLine(); AppendPermissionList(script, "grantedPermissions", grantedPermissionNames); script.AppendLine(); script.Append("})();"); return script.ToString(); }View Code
权限初始化定义需集成 AuthorizationProvider,如下
public class ModuleZeroSampleProjectAuthorizationProvider : AuthorizationProvider { public override void SetPermissions(IPermissionDefinitionContext context) { //TODO: Localize (Change FixedLocalizableString to LocalizableString) context.CreatePermission("CanCreateQuestions", new FixedLocalizableString("Can create questions")); context.CreatePermission("CanDeleteQuestions", new FixedLocalizableString("Can delete questions")); context.CreatePermission("CanDeleteAnswers", new FixedLocalizableString("Can delete answers")); context.CreatePermission("CanAnswerToQuestions", new FixedLocalizableString("Can answer to questions"), isGrantedByDefault: true); } }View Code
所有的权限验证都是通过 AbpUserManager 完成的,以下是几个重要方法
Task<bool> IsGrantedAsync(long userId, string permissionName)
(await UserPermissionStore.HasPermissionAsync(user, new PermissionGrantInfo(permission.Name, false))) 判断当前用户是否被授予权限
以QuestionAppService为例,说明一下权限配置,每个Service层都要设置权限的 [AbpAuthorize(“Questions”)],当请求时会通过拦截器自动进行权限验证,每个Action操作同样会进行权限拦截 [AbpAuthorize("CanCreateQuestions")] ,权限拦截实现是通过 AuthorizationInterceptor 实现的。
权限验证是通过如下方法进行操作
internal class AuthorizeAttributeHelper : IAuthorizeAttributeHelper, ITransientDependency { public async Task AuthorizeAsync(IEnumerable<IAbpAuthorizeAttribute> authorizeAttributes) { if (!AbpSession.UserId.HasValue) { throw new AbpAuthorizationException("No user logged in!"); } foreach (var authorizeAttribute in authorizeAttributes) { await PermissionChecker.AuthorizeAsync(authorizeAttribute.RequireAllPermissions, authorizeAttribute.Permissions); //权限检查 } } }View Code
建议大家先学会如何去用,在用的过程中会调试再调试,慢慢的就会熟悉源代码,在不会用的情况下直接研究源代码确实不易,俗话说“熟能生巧”应该就是这个意思吧,每个人的技术水平与能力各不相同,建议只是个人意见。