首页 > 解决方案 > python:如何从桌面应用程序重定向到url,等待用户接受授权并获取授权码

问题描述

我正在使用 Spotify API 开发一个应用程序,但我对这一切有点陌生。我正在尝试使用用于代码交换的证明密钥 (PKCE) 获取授权代码(https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof- key-for-code-exchange-pkce)我的问题是如何将用户重定向到query他必须接受授权的地方,并使我的应用程序等到用户点击接受。当他这样做时,用户将被重定向,并且该新 URL(如文档所述)将包含我需要的授权代码,然后将其交换为授权令牌。

到目前为止,这是我获取该授权码的功能:

def get_auth_code(self):
    code_challenge = self.get_code_challenge_PKCE()
    scopes_needed = "user-read-email%20user-read-private%20playlist-read-collaborative%20playlist-modify-public%20playlist-read-private%20playlist-modify-private%20user-library-modify%20user-library-read"

    endpoint = "https://accounts.spotify.com/authorize"
    query = f"{endpoint}?client_id={self.client_ID}&response_type=code&redirect_uri={self.redirect_uri}&scope={scopes_needed}&code_challenge_method=S256&code_challenge={code_challenge}"
    webbrowser.open(query)

标签: pythonauthenticationoauth-2.0authorizationspotify

解决方案


设置一个网络服务器。

要以编程方式提取访问令牌,您需要一个 Web 服务器来在用户登录 Spotify(您将他们重定向到)后处理重定向。现在这个服务器可以是用户将 URI 粘贴到终端上的输入字段,但显然这对于​​用户体验来说并不理想。它为许多错误留下了空间。

我编写了一个 Spotify Web API 客户端,它的内部结构可能对您有用。例如,您可以使用 Flask 来构建服务器。主要原则是使用一个端点(即/login)将用户重定向(307为我工作的代码浏览器不会记住它)到一个回调(即/callback),它接收code您可以请求访问令牌的参数。

我知道,在本地实施 OAuth2 可能有点麻烦。在我的库中,我还制作了一个类似的函数,你正在使用 构建webbrowser,但它确实有手动复制粘贴的怪癖。要使用功能,您可以为简洁起见定义自己,其要点是:

verifier = secrets.token_urlsafe(32)  # for PKCE, not in my library yet
url = user_authorisation_url(scope, state, verifier)

# Communicate with the user
print('Opening browser for Spotify login...')
webbrowser.open(url)
redirected = input('Please paste redirect URL: ').strip()

code = parse_code_from_url(redirected)
state_back = parse_state_from_url(redirected)
assert state == state_back  # For that added security juice
token = request_user_token(code, verifier)

推荐阅读