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

How can I authenticate with tokens in django rest framework

我正在学习使用令牌在 angular.js 前端对用户进行身份验证。

我正在使用以下包(JSON Django REST Framework 的 Web 令牌身份验证支持)

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

我已经实施了所有设置并且示例 curl 请求工作正常。

现在我有了带有 angularjs 的登录页面,其中 posts 用于休息端点,如下面的代码所示:

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

现在,当我 post 电子邮件和密码时,我会在响应中得到这样的成功令牌

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

我现在对token不是很了解,想知道接下来应该怎么做?我的意思是在获得令牌后如何让用户登录并将该用户放入 angular.

中的某个 userObject

如果您收到令牌作为响应,则表示用户已经登录。

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

Authorization: JWT <your_token>

您必须在授权时传递令牌 header 在您访问登录内容的每个请求中。您可以使用 $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');
    }
    ...

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

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