[Fixed]-Django JWT send token via Angularjs

1👍

you have to send the token in the Authorization header. The token should be JWT <token>, as per documented in django jwt.

Here is the Angularjs based function I have written to show how to sign up, the code is very basic just for understanding you can write a separate service or factory, but for the sake of explaining this seems good.

$scope.registerUser = function(){
        var postDict = $scope.user;
        $http.post('http://127.0.0.1:8000/api/v1'+'/accounts/', postDict).success(function(data){
            $scope.userRegistered = data;
        var authData = {
          username: data.username,
          password: data.password
        };
        $http.post('http://127.0.0.1:8000/api-token-auth/', authData).success(function(data){
          var token = data.token;
          $http({
            method  : 'POST',
            url     : 'http://127.0.0.1:8000/api/v1/auth/login/',
            data    : authData,  // pass in data as strings
            headers : { "Content-Type": "application/json", "Authorization": "JWT "+data.token  }  // set the headers so angular passing info as form data (not request payload)
          })
          .success(function(data){
            console.log(data);
              var userdata = { "username": data.username, "first_name": data.first_name , "token": token , "last_name": data.last_name , "email": data.email};
              $window.localStorage.setItem('userdata', JSON.stringify(userdata));
              $state.go('app.dashboard');
          });
        });
        });
    }

now here we have obtained the token and in the headers property of the $http.post method of the angularjs, we have used this token for login.
This is how you can use Django JWT in Angularjs , also have a look at the django jwt documentation

0👍

You have to send it through a header named Authorization with the value: Token your-token-value.

In AngularJS you can do this through the $httpProvider in the configuration of your module, for instance:

angular.module('mymodule', []).config(function($httpProvider) {
    $httpProvider.defaults.headers.common['Authorization'] = 'Token your-token-value';
});

After you do that, every request made with $http will have this header.

Leave a comment