c# - 在 asp.net 中为特定端点创建简单的 api 密钥身份验证
问题描述
我正在尝试为某些特定端点创建一个简单的 apikey 身份验证。我在 ASPNet 核心 3.1 中做了类似的事情。这非常适合这种情况。
我想在 ASP.Net 中实现相同的东西,我可以在 asp.net 中的 if 加上其他检查,然后再到达端点。有了它,我可以[ApiKeyAuth]
在控制器中添加注释。
就像是
[ApiController]
[ApiKeyAuth]
下面是我在 asp.net core 3.1 中实现的
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiKeyAuthAttribute : Attribute, IAsyncActionFilter
{
private const string ApiKeyHeaderName = "ApiKey";
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeaderName, out var potentialApikey))
{
context.Result = new UnauthorizedResult();
return;
}
var configuration = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
var apikey = configuration.GetValue<string>("ApiKey");
if (!apikey.Equals(potentialApikey))
{
context.Result = new UnauthorizedResult();
return;
}
await next();
}
这是我试图在 asp.net 中实现的
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiKeyAuthAttribute : Attribute, IActionFilter
{
private const string ApiKeyHeaderName = "ApiKey";
public bool AllowMultiple => throw new NotImplementedException();
public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
if (!actionContext.Request.Headers.TryGetValues(ApiKeyHeaderName, out var potentialApiKey))
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
return actionContext.Response; //ERROR HERE
}
var apikey = actionContext.Request.Headers.GetValues("ApiKey");
if (!apikey.Equals(potentialApiKey))
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
return actionContext.Response; //ERROR HERE
}
return continuation();
}
}
这是我得到的错误
Cannot implicitly convert type 'System.Net.Http.HttpResponseMessage' to 'System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>'
解决方案
推荐阅读
- python - 将 Ajax 添加到 Django
- api - 嘿,有人可以给我看一些关于 discord.py API 的代码吗?使用来自网站的 api
- python - 为开发设置沙盒容器环境的好方法是什么?
- python - 解包字典
- python - 如何从 sqlalchemy .execute() 方法中获取价值?Python + Sqlalchemy + MS SQL 服务器
- acumatica - 报表设计器中 Acumatica 中金额字段的文字表示
- python - 如何解决爬取GitHub问题正文时出现非法字符的问题?
- yocto - yocto如何支持ftp命令?
- python - 未找到 Anaconda3 Python shapely 模块
- sql - 在 Postgres (Redshift) 中使用两个选择列运行 MAX 聚合查询时出现问题