WebCpi MVC Authentication Example from AngularJs -.net

I have a .Net MVC WebApi application and you are trying to write an interface only in Angularjs. I can get the data through json and manipulate it, but now I need to protect the data and add Base64 authentication to the headers on the server. When I look through some of my .net test pages, I get the corresponding login requesting the user / pass, so I can continue to receive json.

What I don’t know how to do is pass this information (user / pass) in the headers that angular configures in my $ resource. Are there any complete examples that could better show me how to do this? I know that it includes cookies and uses the token that the server transmits, but I do not know how to compose the fragments.

When I get it all together, I hope to publish a complete example of the skeleton of this across all layers (DAL, RESTFUL, test test layer).

So the question is, how do you insert authentication information in the headers on the client when using AngularJS $ resources?

thanks

+5
angularjs authentication asp.net-web-api
source share
1 answer

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

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

Then, if you want to find out if the user is registered or if he got the rights, he simply implements the interceptor. This is a simple factory that you will always enter in responseIntercetors in your configuration block.

This factory will listen for every response from the server and, when implemented, you will check the response status code in case of an error:

401 β†’ not registered 403 β†’ do not allow

factory example:

 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 http responseIntercetors, like this in your con fig block:

 myModule.config(function ($httpProvider) { $httpProvider.responseInterceptors.push('myHttpInterceptor'); }); 

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

factory should be a little different, just refer to this post for more info: AngularJS Intercept all responses in $ http JSON

Hope this helps

+3
source share

All Articles