<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          .NET Core 反射獲取所有控制器及方法上特定標(biāo)簽

          共 5485字,需瀏覽 11分鐘

           ·

          2020-10-05 11:59


          有個(gè)需求,就是在. NET Core中,我們想在項(xiàng)目 啟動(dòng)時(shí),獲取LinCmsAuthorizeAttribute這個(gè)特性標(biāo)簽所有出現(xiàn)的地方,把他的參數(shù),放入一個(gè)集合并緩存起來,以便后面使用此數(shù)據(jù)用于權(quán)限驗(yàn)證。

          我們通過反射獲取所有控制器下及方法的Attribute。

          LinCmsAuthorizeAttribute是什么

          其代碼非常簡單,用于自定義權(quán)限驗(yàn)證,通過重寫OnAuthorizationAsync方法,實(shí)現(xiàn)固定權(quán)限可分配給動(dòng)態(tài)角色(也能分配給動(dòng)態(tài)用戶)。主要就基于權(quán)限的授權(quán)的實(shí)現(xiàn)進(jìn)行研究,實(shí)現(xiàn)方法級(jí)別的權(quán)限驗(yàn)證。

          • https://www.cnblogs.com/RainingNight/p/dynamic-authorization-in-asp-net-core.html

          當(dāng)然,這個(gè)只是部分代碼,完整代碼請(qǐng)查看最下方開源地址,其中LinCmsAuthorizeAttribute繼承AuthorizeAttribute,擁有指定角色權(quán)限控制,當(dāng)Permission未指定時(shí),當(dāng)過濾器與Authorize功能相同。Module是指模塊,即多個(gè)權(quán)限,屬于同一個(gè)模塊,方便前臺(tái)展示為樹型結(jié)構(gòu)。Permission屬性的值不可重復(fù)。

          [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
          public class LinCmsAuthorizeAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
          {
          public string Permission { get; set; }
          public string Module { get; set; }

          public LinCmsAuthorizeAttribute()
          {

          }

          public LinCmsAuthorizeAttribute(string permission,string module)
          {
          Permission = permission;
          Module = module;
          }

          public LinCmsAuthorizeAttribute(string permission,string module, string policy) : base(policy)
          {
          Permission = permission;
          Module = module;
          }

          public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
          {
          if (Permission == null) return;
          var authorizationService = (IAuthorizationService)context.HttpContext.RequestServices.GetService(typeof(IAuthorizationService));
          var authorizationResult = await authorizationService.AuthorizeAsync(context.HttpContext.User, null, new OperationAuthorizationRequirement() { Name = Permission });
          if (!authorizationResult.Succeeded)
          {
          context.Result = new ForbidResult();
          }
          }

          public override string ToString()
          {
          return $"\"{base.ToString()}\",\"Permission:{Permission}\",\"Module:{Module}\",\"Roles:{Roles}\",\"Policy:{Policy}\",\"AuthenticationSchemes:{AuthenticationSchemes}\"";
          }
          }

          Controller

          在 LinCms.Web中的Controller,至于為什么Permission為中文,目前的主要原因,此項(xiàng)目用于適配?Lin-CMS-VUE項(xiàng)目,所以于平常我們以某個(gè)字符串作為權(quán)限名不同,但不須大精小怪,道理相同。

          [Route("cms/log")]
          [ApiController]
          public class LogController : ControllerBase
          {
          private readonly ILogService _logService;

          public LogController(ILogService logService)
          {
          _logService = logService;
          }

          [HttpGet("users")]
          [LinCmsAuthorize("查詢?nèi)罩居涗浀挠脩?/span>", "日志")]
          public List<string> GetLoggedUsers([FromQuery]PageDto pageDto)
          {
          return _logService.GetLoggedUsers(pageDto);
          }


          [HttpGet]
          [LinCmsAuthorize("查詢所有日志", "日志")]
          public PagedResultDto GetLogs([FromQuery]LogSearchDto searchDto)
          {
          return _logService.GetLogUsers(searchDto);
          }

          [HttpGet("search")]
          [LinCmsAuthorize("搜索日志", "日志")]
          public PagedResultDto SearchLogs([FromQuery]LogSearchDto searchDto)
          {
          return _logService.GetLogUsers(searchDto);
          }
          }

          測(cè)試類獲取方法上的特定標(biāo)簽

          in xunit test 項(xiàng)目工程中,開始我們的測(cè)試

          [Fact]
          public void GetAssemblyMethodsAttributes()
          {
          var assembly = typeof(Startup).Assembly.GetTypes().AsEnumerable()
          .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToList();

          assembly.ForEach(r =>
          {
          foreach (var methodInfo in r.GetMethods())
          {
          foreach (Attribute attribute in methodInfo.GetCustomAttributes())
          {
          if (attribute is LinCmsAuthorizeAttribute linCmsAuthorize)
          {
          _testOutputHelper.WriteLine(linCmsAuthorize.ToString());
          }
          }
          }
          });
          }

          方法結(jié)果

          可在輸出文本中查看,正是我們想要的東西,最后一行,是其他Controller中的內(nèi)容,而且我們重寫了ToString(),所以我們能看到其屬性。

          "LinCms.Zero.Authorization.LinCmsAuthorizeAttribute","Permission:查詢?nèi)罩居涗浀挠脩?/span>","Module:日志","Roles:","Policy:","AuthenticationSchemes:"
          "LinCms.Zero.Authorization.LinCmsAuthorizeAttribute","Permission:查詢所有日志","Module:日志","Roles:","Policy:","AuthenticationSchemes:"
          "LinCms.Zero.Authorization.LinCmsAuthorizeAttribute","Permission:搜索日志","Module:日志","Roles:","Policy:","AuthenticationSchemes:"
          "LinCms.Zero.Authorization.LinCmsAuthorizeAttribute","Permission:查看lin的信息","Module:信息","Roles:","Policy:","AuthenticationSchemes:"

          獲取控制器上特性標(biāo)簽

          /// 
          /// 獲取控制器上的LinCmsAuthorizeAttribute
          /// </summary>
          /// "LinCms.Zero.Authorization.LinCmsAuthorizeAttribute","Permission:","Module:","Roles:Administrator","Policy:","AuthenticationSchemes:"
          [Fact]
          public void GetControllerAttributes()
          {
          var assembly = typeof(Startup).Assembly.GetTypes().AsEnumerable()
          .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToList();

          assembly.ForEach(d =>
          {
          var linCmsAuthorize = d.GetCustomAttribute()
          ;
          if (linCmsAuthorize != null)
          {
          _testOutputHelper.WriteLine(linCmsAuthorize.ToString());
          }
          });
          }

          Controller結(jié)果

          只有AdminController加了此標(biāo)簽,所以只有一行。

          "LinCms.Zero.Authorization.LinCmsAuthorizeAttribute","Permission:","Module:","Roles:Administrator","Policy:","AuthenticationSchemes:"

          此時(shí)Roles為Administrator,Permission及Module都是null, 這是因?yàn)橹挥蠥dminController中加了LinGroup.Administrator="Administrator"字符串,在登錄過程中,已經(jīng)給當(dāng)前登錄用戶設(shè)置了 new Claim(ClaimTypes.Role,user.IsAdmin()?LinGroup.Administrator:user.GroupId.ToString()),即"Administrator,當(dāng)用戶訪問AdminController中的方法時(shí),LinCmsAuthorize并沒有做相關(guān)驗(yàn)證,都是AuthorizeAttribute,實(shí)現(xiàn)了固定角色權(quán)限的判斷及登錄的判斷。LinCmsAuthorize完成了固定權(quán)限設(shè)置為不同的動(dòng)態(tài)角色后,判斷用戶是否擁有此權(quán)限。

          [LinCmsAuthorize(Roles = LinGroup.Administrator)]
          public class AdminController : ControllerBase
          {
          ...
          }

          參考

          • c# – 如何在asp. net core rc2中獲取控制器的自定義屬性?https://codeday.me/bug/20181207/453278.html

          開源地址

          • github.com/luoyunchong/lin-cms-dotnetcore

          瀏覽 50
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  无码污污网站 | 欧美一级做A片 | 玩弄奶水刚产少妇 | 中文字幕第777页 | 国产黄色小视频在线观看 |