AngularJS - store basic authentication on login

后端 未结 5 1839
忘掉有多难
忘掉有多难 2021-01-18 07:35

I\'m banging my head on a wall with this - I\'m relatively new to working with APIs and have yet to do anything that requires authentication.

I\'m stuck with sendin

5条回答
  •  -上瘾入骨i
    2021-01-18 08:13

    Call this once you have a token:

    $httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
        if (authToken !== null) {
            var headers = headersGetter();
            angular.extend(headers, 'Authorization: basic ' + authToken);
        }
    
        return data;
    });
    

    EDIT: Have not tested it, but it should be something like:

    myApp.provider('authService', function() {
    
        var authToken = null;
    
        this.$get = ['$httpProvider', function($httpProvider) {
            return {
                configure: configure,
                setAuthToken: setAuthToken
            }
        };
    
        function configure() {
            $httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
                if (authToken !== null) {
                    var headers = headersGetter();
                    angular.extend(headers, 'Authorization: basic ' + authToken);
                }
    
                return data;
            });
        }
    
        function setAuthToken(token) {
            authToken = token;
        }
    });
    

    and then inject authService to your app config and call authService.configure()

提交回复
热议问题