首页 > 解决方案 > 在 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>'  

标签: c#asp.netasp.net-mvc-4asp.net-web-api

解决方案


推荐阅读