簡體   English   中英

ASP.NET Core 6 Web API - 如何檢查給定 ActionDescriptor 的操作是否需要身份驗證?

[英]ASP.NET Core 6 Web API - How do I check if the action with given ActionDescriptor requires authentication?

給定一個ActionDescriptor ,例如位於GET /api/Item/{id}的操作的ActionDescriptor ,我如何判斷它是否需要身份驗證?
檢查與操作對應的方法的過濾器,以及可能聲明該方法的 class 的過濾器是否為AuthorizeAttributeAllowAnonymousAttribute是不可靠的,因為通過這種方式AuthorizationOptions的策略( FallbackPolicyDefaultPolicy和使用AddPolicy()添加的策略)例如,不會被考慮在內。
我試圖檢查以下接口是否具有接受ActionDescriptor的方法,但不幸的是它們都沒有:

  • IAuthorizationPolicyProvider
  • IAuthorizationService
  • IAuthorizationHandler
  • IAuthorizationHandlerContextFactory
  • IAuthorizationHandlerProvider

編輯:經過一番搜索,我認為 WebForms 中存在我需要的內容: UrlAuthorizationModule.CheckUrlAccessForPrincipal() 我想知道 ASP.NET Core 是否有類似的東西。

這里是 go:

using System.Linq;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;

public static bool RequiresAuthoriation(this ActionDescriptor actionDescriptor)
{
    return actionDescriptor.FilterDescriptors.Any(fd=>fd.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAuthorizationFilter));
}

您需要使用授權接口檢查過濾器,所以我認為這應該有效:

if(ControllerContext.ActionDescriptor.FilterDescriptors.OfType<IAuthorizationFilter>().Any())
 //means the action has Authorization filter
        
if(ControllerContext.ActionDescriptor.FilterDescriptors.OfType<IAllowAnonymous>().Any())
 //means action has AllowAnonymous filter

更新:另一種方法是獲取所有動作及其屬性

var projectAssembly = Assembly.GetAssembly(typeof(Suxxeed.Analytixx.Api.Startup));
var controllerActionlist = projectAssembly.GetTypes()
            .Where(type => typeof(Controller).IsAssignableFrom(type))
            .SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
            .Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
            .Select(x => new
            {
                Controller = x.DeclaringType?.Name,
                ControllerAttributes = string. Join(",", x.DeclaringType.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))),
                Action = x.Name,
                ActionAttributes = string. Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", "")))
            })
            .OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();

//for detecting any action has Authorize attribute you can do this
if(controllerActionlist.Any(x=> x.Action=="YouAction" 
&& (x.ActionAttributes.Contains("Authorize") || x.ControllerAttributes.Contains("Authorize"))))
   //some stuff

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM