上一节我们定义了权限,现在需要在需要的地方增加权限控制。首先,需要为应用层的功能授权,在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<Poet, Guid> 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<RazorPagesOptions>(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<TestResource> L
@inject IAuthorizationService AuthorizationService
@section scripts
{
<abp-script src="/Pages/Poets/Index.js" />
}
<abp-card>
<abp-card-header>
<abp-row>
<abp-column size-md="_6">
<abp-card-title>@L["Poet"] </abp-card-title>
</abp-column>
<abp-column size-md="_6" class="text-right">
@if (await AuthorizationService.IsGrantedAsync(TestPermissions.Poets.Create))
{
<abp-button id="NewBookButton"
text="@L["NewPoet"]"
icon="plus"
button-type="Primary" />
}
</abp-column>
</abp-row>
</abp-card-header>
<abp-card-body>
<abp-table striped-rows="true" id="PoetsTable"></abp-table>
</abp-card-body>
</abp-card>
增加和删除菜单是在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'),
到这里授权就完成了。