【问题标题】:How can I authenticate with tokens in django rest framework如何在 django rest 框架中使用令牌进行身份验证
【发布时间】:2015-06-21 07:54:12
【问题描述】:

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

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

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

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

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

$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 角度。

【问题讨论】:

    标签: django angularjs rest django-rest-framework


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢。我无法得到你的第二部分,你说我需要在应用程序运行中放置默认标题。我怎样才能做到这一点。如果使用 ur 行是否意味着下次用户访问经过身份验证的 iurl 时不需要登录
    • 我现在已经更新了答案,登录时在 localstorage 中设置令牌。当您的应用启动并从 localstorage 获取令牌并将其用作默认标头时,运行块将触发,然后是您的用户不应该再登录了! :)
    • 谢谢。有什么方法可以同时获取用户名、用户 ID 等以及令牌作为响应,以便我可以更新有角度的用户对象
    【解决方案2】:

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

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

    Authorization: JWT <your_token>
    

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 2023-03-16
      • 1970-01-01
      • 2021-10-27
      • 2016-09-10
      • 2015-12-19
      • 2014-04-14
      • 1970-01-01
      • 2015-09-16
      相关资源
      最近更新 更多