Search code examples
c#asp.net-coreauthentication.net-6.0

How to get a section of appSettings in a middleware?


I want to call a section of appSettings in authentication middleware, but I don't know how to do this. I'm using .Net 6. In my program.cs file, I'm calling:

app.UseAuthentication();

I'm want to authenticate the call in a endpoint using a apikey, so I follow this article in my language: https://balta.io/blog/aspnet-autenticacao-apikey

So, following this blog, I created a ApiKeyAttribute.cs file:

    private const string ApiKeyName = "api_key";
    private const string ApiKey = "key_example";

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        
        if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyName, out var extractedApiKey)) 
        {
            context.Result = new ContentResult()
            {
                StatusCode = 401,
                Content = "ApiKey não encontrada"
            };
            return;
        }

        if (!ApiKey.Equals(extractedApiKey))
        {
            context.Result = new ContentResult()
            {
                StatusCode = 403,
                Content = "Acesso não autorizado"
            };
            return;
        }

        await next();
    }

In this example, the key is in inside the file, but I want store in my appSettings and call the section in this file.

It is possible to do this? If yes, how? If is not possible, what is the correct way to store the key?

Observation: In this example, just have one key, but I want store more than one key, like this:

"keys": [
    {
      "keyName1": "example1"
    },
    {
      "keyName2": "example2"
    }
  ]

I already search about this, but the examples I found just call the data of appSettings in a Controller file.

I read this documentation: https://learn.microsoft.com/pt-br/aspnet/core/security/authentication/?view=aspnetcore-6.0 but found nothing about appSettings


Solution

  • In this example, the key is in inside the file, but I want store in my appSettings and call the section in this file.

    It is possible to do this? If yes, how? If is not possible, what is the correct way to store the key?

    Based on your scenario and description, you can directly build configuration service within your middleware in order to get your appsettings.json value.

    Let's have a look in practice, how we can achieve that.

    Your Middleware:

            private const string ApiKeyName = "api_key";
            private const string ApiKey = "key_example";
       
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
               
                var keyName1 = configuration.GetValue<string>("keys:0:keyName1");
                var keyName2 = configuration.GetValue<string>("keys:1:keyName2");
             
               
    
                if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyName, out var extractedApiKey))
                {
                    context.Result = new ContentResult()
                    {
                        StatusCode = 401,
                        Content = "ApiKey não encontrada"
                    };
                    return;
                }
    
                if (!ApiKey.Equals(extractedApiKey))
                {
                    context.Result = new ContentResult()
                    {
                        StatusCode = 403,
                        Content = "Acesso não autorizado"
                    };
                    return;
                }
    
                await next();
            }
    

    Note: I am directly accessing by its index for the sake of demo but you can get the array as well and then can loop through it.

    Output:

    enter image description here

    enter image description here

    Note: You can refer to this sample. If you would like to know more details on configuration providers you could check our official document here.