Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs -.net MVC WebApi Authentication example

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?

Thanks

like image 412
Jeff Avatar asked Oct 22 '22 05:10

Jeff


1 Answers

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) {
    $httpProvider.responseInterceptors.push('myHttpInterceptor');
});

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

like image 73
Thomas Pons Avatar answered Oct 24 '22 05:10

Thomas Pons