简体   繁体   中英

Getting Unauthorized : Access denied on web api

So a while ago I created a web api to log who is using all our application.

In dev, it works fine. It prod, it worked for a month and all of suddenly stopped working. To the best of my knowledge nothing has changed on the prod site.

If I hit the webapi directly, it works. It's when I'm using a site calling the api then the problem occurs.

I've checked, the IIS settings between dev and prod are the same. (Both windows authentication and it's advanced settings are the same, anonymous is off.)

Both sites are using the same application pool (the client site and api site). With domain accounts as the identity.

I've done file compares between dev and prod of the web.config and applicationhost.config and nothing seems out of the ordinary.

I'm running out of ideas of what to check.

Web api controller

[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;
        }
    }

Code to hit the api on the client

/// <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);
                }
        }

Error message

<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>

Here are sections of the 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>

dev IIS log

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

Prod IIS log - It seems like the permissions are being sent..

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

If you are running out of ideas I'd recommend going through David Wang's excellent checklist:

HOWTO: Diagnose 401.x HTTP errors on IIS

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM