Legion Legion - 1 year ago 279
AngularJS Question

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

and my angularjs website which makes calls to the webservice at

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:

<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<authentication mode="Windows" />
<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" />

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

<location path="MyNamespace.WebAPI">
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />

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?

Answer Source

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, { withCredentials: true });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download