Spotify 的 Python 社交身份验证:重定向缺少“状态”参数

Bra*_*own 2 python django spotify oauth-2.0 python-social-auth

我正在需要访问用户的 Spotify 帐户的 Django 应用程序中实现 Python Social Auth。身份验证流程中的初始步骤有效:将请求发送到 Spotify 的“/授权”端点,并向用户显示一个模式,解释应用程序将被授权的访问范围。但是,当应用程序的重定向 uri 被请求时 ('/completed/spotify/') 会引发此异常:

AuthMissingParameter at /complete/spotify/
Missing needed parameter state
Request Method: GET
Request URL:    http://127.0.0.1:8000/complete/spotify/
Django Version: 1.8.2
Exception Type: AuthMissingParameter
Exception Value:    
Missing needed parameter state
Exception Location: /Users/brandon/Envs/group_playlist_generator/lib/python2.7/site-packages/social/backends/oauth.py in validate_state, line 86
Python Executable:  /Users/brandon/Envs/group_playlist_generator/bin/python
Python Version: 2.7.9
Python Path:    
['/Users/brandon/dev/group_playlist_generator',
 '/Users/brandon/Envs/group_playlist_generator/lib/python27.zip',
 '/Users/brandon/Envs/group_playlist_generator/lib/python2.7',
 '/Users/brandon/Envs/group_playlist_generator/lib/python2.7/plat-darwin',
 '/Users/brandon/Envs/group_playlist_generator/lib/python2.7/plat-mac',
 '/Users/brandon/Envs/group_playlist_generator/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/brandon/Envs/group_playlist_generator/lib/python2.7/lib-tk',
 '/Users/brandon/Envs/group_playlist_generator/lib/python2.7/lib-old',
 '/Users/brandon/Envs/group_playlist_generator/lib/python2.7/lib-dynload',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/brandon/Envs/group_playlist_generator/lib/python2.7/site-packages']
Run Code Online (Sandbox Code Playgroud)

这个问题可能只是我在 Auth 方面的经验的一个函数,尤其是在 Django 的上下文中。我已经阅读了 PSA 源代码的相关部分,但我不明白这个“状态”参数是如何在 Spotify 和应用程序之间传递的。我看到此参数已添加到对 Spotify 的原始请求中,但我不确定如何确保将其传递回重定向​​ URI 和/或是否还有其他有关“状态”的注意事项,例如将其存储在某处。欢迎任何建议。

Mic*_*lin 5

我已经阅读了 PSA 源代码的相关部分,但我不明白这个“状态”参数是如何在 Spotify 和应用程序之间传递的。

在 oAuth 2.0 中使用授权代码流或隐式授权流时,state可以将可选值附加到授权 URL。如果 astate被发送到 API 提供者,它也会作为重定向的一部分附加在对发出请求的应用程序的响应中。目的state是防止跨站请求伪造(CSRF)攻击。

Spotify的授权指南授权码流:

授权码流和 Spotify 的 Web API

正如您在图像中看到的,状态被发送到#1 中的Spotify 帐户服务,并传递回#3 中的应用程序。此时,应用程序会再次检查该状态是否与#1期间发送的值相同。如果它不是相同的值,则有人试图直接访问应用程序的重定向 URI,而不是从 Spotify 的帐户服务重定向。

我看到这个参数被添加到 Spotify 的原始请求中,但我不确定如何确保它被传递回重定向​​ URI

鉴于您使用的是 Python Social Auth 的 0.2.10 版,state参数在此处读取,并且在此处引发异常,因此看起来该state参数永远不会传回您的应用程序。它不会被传回的唯一原因是它state从未被发送到 Spotify 的帐户服务。请调试并仔细检查它state是响应查询参数的一部分,也是请求查询参数的一部分。如果请求有一个state,那么state响应中也应该有一个集合。如果 Python Social Auth 允许您选择退出使用状态,我至少会尝试进行故障排除。