码迷,mamicode.com
首页 > Web开发 > 详细

dotnet core 自定义Attribute

时间:2020-04-20 23:40:50      阅读:217      评论:0      收藏:0      [点我收藏+]

标签: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<ISomeService>();

            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<IEnumerable<string>> 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<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
    {
        protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);

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

            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<TAttribute> GetAttributes(MemberInfo memberInfo)
        {
            return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
        }
    }

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

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

            context.Succeed(requirement);
        }

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

}

在startup的configureservice添加

    services.AddSingleton<Microsoft.AspNetCore.Authorization.IAuthorizationHandler, Utils.PermissionAuthorizationHandler>();

    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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!