zoukankan      html  css  js  c++  java
  • dotnet core 自定义Attribute

    自定義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());
            });
        });
    
  • 相关阅读:
    基于Cat的分布式调用追踪
    python3.8.0 Django 开发后端接口api 部署到 Linux Centos7上
    openlayers上添加点击事件
    openlayers在底图上添加静态icon
    vue中使用kindeditor富文本编辑器2
    openlayers绘制点,线,圆等
    openLayers绘制静态底图
    快速调用Android虚拟机
    flutter环境配置window10
    reactjs中配置代理跨域
  • 原文地址:https://www.cnblogs.com/hwxing/p/12737356.html
Copyright © 2011-2022 走看看