我正在使用 Django REST Framework 创建一个社交媒体 Web 应用程序,并在前端和 postgreSQL 上做出反应,但我在考虑如何存储用户的 Spotify 身份验证令牌时遇到了困难。问题是令牌存储在下面的这个 spotify_callback 视图中,我无法将用户与令牌关联起来。
class spotify_callback(APIView):
# permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
code = request.GET.get('code')
response = post('https://accounts.spotify.com/api/token', data={
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
}).json()
access_token = response.get('access_token')
token_type = response.get('token_type')
refresh_token = response.get('refresh_token')
expires_in = response.get('expires_in')
error = response.get('error')
update_or_create_user_tokens(
self.request.user, access_token, token_type, expires_in, refresh_token)
return redirect('http://localhost:3000/')
我提取 Spotify 身份验证流程的来源在他们的应用程序中没有任何用户身份验证,因此他们能够利用 request.session。但是,根据我的理解,由于用户身份验证,我无法使用会话,所以我一直在使用
permission_classes = (IsAuthenticated,)
...
self.request.user
获取发出请求的用户的电子邮件。所以这就是我遇到麻烦的地方。因为此请求是在用户输入有效的 Spotify 凭据而不是用户之后由 Spotify API 发出的,所以我无法使用上面的两行,因此无法跟踪令牌属于哪个用户。
我尝试使用 Django 会话一段时间,然后得出结论,我无法将它们与经过身份验证的用户一起使用。我还尝试了我所说的权限类,但它不起作用,因为它不是经过身份验证的用户发出请求。
无需登录即可在前端获取 Spotify 令牌,然后将这些令牌发送到后端