你有这个工作吗?如果没有,这就是我所做的。希望对您有所帮助。
我的设置:
- 带有 Postgres 的 Django
- 用于 REST API 实现的 Django Rest 框架
- 用于社交身份验证的 Python Social Auth (PSA)(目前使用 Google+ 库)
- 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 访问社交身份验证令牌。干杯!