如何在中间件中获取 appSettings 的一部分?

huangapple go评论78阅读模式
英文:

How to get a section of appSettings in a middleware?

问题

我想在身份验证中间件中调用appSettings的一部分,但我不知道如何做到这一点。我正在使用.Net 6。在我的program.cs文件中,我正在调用:

app.UseAuthentication();

我想要在端点中使用API密钥进行调用身份验证,所以我按照我的语言中的这篇文章操作:https://balta.io/blog/aspnet-autenticacao-apikey

因此,按照这篇博客,我创建了一个ApiKeyAttribute.cs文件:

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();
}

在这个示例中,密钥在文件内部,但我想要存储在我的appSettings中,并在这个文件中调用该部分。

这是可能的吗?如果是的话,如何做到的?
如果不可能,存储密钥的正确方法是什么?

注意:在这个示例中,只有一个密钥,但我想要存储多个密钥,就像这样:

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

我已经搜索了一下,但我找到的示例只是在Controller文件中调用appSettings的数据。

我阅读了这份文档:https://learn.microsoft.com/pt-br/aspnet/core/security/authentication/?view=aspnetcore-6.0
但没有找到关于appSettings的内容。

英文:

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

答案1

得分: 0

您可以利用依赖注入来从appConfig中解析这些信息,方法是向您的自定义ActionFilter类添加一个构造函数,将IConfiguration作为参数传递给构造函数,最后将引用赋给一个(私有)字段(例如configuration)。

OnActionExecutionAsync()方法中,尝试从包含所需数据的IConfiguration字段获取配置的部分。

var keyConfig = configuration.GetSection("keys");
英文:

You can leverage Dependency Injection to resolve this information from appConfig by adding a constructor to your custom ActionFilter class, passing IConfiguration as a parameter to the constructor and finally assigning the reference to
a (private) field (e.g. configuration).

Within the OnActionExecutionAsync() method try getting the section of your config from the IConfiguration field that has the data you need.

var keyConfig = configuration.GetSection("keys");

答案2

得分: 0

根据您的情景和描述,您可以直接在中间件中构建配置服务,以获取您的appsettings.json值。

让我们实际看看如何实现这一点。

您的中间件:

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();
}

注意: 为了演示的目的,我直接按索引访问,但您也可以获取数组,然后遍历它。

输出:

如何在中间件中获取 appSettings 的一部分?

如何在中间件中获取 appSettings 的一部分?

注意: 您可以参考此示例。如果您想了解有关配置提供程序的更多详细信息,您可以在这里查看我们的官方文档

英文:

> 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 = &quot;api_key&quot;;
        private const string ApiKey = &quot;key_example&quot;;
   
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var configuration = new ConfigurationBuilder().AddJsonFile(&quot;appsettings.json&quot;).Build();
           
            var keyName1 = configuration.GetValue&lt;string&gt;(&quot;keys:0:keyName1&quot;);
            var keyName2 = configuration.GetValue&lt;string&gt;(&quot;keys:1:keyName2&quot;);
         
           

            if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyName, out var extractedApiKey))
            {
                context.Result = new ContentResult()
                {
                    StatusCode = 401,
                    Content = &quot;ApiKey n&#227;o encontrada&quot;
                };
                return;
            }

            if (!ApiKey.Equals(extractedApiKey))
            {
                context.Result = new ContentResult()
                {
                    StatusCode = 403,
                    Content = &quot;Acesso n&#227;o autorizado&quot;
                };
                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:

如何在中间件中获取 appSettings 的一部分?

如何在中间件中获取 appSettings 的一部分?

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.

huangapple
  • 本文由 发表于 2023年6月8日 04:53:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定