未经授权:在网络API上拒绝访问

时间:2016-07-15 14:51:47

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

前一段时间我创建了一个web api来记录谁在使用我们所有的应用程序。

在开发中,它运行正常。它刺激,它工作了一个月,所有突然停止工作。据我所知,产品网站上没有任何变化。

如果我直接点击webapi,它就可以了。当我使用调用api的站点时,问题就出现了。

我已经检查过,dev和prod之间的IIS设置是一样的。 (Windows身份验证和它的高级设置都是相同的,匿名是关闭的。)

两个站点都使用相同的应用程序池(客户端站点和api站点)。以域帐户作为身份。

我已经完成了web.config和applicationhost.config的dev和prod之间的文件比较,似乎没有任何异常。

我已经没有检查什么的想法了。

Web api控制器

[Authorize]
    public class ValuesController : ApiController
    {
        public string Get(string samAccountName, bool success, string permissionName)
        {
            var returnValue = "Failed";

            if (!string.IsNullOrWhiteSpace(samAccountName) && !string.IsNullOrWhiteSpace(permissionName))
            {
                     // Do my logging (removed all the try catch etc to simplify thing)

                   returnValue = "Success";
            }

            return returnValue;
        }
    }

在客户端点击api的代码

/// <summary>
        /// This method calls a web api get method to log the call of the audit
        /// </summary>
        /// <param name="authorityName">This is the name of the permission to check</param>
        /// <param name="success">This is the flag to determine if the call was successful.</param>
        /// <returns>Returns an Async task</returns>
        private async Task WriteToAuditLogAsync(string authorityName, bool success)
        {
                try
                {
                    using (var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }))
                    {
                        client.BaseAddress = new Uri(GlobalConfiguration.AuditBaseAddress);
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                        var values = string.Format(
                            CultureInfo.InvariantCulture, GlobalConfiguration.AuditApivalue,
                            this.userName.ToUpper(CultureInfo.InvariantCulture),
                            success.ToString(),
                            authorityName.ToUpper(CultureInfo.InvariantCulture));

                        // HTTP GET
                        var response = await client.GetAsync(values, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

                    }
                }
                catch (Exception ex)
                {
                    LogWriter.CriticalError(ex);
                }
        }

错误消息

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>401 - Unauthorized: Access is denied due to invalid credentials.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;} 
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} 
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
 <div class="content-container"><fieldset>
  <h2>401 - Unauthorized: Access is denied due to invalid credentials.</h2>
  <h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>
 </fieldset></div>
</div>
</body>
</html>

以下是web.config

的部分内容
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <customErrors mode="Off" />
    <authentication mode="Windows" />
  </system.web>
  <system.webServer>
    <security>
      <authorization>
        <clear />
        <add accessType="Allow" users="*" />
      </authorization>
    </security>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

开发IIS日志

2016-07-15 14:26:45 10.9.9.9 GET /ApmApi/api/Values samAccountName=somename&success=True&permissionName=somePermission 80 - 10.9.9.9- - 401 2 5 593
2016-07-15 14:26:53 10.9.9.9 GET /ApmApi/api/Values samAccountName=somename&success=True&permissionName=somePermission 80 Domain\AppPool 10.9.9.9- - 200 0 0 7015

生成IIS日志 - 似乎正在发送权限..

2016-07-15 17:09:45 10.9.9.8 GET /ApmApi/api/Values samAccountName=somename&success=True&permissionName=somePermission 80 - 10.9.9.8 - - 401 2 5 546
2016-07-15 17:09:45 10.9.9.8 GET /ApmApi/api/Values samAccountName=somename&success=True&permissionName=somePermission  80 - 10.9.9.8 - - 401 1 3221225581 0

2 个答案:

答案 0 :(得分:0)

如果您的想法不足,我建议您阅读David Wang的优秀清单:

  

HOWTO: Diagnose 401.x HTTP errors on IIS

答案 1 :(得分:0)

确保将Integrated作为应用程序池托管管道模式。