Dev Aggarwal
Dev Aggarwal

Reputation: 8516

Spotify Authorization Code Flow returns incomplete response

I have a django server, and I wish to perform the spotify Authorization code flow.

Here is a basic skeleton I have created:

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

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!

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.

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


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

What's going on here?

Upvotes: 0

Views: 1166

Answers (1)

zypox
zypox

Reputation: 176

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. In your handle_callback() method:

 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,
)

Upvotes: 3

Related Questions