2017-04-26 33 views
1

檢索訪問令牌,我提出以下要求:無需人工複製

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

檢索訪問令牌。此網址導致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 
+0

鏈接到API文檔和oauth:https://vk.com/dev/access_token – jackdawrites

+0

難道你不能改變redirect_uri嗎?通常的做法是打開一個本地web服務器(比如在'localhost:5000'上)並重定向用戶,然後一旦收到該令牌就停止服務器。 –

+0

@Rawing謝謝,我會盡力的。 – jackdawrites

回答

0

其中您收到AUTH_CODE然後使用這個代碼來檢索您的access_token可以使用授權碼流。

獲取auth_code和access_tokens只是POST請求到OAuth服務器。

在你的代碼RESPONSE_TYPE應該是代碼來獲取授權碼,然後用這個代碼來檢索acccess_token

請參閱本https://vk.com/dev/auth_sites。一般來說,這個流量在任何OAuth提供者上都是一樣的。

+0

但獲取access_token的代碼也在url中提供,只能通過瀏覽器的地址欄訪問,因爲我使用https://oauth.vk.com作爲redirect_uri。我的問題是我是否可以從url中獲取這段代碼? – jackdawrites

+0

是的,有一些方法可以實現這一點。一種方法是使用python創建一個httpserver,在端口上偵聽ex:localhost:8080。完成身份驗證後,將redirect_uri指向localhost:8080。一旦你在那裏重定向,你可以從查詢字符串參數中獲取代碼。如果使用response_type = access_token直接檢索access_token,則可以使用上面的相同片段將請求發佈到服務器,並在python代碼中獲取access_token。 –