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



我正在使用Spotify API开发一款应用程序,但我对这一切都有点陌生。我正在尝试获取带有代码交换验证密钥的授权代码(PKCE((https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-具有用于代码交换的验证密钥的代码流(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)

设置web服务器

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

我已经编写了一个SpotifyWebneneneba API客户端,其内部可能对您的研究有用。例如,可以使用Flask构建服务器。主要原理是使用一个端点(即/login(将用户重定向(适用于me浏览器的代码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)

最新更新