您如何访问 .Net Core 中 AuthorizeAttribute class 中的 appsetting.json 参数

How do you access appsetting.json parameters in an AuthorizeAttribute class in .Net Core

在我的 ASP.NET 核心 MVC 应用程序中,我有一个 class 继承自 AuthorizeAttribute 并实现 IAuthorizationFilter。

namespace MyProject.Attributes
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class AllowGroupsAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        private readonly List<PermissionGroups> groupList = null;
        public AllowGroupsAttribute(params PermissionGroups[] groups)
        {
            groupList = groups.ToList();
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var executingUser = context.HttpContext.User;

            //If the user is not authenticated then prevent execution
            if (!executingUser.Identity.IsAuthenticated)
            {
                context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
            }
        }
    }
}

这让我可以用类似 [AllowGroups(PermissionGroups.Admin, PermissionGroups.Level1]

的东西来装饰控制器方法

我打算做的是,根据列出的枚举值从 appsettings.json 中检索组名,并检查用户是否是这些组的成员。

我的问题是,从我的属性 class 中访问应用程序设置的正确方法是什么?

启动时配置设置,

通过选项

services.Configure<MySettings>(Configuration.GetSection("groups"));

或具体对象模型

MySettings settings = Configuration.GetSection("groups").Get<MySettings>();
services.AddSingleton(settings);

然后通过过滤器HttpContext.RequestServices中的

解析它们
//...

IServiceProvider services = context.HttpContext.RequestServices;

MySettings settings = services.GetService<MySettings>();
//-- OR --
//MySettings settings = services.GetService<IOptions<MySettings>>().Value;

//...

虽然是一种更多的服务定位器方法,但它应该允许访问所需的配置。

我遇到了同样的问题,所以你解决了

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AllowGroupsAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    IConfigurationBuilder builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            IConfigurationRoot configuration = builder.Build();
            var user = configuration.GetSection("AppConfig").GetSection("user").Value;
            var pass = configuration.GetSection("AppConfig").GetSection("pass").Value;

..........

}

在appsettings.json

"AppConfig": {
    "user": "hola",
    "pass": "mundo"
  },