【发布时间】: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 时,它们才能按预期工作。
问题:
- 我是否使用自定义 AuthorizeAttribute 走在正确的道路上,还是有更好的方法?
- 如果客户 AuthorizeAttribute 是正确的路径...我错过了什么?
感谢任何帮助!
【问题讨论】:
-
您不应该编写自己的自定义授权属性,请参阅blowdart's answer
标签: asp.net-core .net-core asp.net-authorization