如何在django rest框架中使用令牌进行身份验证

时间:2015-04-15 11:17:54

标签: django angularjs rest django-rest-framework

我正在学习使用token来验证angular.js前端的用户。

我正在使用下面的包(对Django REST Framework的JSON Web令牌认证支持)

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

我已经实现了所有设置,并且示例卷曲请求工作正常。

现在我有一个带有angularjs的登录页面,它会发布到休息端点,如下面的代码所示:

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

现在当我发布电子邮件和密码然后在回复中我得到了像这样的成功标记

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

现在因为我对代币知之甚少,我想知道接下来该怎么办?我的意思是在获得令牌之后如何记录用户并将该用户置于角度为userObject的某些内容中。

2 个答案:

答案 0 :(得分:2)

您必须在访问登录内容的每个请求中作为Authorization标头传递令牌。您可以使用$ https默认标头执行此操作。

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

您还应该在localstorage中保存此值,并在运行的应用程序中设置默认标题,这样当用户返回您的页面时,他们已经登录。就像这样:

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

答案 1 :(得分:0)

如果您收到令牌作为回复,则表示该用户已登录。

要使用该令牌,您应将其添加为后续请求的http标头。

Authorization: JWT <your_token>
相关问题