【发布时间】:2021-12-30 08:27:24
【问题描述】:
我已将我的 django 项目推送到免费托管网站 pythonanywhere。 该代码在我的本地和网络上都可以正常工作,但不知何故在 instagram 身份验证方面存在问题。
Instagram 使用 oauth2 身份验证系统,在该系统中,当用户允许您的应用程序时,它会将用户重定向到指定的 URI 并在 URL 中附加代码,该代码可进一步用于对用户进行身份验证。
Instagram 不允许本地主机作为有效的重定向 URL,因此在测试中我使用了类似的东西
InstaAuth.html
<script>
history.pushState(null, null, '?code=AQD_4...q6#_');
function reloadThePage() {
window.location.reload();
}
</script>
<button type="submit" class="btn btn-primary" onclick="reloadThePage()">Continue</button>
它改变了 url 的状态,但实际上并没有刷新它。然后我有一个刷新当前页面的按钮,它直接在我的views.py中触发下面的代码并通过request.GET['code']获取代码。
Views.py
>def instaAuth(request):
if 'code' in dict(request.GET).keys():
code = request.GET['code']
print('the given code is', code)
core = instaCore()
user_id, short_lived_access_token = core.code_to_short_access_with_userid(code_string=code)
print(user_id)
obj = InstaModel.objects.get(username=request.user)
obj.instagram_userid = user_id
obj.short_lived_access_token = short_lived_access_token
obj.is_active = True
obj.save()
print('all data saved!')
messages.success(request, "Your instagram is connected!")
return render(request, 'authentication/success.html')
return render(request, 'authentication/instaAuth.html')
当我使用pushState mehod 添加代码并使用按钮刷新页面时,上面的代码工作得非常好。但是当我在我的 web 应用程序中执行相同操作时,授权应用程序然后单击继续按钮,它会通过 KeyError at /instaAuth 'access_token'。
当有人尝试多次使用同一个oauth code 时,通常会发生此错误。当我查看日志时,我在与访问令牌交换 oauth 代码的同一行中发现了错误。我试图查看请求的网络选项卡,但我不确定缺少什么。我使用streamlit 做了类似的事情,效果很好,你可以在这里查看流光应用https://instalogintest.herokuapp.com/
我被困在这个地方,我想要一些不刷新页面的逻辑,或者让 django 知道这个请求来自 Instagram 并使用代码验证用户的方式。强>
【问题讨论】:
标签: python django redirect oauth-2.0 instagram-api