AngularJs MVC WebApi Authentication example

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

I have a .Net MVC WebApi app and trying to write the front end exclusively in Angularjs. I am able to get data via json and manipulate it but I now need to secure the data and have added Base64 authentication into the headers on the server. When I browse to some of my .net view test pages, I get the appropriate login box asking for user/pass so I can continue to get the json.

What I don’t know how to do is pass this info (user/pass) in the headers that angular is setting up in my $resource. Is there any complete examples that might better show me how to do this? I know it involves cookies and using the token the server passes back but I don’t know how to put the pieces together.

When I get all this together I hope to post a complete skeleton example of this thru all the layers (DAL, RESTFUL, console test layer).

So the question is – how do you insert the authentication info into the headers on the client when using AngularJS $resources?


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

If you put a cookie in the header on server side AngularJS will send this cookie all time.. U have nothing to do.

If you want to pass the token in Header not in cxookie on Angular side just do this : $httpProvider.defaults.headers.common['X-Auth'] = yourKey; in your config block.

Then if you want to know if the user is logged or if he’s got the rights just implements an interceptor. It’s a simple factory that you’ll push in responseIntercetors always in your config block.

This factory will listen each response from the server and on his implementation you’ll check the status code of the response in error case :

401 –> not logged
403 –> not authorize

example of factory :

myModule.factory('myHttpInterceptor', function ($q) {
    return function (promise) {
        return promise.then(function (response) {
            // do something on success              
            return response;
        }, function (response) {
            // do something on error
            //check status 401 or 403
            return $q.reject(response);

Then put your factory in the http responseIntercetors like this in your con fig block:

myModule.config(function ($httpProvider) {

Just keep in mind this solution is deprecated in AngularJS 1.1.4 (still unstable) …

The factory have to be a little different just refer to this post for more information : AngularJS Intercept all $http JSON responses

Hope it helps

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

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

Leave a Reply