AngularJS authorization header does not work

I am using Django REST token authentication for my API.

I sent my credentials to get the marker endpoint. However, when I try to configure the header correctly, it continues to respond to the http 401 error. I tried it with curl -X GET http://127.0.0.1:8000/events/ -H 'Authorization: Token 4d92d36768ca5d555b59cf68899eceab39c23704 ' , and it really is works! This is my code:

 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') }); }; }]); 

And the error message in chrome dev tools:

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

How to get rid of this error 401?

Edit: I just found out that the error was that I did not have CORS installed on my API. I used the CORS plugin in chrome, which worked for the authentication part of my api, but not for the URLs of my events.

+1
source share
2 answers

Have you verified that the token has actually been added to your request?

You can do this, for example, using the Chrome Developer Tools.

Personally, I prefer to use the $ httpprovider.interceptor as described in:

angularjs $ httpProvider documentation interceptor

This ensures that tokens are always present on any call.

If you are accessing multiple APIs, you should add something like:

  $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); } }; }]); }]) 

This avoids the problems that arise when adding a token to API calls that do not expect them. The code also ensures that the user is automatically redirected to the login page if the credentials are invalid.

In the example, I use two additional services. The loginService service, which manages tokens, and the RestHelperService, which manages the URLs of the REST structure.

I would recommend doing the same thing as otherwise it would be difficult to access credentials from outside your controller.

+1
source

You need to add the token in the headers:

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

Response code 401 means Unauthorized. If you use token-based authentication, then in case of failure it will be 403, Forbidden. Therefore, I assume that this is the username / password that is messing with it. In your curl example, you are not using them.

+1
source

Source: https://habr.com/ru/post/1235700/


All Articles