Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

401 Unauthorized error when accessing webapi from angular

I need to capture a user's domain\username when they access my webapi app. On my dev machine I have my webapi at localhost:10570 and my angularjs website which makes calls to the webservice at localhost:34575.

If I make a call directly to my webapi app everything works fine. I can see the users domain and username and the service returns the requested data as JSON. But if I access my angularjs site and angular makes the call to webapi then I get 401 unauthorized for every call against the service.

In my WebApi app's web.config I have:

<system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <authentication mode="Windows" />
  </system.web>
  <system.webServer>
    <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://localhost:34575" />
    <add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" />
    <add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With, Authorization, name" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</system.webServer>

I have this in IIS Express for Visual Studio 2015's applicationhost.config file:

<location path="MyNamespace.WebAPI">
    <system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="true" />
                <anonymousAuthentication enabled="false" />
            </authentication>
        </security>
    </system.webServer>
</location>

My angularjs site is part of the same solution at "MyNamespace.Client".

Why does accessing the web service directly work fine, but accessing it via the angular app fail?

like image 696
Legion Avatar asked Aug 26 '16 16:08

Legion


1 Answers

I didn't realize you have to tell Angular to send your credentials to the server. I just had to change my API calls from:

$http.get(url);

to

$http.get(url, { withCredentials: true });
like image 92
Legion Avatar answered Sep 20 '22 19:09

Legion