user3214546 user3214546 - 18 days ago 6
AngularJS Question

How can I authenticate with tokens in django rest framework

I'm learning to use token to authenticate users in angular.js front end.

I'm using below package(JSON Web Token Authentication support for Django REST Framework)

https://github.com/GetBlimp/django-rest-framework-jwt

I have implemented all settings and sample curl request is working fine.

Now I have login page with angularjs which posts to rest endpoint as shown in below code:

$http
.post('/api-token-auth/', {email: $scope.account.email, password: $scope.account.password})
.then(function(response) {
// assumes if ok, response is an object with some data, if not, a string with error
// customize according to your api
if ( !response.account ) {
$scope.authMsg = 'Incorrect credentials.';
}else{
$state.go('dashboard');
}
}, function(x) {
$scope.authMsg = 'Server Request Error';
});


Now when I post email and password then in the response I get successful token like this

{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNhbXBsZUBzYW1wbGUuY29tIiwidXNlcl9pZCI6MSwiZW1haWwiOiJzYW1wbGVAc2FtcGxlLmNvbSIsImV4cCI6MTQyOTA5NjM5N30
.w0XV1kArTyZY9iCPyr2LmRzToD9iOgYlMVCoXmdOJ1A"}


Now as I don't know much about tokens, I want to know what should I do next? I mean after getting token how can I log the user in and put that user in some
userObject
in angular.

Answer

You must pass the token as you Authorization header in every request where you access logged in content. You can do this by using $https default headers.

   $http
   .post('/api-token-auth/', {email: $scope.account.email, password: $scope.account.password})
   .then(function(response) {
    ...
    } else {
        localStorage.setItem('myApp.token',response.token);
        $http.defaults.headers.common.Authorization = 'Bearer ' + response.token
        $state.go('dashboard');
    }
    ...

You should also save this value in localstorage and set the default header in you apps run, so that when a user comes back yo your page they are already logged in. Like this:

angular.module('myApp').run(function($http) {
    $http.defaults.headers.common.Authorization = 'Bearer ' + localStorage.getItem('myApp.token')
});