从声明中检查ABP权限

时间:2019-01-10 21:45:29

标签: c# asp.net-core authorization aspnetboilerplate claims

我将ABP 3.9版用于ASP.NET Core。我们有一个现有的Identity Server 4实例,该实例以声明的形式(通过OIDC)提供角色信息。我想加入ABP的权限系统进行动态菜单处理。由于我没有使用本地Identity Server 1 实现,因此我看不到将声明转换为权限的方法。

我的想法是使用自定义中间件来处理它:

public class ClaimsToAbpPermissionsMiddleware
{
    private readonly RequestDelegate _next;

    public ClaimsToAbpPermissionsMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Get user
        ClaimsPrincipal user = context.User;

        // foreach claim of type "role"
        var roleClaims = user.Claims.Where(claim => claim.Type == "role");
        foreach (Claim claim in roleClaims)
        {
            switch (claim.Value)
            {
                case "TestResults":
                    // Assign applicable permission
                    // ...
                    break;
                default:
                    break;
            }
        }

        // Call the next delegate/middleware in the pipeline
        await _next(context);
    }
}

问题是我不知道如何应用权限。 User Management 2 建议使用UserManager,它似乎具有必要的功能。

首先,Abp.ZeroCore没有此类。我可以在ASP.NET Core应用中使用Abp.Zero吗?

第二,看起来Abp.Authorization.Users.AbpUserManager具有相似的功能。我可以用这个吗?但是,我不确定如何将其注入到Startup中,因为它需要某些类型来注入AbpUserManager<TRole, TUser>,并且我不清楚要使用哪种类型。

任何帮助将不胜感激。 另外,我正在尝试的方法可行吗?有更好的方法吗?

问题是我没有使用模块零的User Management 2 。我们所有的用户都在单独的ASP.NET Identity(Identity Server)实现中,并且我使用的是ABP中的模板,该模板不包含用户/租户/角色的模型/页面,因此我没有注入AbpUserManager<TRole, TUser>的类型。

1 https://aspnetboilerplate.com/Pages/Documents/Zero/Identity-Server
2 https://aspnetboilerplate.com/Pages/Documents/Zero/User-Management

更新:因此,我按照以下答案实施了IPermissionChecker:

PermissionChecker(不喜欢该开关,但是一旦工作就可以重构):

public class PermissionChecker : IPermissionChecker, ITransientDependency
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public PermissionChecker(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public  Task<bool> IsGrantedAsync(string permissionName)
    {
        bool isGranted = false;

        // Get user
        var user = _httpContextAccessor.HttpContext.User;

        // Get claims of type "role"
        var roleClaims = user.Claims.Where(claim => claim.Type == "role");

        // Check for applicable permission based on role permissions
        foreach (Claim claim in roleClaims)
        {
            switch (claim.Value)
            {
                case "TestResults":
                    // Assign applicable permission
                    // ...
                    if(permissionName.ToLowerInvariant() == "TestResults".ToLowerInvariant())
                    {
                        isGranted = true;
                    }
                    break;
                case "About":
                    // Assign applicable permission
                    // ...
                    if (permissionName.ToLowerInvariant() == "AboutView".ToLowerInvariant())
                    {
                        isGranted = true;
                    }
                    break;
                case "Account":
                    // Assign applicable permission
                    // ...
                    if (permissionName.ToLowerInvariant() == "AccountView".ToLowerInvariant())
                    {
                        isGranted = true;
                    }
                    break;
                default:
                    break;
            }
            if (isGranted)
            {
                break;
            }
        }
        //return new Task<bool> 
        return Task.FromResult(isGranted);
    }

    public Task<bool> IsGrantedAsync(UserIdentifier user, string permissionName)
    {
        return IsGrantedAsync(permissionName);
    }
}

AuthorizationProvider:

public class MyAuthProvider : AuthorizationProvider
{
    public override void SetPermissions(IPermissionDefinitionContext context)
    {
        var about = context.CreatePermission("AboutView");
        var account = context.CreatePermission("AccountView");
        var testResults = context.CreatePermission("TestResults");
    }
}

模块初始化:

