获取IIS未经授权的html页面而不是Web API未经授权的响应,以获取未经授权的状态

时间:2019-05-27 19:28:14

标签: c# authentication asp.net-web-api iis-10

我在IIS 10(Windows Server 2016)上托管了一个Web API应用程序。该应用程序具有用于登录的API。登录API带有实现IAuthenticationFilter的自定义身份验证过滤器属性。

[RoutePrefix("api/login")]
[AllowUnAuthorized]
[AuthenticationFilter]

public class LoginController : ApiController
{

    [HttpPost]
    public IHttpActionResult Login()
    {
        //Code to return token if passed authentication in the Authentication Filter
    }
 }   

如果登录凭据(用户名和密码)无效,则“身份验证筛选器”属性会在上下文中设置一个ErrorResult,并返回带有响应消息的状态码401(“未授权”)。

public class AuthenticationFilter : Attribute, IAuthenticationFilter
{
    public bool AllowMultiple => false;

    public async Task AuthenticateAsync(HttpAuthenticationContext context, 
    CancellationToken cancellationToken)
    {
        HttpRequestMessage request = context.Request;
        AuthenticationHeaderValue authorization = 
         request.Headers.Authorization;

        if (authorization == null)
        {
            return;
        }
        if (authorization.Scheme != "Basic")
        {
            return;
        }


        Tuple<string, string> credentials = 
        ExtractCredentials(request.Headers);
        if (credentials == null)
        {
            context.ErrorResult = new AuthenticationFailureResult("Invalid 
            credentials", request);                
            return;
        }
        string userName = credentials.Item1;
        string password = credentials.Item2;


        IAuthenticationService 
        service=container.Resolve<IAuthenticationService>();
        var user = service.GetUser(userName, password);
        if (user ==  null)
        {
            context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request);                
            return;
        }

        //Code to set principal if authentication passed
}

这是AuthenticationFailureResult类的代码。

internal class AuthenticationFailureResult : IHttpActionResult
{
    public string ReasonPhrase { get; private set; }

    public HttpRequestMessage Request { get; private set; }

    public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request)
    {
        ReasonPhrase = reasonPhrase;
        Request = request;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Execute());
    }

    private HttpResponseMessage Execute()
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        response.RequestMessage = Request;
        response.ReasonPhrase = ReasonPhrase;
        return response;
    }
}

此代码工作正常,并且返回401状态代码以及原因短语中指定的消息。但是我不知道由于什么变化,API突然返回了IIS通常返回的html页面,并显示消息“ 401-未经授权:由于凭据无效而拒绝访问。” 而不是在验证过滤器中设置的错误响应。请注意,在IISExpress中运行时,相同的API可以按预期工作

我到目前为止所做的事情:

  1. 检查Web.config并验证CustomErrors Mode设置为“ On”
  2. 确保在IIS中的站点的“身份验证”部分中启用了“匿名身份验证”
  3. 已将以下内容添加到Web.config

    <system.webServer>
      <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>
    

奇怪的是,通过身份验证后,网络api返回正确的JSON响应

编辑1:

这是ChallengeAsync方法

public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            var challenge = new AuthenticationHeaderValue("Basic");
            context.Result = new AddChallengeOnUnauthorizedResult(challenge, context.Result);
            return Task.FromResult(0);
        }

AddChallengeOnUnauthorizedResult的实现

public class AddChallengeOnUnauthorizedResult : IHttpActionResult
    {
        public AddChallengeOnUnauthorizedResult(AuthenticationHeaderValue challenge, IHttpActionResult innerResult)
        {
            Challenge = challenge;
            InnerResult = innerResult;
        }

        public AuthenticationHeaderValue Challenge { get; private set; }

        public IHttpActionResult InnerResult { get; private set; }

        public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await InnerResult.ExecuteAsync(cancellationToken);

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                // Only add one challenge per authentication scheme.
                if (!response.Headers.WwwAuthenticate.Any((h) => h.Scheme == Challenge.Scheme))
                {
                    response.Headers.WwwAuthenticate.Add(Challenge);
                }
            }

            return response;
        }
    }

1 个答案:

答案 0 :(得分:0)

解决方案是在Web.config中添加以下两个设置。

 <system.webServer>
            <httpErrors existingResponse="PassThrough" />
            <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>