dotnet core 自定义Attribute

2021-03-20 07:26

阅读:745

标签:reg   gis   city   register   namespace   requests   some   name   where   

自定義Attribute

使用dotnet core 2.1

第一種

using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;

namespace MyProject.Utils
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class PermissionAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        private readonly string _Permission;
        private IConfiguration _config;
        public PermissionAttribute(string Permission)
        {
            _Permission = Permission;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            this._config = (IConfiguration)context.HttpContext.RequestServices.GetService(typeof(IConfiguration));
            var tem = _config["Temperature:city"];
            var user = context.HttpContext.User;
            if(!user.Identity.IsAuthenticated)
            {
                context.Result = new UnauthorizedResult();
                return;
            }

            // you can also use registered services
            // var someService = context.HttpContext.RequestServices.GetService();

            var isAuthorized = false;
            if (!isAuthorized)
            {
                context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
                return;
            }
        }
    }
}

然後就可以使用Permission

[Route("api/[controller]")]
    [ApiController,Authorize,Permission("123")]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult> Get()
        {
            return new string[] { "value1", "value2" };
        }

    }

第二種

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;

namespace MyProject.Utils
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class PermissionAttribute : AuthorizeAttribute
    {
        public string Name { get; }

        public PermissionAttribute(string name) : base("Permission")
        {
            Name = name;
        }
    }

    public abstract class AttributeAuthorizationHandler : AuthorizationHandler where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
    {
        protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable attributes);

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
        {
            var attributes = new List();

            var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
            if (action != null)
            {
                attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
                attributes.AddRange(GetAttributes(action.MethodInfo));
            }

            return HandleRequirementAsync(context, requirement, attributes);
        }

        private static IEnumerable GetAttributes(MemberInfo memberInfo)
        {
            return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast();
        }
    }

    public class PermissionAuthorizationRequirement : IAuthorizationRequirement
    {
        //添加自定义需求属性
    }

    public class PermissionAuthorizationHandler : AttributeAuthorizationHandler
    {
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement, IEnumerable attributes)
        {
            foreach (var permissionAttribute in attributes)
            {
                if (!await AuthorizeAsync(context.User, permissionAttribute.Name))
                {
                    return;
                }
            }

            context.Succeed(requirement);
        }

        private Task AuthorizeAsync(ClaimsPrincipal user, string permission)
        {
            //自定义用户权限逻辑
            return new Task(() => false);
        }
    }

}

在startup的configureservice添加

    services.AddSingleton();

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Permission", policyBuilder =>
        {
            policyBuilder.Requirements.Add(new Utils.PermissionAuthorizationRequirement());
        });
    });

dotnet core 自定义Attribute

标签:reg   gis   city   register   namespace   requests   some   name   where   

原文地址:https://www.cnblogs.com/hwxing/p/12737356.html


评论


亲,登录后才可以留言!