【问题标题】:Retrieving access token without manual copying无需手动复制即可检索访问令牌
【发布时间】:2017-11-15 00:53:45
【问题描述】:

我提出以下要求:

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

【问题讨论】:

  • API 文档和 oauth 的链接:vk.com/dev/access_token
  • 你不能改变redirect_uri吗?通常的程序是打开一个本地网络服务器(比如localhost:5000)并将用户重定向到那里,然后在收到令牌后停止服务器。
  • @Rawing 谢谢,我会试试的。

标签: python oauth python-requests vk


【解决方案1】:

您可以使用授权码流程,您可以在其中收到 Auth_code,然后使用此代码检索 access_token。

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

在您的代码中 response_type 应该是获取身份验证码然后使用此代码检索访问令牌的代码

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

【讨论】:

  • 但是获取 access_token 的代码也提供在 url 中,因为我使用 oauth.vk.com 作为 redirect_uri,所以只能通过浏览器的地址栏访问。我的问题是我是否可以从网址中获取此代码?
  • 是的,有一些方法可以实现这一点。一种方法是使用 python 创建一个 httpserver,它监听一个端口,例如:localhost:8080。完成身份验证后,将 redirect_uri 提供给 localhost:8080。重定向到那里后,您可以从查询字符串参数中获取代码。如果您使用 response_type=access_token 直接检索 access_token,那么您可以使用上面相同的 sn-p 向服务器发布请求并在 python 代码中获取 access_token。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多