【问题标题】:python: how to redirect from desktop app to url, wait user to accept the authorization and get authorization codepython:如何从桌面应用程序重定向到url,等待用户接受授权并获取授权码
【发布时间】:2020-11-02 08:16:13
【问题描述】:

我正在使用 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)

【问题讨论】:

    标签: python authentication oauth-2.0 authorization spotify


    【解决方案1】:

    设置网络服务器。

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

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

    我知道,在本地实施 OAuth2 可能有点麻烦。在我的库中,我还制作了一个 similar function,您正在使用 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)
    

    【讨论】:

    • 是的,我做了类似的事情,但最后我决定多做一点,创建一个基本的服务器,这样我就可以得到响应,它“有点”工作得很好。仍在进行一些改进
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    相关资源
    最近更新 更多