无需手动复制即可检索访问令牌

Retrieving access token without manual copying

我提出以下要求:

https://oauth.vk.com/authorize?redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&response_type=token&client_id=5842359&v=5.63&scope=friends%2Coffline&display=page

检索访问令牌。此 url 导致 vk.com 上的登录页面(如果尚未登录),然后提示用户授权应用程序,然后重定向到 https://oauth.vk.com/blank.html#access_token={token}&expires_in =0&user_id={id}。因此,要实际检索访问令牌,需要从地址栏中手动复制它。这个程序是官方指定的API。有办法解决这个问题吗?如何仅使用 python 代码获取令牌?

下面是生成 url 的过程:

import requests

def authorize_app(client_id, redirect_uri = None):
'''
    The function generates an url, which redirects to login page (optional, if not logged in) and app authorization. 
'''
if redirect_uri == None:
    redirect_uri = 'https://oauth.vk.com/blank.html' # default callback url
oauth = requests.get('https://oauth.vk.com/authorize', params = {'client_id' : str(client_id), 
                                                                'redirect_uri' : redirect_uri,
                                                                'display' : 'page',
                                                                'scope' : ['friends,offline'], # offline option makes the token permanent
                                                                'response_type' : 'token',
                                                                'v' : 5.63})
return oauth.url

您可以使用接收 Auth_code 的授权代码流程,然后使用此代码检索 access_token。

获取 auth_code 和 access_token 只是对 OAuth 服务器的 POST 请求。

在您的代码中 response_type 应该是获取授权码的代码,然后使用此代码检索 acccess_token

参考这个https://vk.com/dev/auth_sites。通常,此流程在任何 OAuth 提供程序上都是相同的。