$http Auth Headers in AngularJS

前端 未结 8 706
闹比i
闹比i 2020-11-30 21:52

I have an angular application that is hitting a node API. Our backend developer has implemented basic auth on the API, and I need to send an auth header in my request.

相关标签:
8条回答
  • I have a service factory that has an angular request interceptor like so:

    var module =  angular.module('MyAuthServices', ['ngResource']);
    
    module
        .factory('MyAuth', function () {
        return {
            accessTokenId: null
        };
    })    
    .config(function ($httpProvider) {
        $httpProvider.interceptors.push('MyAuthRequestInterceptor');
    })
    
    .factory('MyAuthRequestInterceptor', [ '$q', '$location', 'MyAuth',
        function ($q, $location, MyAuth) {
            return {
                'request': function (config) {
    
    
                    if (sessionStorage.getItem('accessToken')) {
    
                        console.log("token["+window.localStorage.getItem('accessToken')+"], config.headers: ", config.headers);
                        config.headers.authorization = sessionStorage.getItem('accessToken');
                    }
                    return config || $q.when(config);
                }
                ,
                responseError: function(rejection) {
    
                    console.log("Found responseError: ", rejection);
                    if (rejection.status == 401) {
    
                        console.log("Access denied (error 401), please login again");
                        //$location.nextAfterLogin = $location.path();
                        $location.path('/init/login');
                    }
                    return $q.reject(rejection);
                }
            }
        }]);
    

    Then on logging in in my login controller I store the accesstoken using this line:

    sessionStorage.setItem('currentUserId', $scope.loginResult.user.id);
    sessionStorage.setItem('accessToken', $scope.loginResult.id);
    sessionStorage.setItem('user', JSON.stringify($scope.loginResult.user));
    sessionStorage.setItem('userRoles', JSON.stringify($scope.loginResult.roles));
    

    This way I can assign the headers to the request on every request made after I log in. This is just the way I do it, and is totally up for criticism, but it appears to work very well.

    0 讨论(0)
  • 2020-11-30 22:45

    In the $http doc you can see that you should set the default headers using $httpProvider:

    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.headers.common['Authorization'] = 'Basic auth';
    }]);
    
    0 讨论(0)
提交回复
热议问题