401 Unauthorized error when accessing webapi from angular

All we need is an easy explanation of the problem, so here it is.

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:

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply