AngularJs -.net MVC WebApi Authentication example

前端 未结 1 1222
借酒劲吻你
借酒劲吻你 2021-02-06 15:08

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

1条回答
  •  情歌与酒
    2021-02-06 15:32

    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

    0 讨论(0)
提交回复
热议问题