Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my ASP.NET Core MVC app, I have a class that inherits from AuthorizeAttribute and implements 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);
            }
        }
    }
}

This allows me to decorate a controller method with something like [AllowGroups(PermissionGroups.Admin, PermissionGroups.Level1]

What I plan to do, is retreive group names from appsettings.json based on the enum values listed and check that the user is a member of those groups.

My question is, what is the correct way to access the app settings from within my attribute class?

like image 559
GarethPN Avatar asked Oct 24 '18 12:10

GarethPN


People also ask

What is Appsetting json in asp net core?

The appsettings. json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information.

How do I get Appsettings json value in startup CS?

In order to add AppSettings. json file, right click on the Project in Solution Explorer. Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button. Once the File is created, it will have a DefaultConnection, below that a new AppSettings entry is added.


1 Answers

Configure settings on startup,

Either via options

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

Or concrete object model

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

And then resolve them through the HttpContext.RequestServices within the filter

//...

IServiceProvider services = context.HttpContext.RequestServices;

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

//...

while a more service locator approach, it should allow for access to the desired configuration.

like image 193
Nkosi Avatar answered Oct 10 '22 18:10

Nkosi