public class CentralPortalCoreModule : AbpModule
{
    public override void PreInitialize()
    {
        Configuration.Auditing.IsEnabledForAnonymousUsers = true;

        CentralPortalLocalizationConfigurer.Configure(Configuration.Localization);
        IocManager.Register<IPermissionChecker, PermissionChecker>(DependencyLifeStyle.Transient);
        Configuration.Authorization.Providers.Add<MyAuthProvider>();
    }

    public override void Initialize()
    {
        IocManager.RegisterAssemblyByConvention(typeof(CentralPortalCoreModule).GetAssembly());
    }
}

导航提供者:

public override void SetNavigation(INavigationProviderContext context)
    {
        context.Manager.MainMenu
            .AddItem(
                new MenuItemDefinition(
                    PageNames.Home,
                    L("HomePage"),
                    url: "",
                    icon: "fa fa-home"
                    )
            ).AddItem(
                new MenuItemDefinition(
                    PageNames.About,
                    L("About"),
                    url: "Home/About",
                    icon: "fa fa-info",
                    requiredPermissionName: "AboutView",
                    requiresAuthentication: true
                    )
            ).AddItem(
                new MenuItemDefinition(
                "Results",
                L("Results"),
                url: "Results",
                icon: "fa fa-tasks",
                requiredPermissionName: "TestResults"
                )
            )
            .AddItem(
                new MenuItemDefinition(
                    PageNames.Account,
                    L("Account"),
                    url: "Account",
                    icon: "fa fa-info",
                    requiredPermissionName:"AccountView",
                    requiresAuthentication: true

                    )

            )
            .AddItem(
                new MenuItemDefinition(
                    PageNames.Contact,
                    L("Contact"),
                    url: "Contact",
                    icon: "fa fa-info"
                    )
            );
    }

添加断点显示PermissionChecker和AuthProvider一样被初始化。不幸的是,即使我已通过身份验证并具有有效的角色声明,导航也不会显示受保护的项目。永远不会调用IsGrantedAsync方法。我尝试使用requireAuthentication = true和false设置导航项,但均未更改任何内容。

我想念什么吗?

1 个答案:

答案 0 :(得分:2)

好吧,您指的是零模块文档,而不是零模块。

如果您不存储用户,则存储用户权限可能没有意义。

您可以实施IPermissionChecker来检查声明的权限。

public class PermissionChecker : IPermissionChecker, ITransientDependency
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public PermissionChecker(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public async Task<bool> IsGrantedAsync(string permissionName)
    {
        // Get user
        var user = _httpContextAccessor.HttpContext.User;

        // Get claims of type "role"
        var roleClaims = user.Claims.Where(claim => claim.Type == "role");

        // Check for applicable permission based on role permissions
        // ...
    }

    public Task<bool> IsGrantedAsync(UserIdentifier user, string permissionName)
    {
        return IsGrantedAsync(permissionName);
    }
}

由于AuthorizationHelper检查了AbpSession.UserId,因此您必须覆盖其方法。

public class NonUserAuthorizationHelper : AuthorizationHelper
{
    private readonly IAuthorizationConfiguration _authConfiguration

    public NonUserAuthorizationHelper(IFeatureChecker featureChecker, IAuthorizationConfiguration authConfiguration)
        : base(featureChecker, authConfiguration)
    {
        _authConfiguration = authConfiguration;
    }

    public override async Task AuthorizeAsync(IEnumerable<IAbpAuthorizeAttribute> authorizeAttributes)
    {
        if (!_authConfiguration.IsEnabled)
        {
            return;
        }

        // if (!AbpSession.UserId.HasValue)
        // {
        //     throw new AbpAuthorizationException(
        //         LocalizationManager.GetString(AbpConsts.LocalizationSourceName, "CurrentUserDidNotLoginToTheApplication")
        //     );
        // }

        foreach (var authorizeAttribute in authorizeAttributes)
        {
            await PermissionChecker.AuthorizeAsync(authorizeAttribute.RequireAllPermissions, authorizeAttribute.Permissions);
        }
    }
}

然后将其替换为PreInitialize模块的*.Core方法。

// using Abp.Configuration.Startup;

public override void PreInitialize()
{
    Configuration.ReplaceService<IAuthorizationHelper, NonUserAuthorizationHelper>();
}