使用IAuthenticationFilter

时间:2018-10-21 11:05:13

标签: asp.net asp.net-web-api restful-authentication

我正在使用ng-file-upload上传文件,并且在使用HttpContext.CurrentIAuthenticationFilter为null时出现一些异常问题。当我在WebApiConfig中评论身份验证过滤器时,一切正常。

要测试的控制器

    [HttpPost]
    public IHttpActionResult Upload()
    {
        var current = HttpContext.Current;
        if (current == null)
        {
            return Content(HttpStatusCode.BadRequest, Logger.Error("HttpContext.Current is null"));
        }            

        if (current.Request != null && current.Request.Files != null)
        {
            var file = current.Request.Files.Count > 0 ? current.Request.Files[0] : null;
            if (file != null)
            {
                file.SaveAs(@"C:\Temp\test.csv");
            }
        }
        return Content(HttpStatusCode.BadRequest, Logger.Error("Should not reach here"));
    }

IAuthenticationFilter

public class KeyAuthentication : Attribute, IAuthenticationFilter
{
    // we only want to apply our authentication filter once on a controller or action method so return false:
    public bool AllowMultiple
    {
        get { return false; }
    }

    // Authenticate the user by apiKey
    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {            
        HttpRequestMessage request = context.Request;

        string apiKey = ExtractApiKey(request);
        bool IsValidCustomer = await ValidateKey(apiKey);
        if (IsValidCustomer)
        {
            var currentPrincipal = new GenericPrincipal(new GenericIdentity(apiKey), null);
            context.Principal = principal;                
        }
        else
        {
             context.ErrorResult = new ErrorMessageResult("Missing API Key");
        }
    }

    // We don't want to add challange as I am using keys authenticaiton
    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {  
        return Task.FromResult(0);
    }
}

提取API密钥

public static string ExtractApiKey(HttpRequestMessage request)
{
    if (!request.Headers.TryGetValues("x-api-key", out IEnumerable<string> keys))
return string.Empty;

    return keys.First();
}

1 个答案:

答案 0 :(得分:0)

解决方案是在@Alfredo评论的web.config中包括“ targetFramework = 4.5”,并在https://stackoverflow.com/a/32338414/3973463中提供更多详细信息