【问题标题】:Asp.Net Core 2.1 - Authorize based on content in requestAsp.Net Core 2.1 - 根据请求中的内容进行授权
【发布时间】:2018-10-18 10:53:51
【问题描述】:

我正在公开一个端点以与第 3 方集成,他们的要求是我根据在发布的正文中传递的密钥授权他们对我的端点的请求。然后,我的代码将需要验证传递的密钥是否与我这边的某个预定值匹配。传入的模型将如下所示:

public class RequestBase
{
    public string ApiKey { get; set; }
    ...
}

探索Authorization in ASP.NET Core 的选项我并没有真正看到我正在尝试做的事情。我在想来自this 问题的自定义 AuthorizeAttribute 会起作用,但无论我做什么,我都没有运气并得到 401。这是我目前所拥有的:

[AttributeUsage(AttributeTargets.Class)]
public class MyAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    private static IEnumerable<string> _apiKeys = new List<string>
        {
            "some key... eventually will be dynamic"
        };

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var req = context.HttpContext.Request;
        req.EnableRewind();

        using (var reader = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
        {
            var bodyStr = reader.ReadToEnd();
            var isAuthorized = _apiKeys.Any(apiKey => bodyStr.Contains(apiKey));
            if (!isAuthorized)
            {
                context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
                return;
            }
        }

        req.Body.Position = 0;
    }
}

如果在正文中找不到密钥,则按预期返回 403。但是,当找到密钥时,我得到的结果仍然是 401。几乎好像 base.OnAuthorization 正在被调用。我还有其他使用标准 AurhorizeAttribute 的端点。只有当我传入 JWT 时,它们才能按预期工作。

问题:

  1. 我是否使用自定义 AuthorizeAttribute 走在正确的道路上,还是有更好的方法?
  2. 如果客户 AuthorizeAttribute 是正确的路径...我错过了什么?

感谢任何帮助!

【问题讨论】:

标签: asp.net-core .net-core asp.net-authorization


【解决方案1】:

对于使用您自己的IAuthorizationFilter 授权逻辑,您不应使用AuthorizeAttribute,这将使用默认身份验证架构检查身份验证。

尝试将AuthorizeAttribute 更改为Attribute

[AttributeUsage(AttributeTargets.Class)]
public class KeyAuthorizeAttribute : Attribute, IAuthorizationFilter
{

【讨论】:

  • 确认这确实有效,并且是我最终要做的……至少现在是这样。谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-02-19
  • 1970-01-01
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
相关资源
最近更新 更多