簡體   English   中英

AngularJS中的授權標頭不起作用

[英]Authorization header in AngularJS not working

我正在為我的API使用Django REST令牌認證。

我發布了憑證以獲得令牌端點。 但是,當我嘗試以正確的方式設置標頭時,它始終以http 401錯誤響應。 我嘗試使用curl -X GET http://127.0.0.1:8000/events/ -H 'Authorization: Token 4d92d36768ca5d555b59cf68899eceab39c23704 ' ,它確實起作用了! 這是我的代碼:

app.controller('HomeController', ['$scope','$http', function($scope,$http) {
    $scope.username = '';
    $scope.password = '';
    $scope.submitLogin = function () {
        var credentials = {
            username : $scope.username,
            password : $scope.password,
        };

        var req = $http.post('http://127.0.0.1:8000/api-token-auth/', credentials);
        req.success(function(data, status, headers, config) {
            $scope.token = data.token;
            var str1 = 'Token ';
            $scope.tokenheader = str1.concat($scope.token);
            $http.defaults.headers.common.Authorization = $scope.tokenheader;
        });
        req.error(function(data, status, headers, config) {
            alert( "failure message: " + JSON.stringify({data: data}));
        });
    };
    $scope.getEvents = function () {
        var req = {
            method: 'GET',
            url: 'http://127.0.0.1:8000/events/',
        }
        $http(req).then( 
           function() {
                       console.log('succes')
           }, 
           function(){
                       console.log('fail') 
        });
    };
}]);

chrome開發工具中的錯誤消息:

 XMLHttpRequest cannot load http://127.0.0.1:8000/events/. Response for preflight has invalid HTTP status code 401 

我如何擺脫這個401錯誤?

編輯:我只是發現錯誤在於我的API上未安裝CORS。 我在Chrome中使用了CORS插件,該插件可用於api的身份驗證部分,但不能用於事件url!

您需要將Token添加到標題中:

get($http, "/some_url", {headers: {"Authorization": "Token " + $your_token}}
    ....
    ....
);

響應碼401表示未授權。 如果您使用的是基於令牌的身份驗證,則在失敗的情況下將為403(禁止)。 因此,我的猜測是,用戶名/密碼會令人困惑。 在您的curl示例中,您沒有使用它們。

您是否檢查過令牌實際上已添加到您的請求中?

例如,您可以使用Chrome開發者工具來執行此操作。

就個人而言,我更喜歡使用$ httpprovider.interceptor,如以下所述:

angularjs $ httpProvider攔截器文檔

這樣可以確保令牌始終出現在任何呼叫中。

如果您要訪問多個API,則應考慮添加以下內容:

           $httpProvider.interceptors.push(['$q', '$location', '$log', 'loginService', 'restHelperService',
            function ($q, $location, $log, loginService, restHelperService) {
                return {
                    request: function (config) {
                        // check if the request comes with an url
                        if (config.url) {
                            // check that the call is to the REST api, if yes add token
                            if (restHelperService.isRestCall(config.url)) {
                                // add auth header or revert to login
                                if (loginService.userIsLoggedIn()) {
                                    config.headers = config.headers || {};
                                    config.headers.Authorization = 'Token ' + loginService.getToken().token;
                                } else {
                                    $location.path('/login');
                                }
                            }
                        }
                        return config;
                    },
                    responseError: function (response) {
                        if (response.status === 401 || response.status === 403) {
                            // clear auth token if the REST call failed with the current token
                            if (response.config && response.config.url && restHelperService.isRestCall(response.config.url)) {
                                $log.debug(" restCall failed due to bad credentials, resetting credentials");
                                loginService.resetCredentials();
                                $location.path('/login');
                            }
                        }
                        return $q.reject(response);
                    }
                };
            }]);
    }])

這樣可以避免在您開始將令牌添加到不需要令牌的API調用中時出現的問題。 此外,該代碼還確保如果憑據無效,則用戶將被自動重定向到登錄頁面。

在示例中,我使用了兩個附加服務。 管理令牌的loginService和管理REST框架的url的restHelperService。

我建議您這樣做,否則將很難從控制器外部訪問憑據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM