6

Tonight i come search some help about how to call a web api hosted in IIS.

Everything work well in local from visual studio to iis express. But strangely, after publish on my IIS server. I always get 401 unauthorized :'(

Here is the code i use and the settings from my IIS server. I will be very grateful if somebody can help me. Thank you

**

The controller and the function i try to call (with basic authentication attribute)

**

    [HttpGet]
    [ActionName("Get_UserID")]
    [IdentityBasicAuthentication]
    [Authorize]
    public HttpResponseMessage Get_UserID(string userName)
    {
        HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.Created);
        try
        {
            var user = Membership.GetUser(userName, false);
            if (user != null)
            {
                res = Request.CreateResponse(HttpStatusCode.OK, (Guid)user.ProviderUserKey);
            }
            else
            {
                res = Request.CreateResponse(HttpStatusCode.ExpectationFailed);
                res.Content = new StringContent("Error");
                res.ReasonPhrase = "UserName not find in the database";
            }
        }
        catch (Exception exc)
        {
            //Set the response message as an exception
            res = Request.CreateResponse(HttpStatusCode.InternalServerError);
            res.Content = new StringContent("Exception");
            res.ReasonPhrase = exc.Message;
        }
        return res;
    }

**

Client side - How i call the web api and build my httpClient

**

    public static async Task<HttpResponseMessage> RequestStart(string requestUrl, string webApiUrlBase = Globals.WebApi_Url, bool IsAuthenticateMemberRequest = false)
    {
        if (webApiUrlBase == null)
        {
            webApiUrlBase = Globals.WebApi_Url;
        }
        var response = new HttpResponseMessage(HttpStatusCode.Created);

        using (var client = new HttpClient())
        {
            if (IsAuthenticateMemberRequest)
            {
                string strToEncode = ApplicationData.Current.LocalSettings.Values["userName"].ToString() + ":" + ApplicationData.Current.LocalSettings.Values["password"].ToString();
                var authenticationBytes = Encoding.ASCII.GetBytes(strToEncode);

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                Convert.ToBase64String(authenticationBytes));
            }
            client.BaseAddress = new Uri(Globals.WebApi_Url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            response = await client.GetAsync(requestUrl);
        }

        return response;
    }

**

IIS Configuration (appPool => NetworkServices - integrate)

** enter image description here

**

Fiddler Debug

** enter image description here

Mehdi Bugnard
  • 3,889
  • 4
  • 45
  • 86

1 Answers1

10

Finally after search many times , many houres by myself. I find the solution. We should never enable Basic Authentication.... I know it's weird ^^ But if you want to use your custom basic authentication. Just disabled the Basic Authentication on IIS and everything goes well.

Mehdi Bugnard
  • 3,889
  • 4
  • 45
  • 86
  • You are a genius man, I spent 2 days trying to fix it. following other SO answers about folder permissions and stuff like that, but this was the only thing that worked for me. Thanks!!!! – Ibrahim D. Aug 05 '18 at 04:30
  • I'm happy to know , i help somebody with my answer ^^ @Ibrahim D. – Mehdi Bugnard Sep 04 '18 at 07:23
  • I have same problem, but i tried change to disabled Basic Authentication, it dont working :( – Mario Villanueva Dec 17 '19 at 14:43
  • Yes! Thank you! I was stuck on this problem for hours. But this totally makes sense now. By turning on Basic Auth in IIS, I was telling IIS that it is the one that should authenticate requests with Basic Auth headers. But if IIS can't auth the user it rejects them. Since my application is providing the auth logic (with a DB lookup), then IIS should not and can not, so it needs to be disabled in IIS. See related: https://stackoverflow.com/a/5373530/579148 – jwatts1980 Jan 21 '20 at 04:58