使用ABP CLI创建Web 应用(十五)—— 授权

上一节我们定义了权限,现在需要在需要的地方增加权限控制。首先,需要为应用层的功能授权,在PoetAppService中增加权限控制,ABP的CrudAppService中已经定义了增删改查的权限,只有把我们定义的权限关联到相应的变量就可以了。代码如下:

using Volo.Abp.Domain.Repositories;
using ZL.Test.Permissions;

namespace ZL.Test.Poets
{
    public class PoetAppService :
        CrudAppService<
            Poet, //The Poet entity
            PoetDto, //Used to show poets
            Guid, //Primary key of the book entity
            PagedAndSortedResultRequestDto, //Used for paging/sorting
            CreateUpdatePoetDto>, //Used to create/update a poet
        IPoetAppService
    {
        public PoetAppService(IRepository repository) : base(repository)
        {
            GetPolicyName = TestPermissions.Poets.Default;
            GetListPolicyName = TestPermissions.Poets.Default;
            CreatePolicyName = TestPermissions.Poets.Create;
            UpdatePolicyName = TestPermissions.Poets.Edit;
            DeletePolicyName = TestPermissions.Poets.Delete;
        }
    }
}

接下来,我们需要给页面授权,在.Web项目中,打开TestWebModule,在ConfigureServices中增加对Razor页面的授权:

           Configure(options =>
            {
                options.Conventions.AuthorizePage("/Poets/Index", TestPermissions.Poets.Default);
                options.Conventions.AuthorizePage("/Poets/CreateModal", TestPermissions.Poets.Create);
                options.Conventions.AuthorizePage("/Poets/EditModal", TestPermissions.Poets.Edit);
            });

我们还需要在页面上增加权限控制,对于没有编辑权限的用户,隐藏增加按钮:

@page
@using ZL.Test.Localization
@using ZL.Test.Permissions
@using Microsoft.AspNetCore.Authorization
@using Microsoft.Extensions.Localization
@model ZL.Test.Web.Pages.Poets.IndexModel
@inject IStringLocalizer L
@inject IAuthorizationService AuthorizationService
@section scripts
{
    
}

    
        
            
                @L["Poet"] 
            
            
                @if (await AuthorizationService.IsGrantedAsync(TestPermissions.Poets.Create))
                {
                    
                }
            
        
    
    
        
    

增加和删除菜单是在Index.js中实现的,因此,还需要在这个文件中增加相关的授权代码:

                              {
                                    text: l('Edit'),
                                    visible: abp.auth.isGranted('Test.Poets.Edit'), //CHECK for the PERMISSION
                                    action: function (data) {
                                        editModal.open({ id: data.record.id });
                                    }
                                },

对于删除:

                                    visible: abp.auth.isGranted('Test.Poets.Delete'),

到这里授权就完成了。

你可能感兴趣的:(使用ABP CLI创建Web 应用(十五)—— 授权)