简体   繁体   English

Spotify授权码流程返回的响应不完整

[英]Spotify Authorization Code Flow returns incomplete response

I have a django server, and I wish to perform the spotify Authorization code flow. 我有一台django服务器,我希望执行Spotify授权代码流程。

Here is a basic skeleton I have created: 这是我创建的基本骨架:

  • The user opens the spotify/login url. 用户打开spotify/login URL。
  • The SpotifyLoginView redirects them to https://accounts.spotify.com/authorize url. SpotifyLoginView将它们重定向到https://accounts.spotify.com/authorize网址。
  • The spotify servers callback to the spotify/callback endpoint. Spotify服务器回调到spotify/callback端点。
  • The SpotifyCallbackView makes a POST request to https://accounts.spotify.com/api/token to get the auth token. SpotifyCallbackViewhttps://accounts.spotify.com/api/token发出POST请求以获取身份验证令牌。

urls.py urls.py

urlpatterns = [
    path(
        "spotify/callback", views.SpotifyCallbackView.as_view(), name="spotify callback"
    ),
    path("spotify/login", views.SpotifyLoginView.as_view(), name="spotify login"),
]

views.py views.py

def build_authorize_url(request):
    params = {
        "client_id": "<my client id>",
        "response_type": "code",
        "redirect_uri": request.build_absolute_uri(
            reverse("spotify callback")
        ),
        "scope": " ".join(
            [
                "user-library-read",
                "user-top-read",
                "user-read-recently-played",
                "playlist-read-private",
            ]
        ),
    }
    print(params)

    url = (
        furl("https://accounts.spotify.com/authorize")
        .add(params)
        .url
    )
    print(url)

    return url


AUTH_HEADER = {
    "Authorization": "Basic "
    + base64.b64encode(
        "<my client id>:<my client secret>".encode()
    ).decode()
}


def handle_callback(request):
    code = request.GET["code"]

    response = requests.post(
        "https://accounts.spotify.com/api/token",
        data={
            "grant_type": "client_credentials",
            "code": code,
            "redirect_uri": request.build_absolute_uri(
                reverse("spotify callback")
            ),
        },
        headers=AUTH_HEADER,
    )

    return response.json()


class SpotifyLoginView(RedirectView):
    query_string = True

    def get_redirect_url(self, *args, **kwargs):
        return build_authorize_url(self.request)


class SpotifyCallbackView(TemplateView):
    template_name = "success.html"

    def get(self, request, *args, **kwargs):
        print(spotify.handle_callback(request))

        return super().get(request, *args, **kwargs)

However, the response returned by spotify doesn't contain the scope and refresh_token ! 但是,spotify返回的响应不包含scoperefresh_token

So for these params: 因此,对于这些参数:

{'client_id': '<my client id>', 'response_type': 'code', 'redirect_uri': 'http://127.0.0.1:8000/spotify/callback', 'scope': 'user-library-read user-top-read user-read-recently-played playlist-read-private'}

which translate to this url: 转换为以下网址:

https://accounts.spotify.com/authorize?client_id=<my client id>&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fspotify%2Fcallback&scope=user-library-read+user-top-read+user-read-recently-played+playlist-read-private

All I get back is: 我得到的是:

{'access_token': '<my acess token>', 'token_type': 'Bearer', 'expires_in': 3600, 'scope': ''}

While the docs suggest that I should get this: 虽然文档建议我应该得到这个:

{
   "access_token": "NgCXRK...MzYjw",
   "token_type": "Bearer",
   "scope": "user-read-private user-read-email",
   "expires_in": 3600,
   "refresh_token": "NgAagA...Um_SHo"
}

Furthermore, If I try using that access token, I get a 401 HTTP error back. 此外,如果尝试使用该访问令牌, 401返回401 HTTP错误。

$ curl -H "Authorization: Bearer <my acess token>" https://api.spotify.com/v1/me


{
  "error" : {
    "status" : 401,
    "message" : "Unauthorized."
  }
}   

What's going on here? 这里发生了什么?

You have to use "authorization_code" as grant_type when making POST request to https://accounts.spotify.com/api/token in order to get an initial access token. https://accounts.spotify.com/api/token发出POST请求时,必须使用“ authorization_code”作为grant_type以获得初始访问令牌。 In your handle_callback() method: 在您的handle_callback()方法中:

 response = requests.post(
    "https://accounts.spotify.com/api/token",
    data={
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": request.build_absolute_uri(
            reverse("spotify callback")
        ),
    },
    headers=AUTH_HEADER,
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 授权代码流中的错误请求 Spotify - Bad Request at Authorization Code Flow Spotify Spotify API {&#39;error&#39;: &#39;invalid_client&#39;} 授权代码流 [400] - Spotify API {'error': 'invalid_client'} Authorization Code Flow [400] Spotify API 授权代码流失败({'error':'invalid_grant','error_description':'无效授权代码'}) - Spotify API Authorization Code Flow failing ({'error': 'invalid_grant', 'error_description': 'Invalid authorization code'}) 通过桌面应用程序完成Spotify授权代码流,无需使用浏览器 - Completing Spotify Authorization Code Flow via desktop application without using browser Python(请求库)ETL:Spotify API“授权代码流”-请求访问令牌问题 - Python (requests library) ETL: Spotify API "Authorization Code Flow" - Request Access Token Problem Spotify API 授权代码流错误:“缺少 grant_type 参数”(Python) - Spotify API authorization code flow error: "grant_type parameter is missing" (Python) Spotify 授权码流程:无法进入初始用户登录,内部服务器错误 - Spotify Authorization code Flow: Can't get to initial user login, Internal Server Error spotipy授权代码流程 - spotipy authorization code flow Spotify授权代码-获取令牌[控制台应用程序] - Spotify authorization code - get token [ console application ] Spotify API(获取授权码)使用Python - Spotify API (Obtaining Authorization Code) using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM