如何将HttpAuthenticationContext.Errorcontext设置为Unauthorized

时间:2017-04-15 07:44:23

标签: c# asp.net asp.net-web-api

我正在尝试按照本教程:http://bitoftech.net/2014/12/15/secure-asp-net-web-api-using-api-key-authentication-hmac-authentication/

如何使用HMAC保护webapi。它在教程代码的某处提供:

  public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var req = context.Request;

        if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
        {
            var rawAuthzHeader = req.Headers.Authorization.Parameter;

            var autherizationHeaderArray = GetAutherizationHeaderValues(rawAuthzHeader);

            if (autherizationHeaderArray != null)
            {
                var APPId = autherizationHeaderArray[0];
                var incomingBase64Signature = autherizationHeaderArray[1];
                var nonce = autherizationHeaderArray[2];
                var requestTimeStamp = autherizationHeaderArray[3];

                var isValid = isValidRequest(req, APPId, incomingBase64Signature, nonce, requestTimeStamp);

                if (isValid.Result)
                {
                    var currentPrincipal = new GenericPrincipal(new GenericIdentity(APPId), null);
                    context.Principal = currentPrincipal;
                }
                else
                {
                    context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
                }
            }
            else
            {
                context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
            }
        }
        else
        {
            context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
        }

        return Task.FromResult(0);
    }

我当然复制了它,但是mvc不知道这些参数有任何未经授权的结果。因此,此行会出错:context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);

我无法弄清楚如何回馈正确的结果。有谁知道吗?

1 个答案:

答案 0 :(得分:0)

我使用了错误的命名空间。应为using System.Web.Http.Results;