【问题标题】:Django REST to React - getting social auth tokens without passwordDjango REST to React - 无需密码即可获取社交身份验证令牌
【发布时间】:2018-01-03 17:41:45
【问题描述】:

我想向 React 传递有关仅在后端使用社交身份验证(由 social_django 处理)的应用中当前经过身份验证的用户的信息。我所有的用户和用户令牌信息都存储在 django REST 中,要访问令牌,我通常必须向 rest_framework.authtoken 的 gain_auth_token 视图发送 POST 请求。我的 django 根 urls.py 文件如下所示:

...
from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    ...
    url(r'^obtain-auth-token/$', obtain_auth_token),
    ...
]

但是,为了真正获得与我的数据库中的用户关联的身份验证令牌,我需要在我的 POST 请求中提供用户名和密码。社交身份验证会自动创建新用户而无需分配任何密码,那么如何获取这些令牌?

【问题讨论】:

  • 您可以在请求正文中返回令牌并将其分配给 Javascript 变量。

标签: django reactjs django-rest-framework django-rest-auth social-authentication


【解决方案1】:

你有这个工作吗?如果没有,这就是我所做的。希望对您有所帮助。

我的设置

  1. 带有 Postgres 的 Django
  2. 用于 REST API 实现的 Django Rest 框架
  3. 用于社交身份验证的 Python Social Auth (PSA)(目前使用 Google+ 库)
  4. Reactjs 前端

使用<a href="{% url 'social:begin' 'google-plus' %}">Login</a> 登录时,它转换为/login/google-plus/。这不仅获得了 access_token,而且还在您的数据库中创建了一个“社交用户”。在我的案例中,我使用了 oauth 2.0 客户端库,并大致遵循this 方法来获取包含客户端所有详细信息的 google 用户对象。我用更灵活的 ajax 调用替换了上面链接中的表单,让我可以控制访问令牌和其他必要的信息。此处的 ajax 调用确保在数据库中的社交身份验证表中创建社交用户。

<script type="text/javascript">

gapi.load('auth2', function () {
let auth2;

auth2 = gapi.auth2.init({
  client_id: "YOUR CLIENT ID",
  scope: "profile",
  cookie_policy: 'single_host_origin'
});

auth2.then(function () {
  let button = document.getElementById("google-plus-button");

  auth2.attachClickHandler(button, {}, function (googleUser) {
    // Send access-token to backend to finish the authenticate
    // with your application

    let authResponse = googleUser.getAuthResponse();

    $.ajax({
      "type": "POST",
      "url": "/complete/google-plus/",
      "data": {
        "access_token": authResponse.access_token,
        "CSRF": "{% csrf_token %}"
      }
    }).then(function(data){
      console.log(data);
      // Your success code
    }).fail(function(error){
      console.log(error);
    });
  });
 });
});
</script>

获取 access_token 后,您可以将它们存储在浏览器本地存储中,直到用户注销。注销时可以删除它们。

对于我提到的设置,这种方法对我很有效。也不存在用用户名和密码查询/obtain-auth-token的问题。

肯定有兴趣知道是否有其他方法可以从 PSA django 访问社交身份验证令牌。干杯!

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 2016-08-23
    • 2023-04-07
    • 2019-01-18
    • 2016-10-20
    • 2014-01-07
    • 2018-06-18
    • 2023-03-16
    • 2014-10-14
    相关资源
    最近更新 更多