2017-07-12 164 views
0

我正在尋找使用httr包在R中執行簡單的GET請求(來自Aplos API)。我可以通過使用API​​密鑰進行身份驗證來獲取臨時令牌,但是一旦嘗試使用該令牌發出實際的GET請求,就會收到401「令牌無法找到」。將不勝感激任何幫助!先謝謝你。R中的API身份驗證 - 無法將身份驗證令牌作爲標頭

AplosURL <- "https://www.aplos.com/hermes/api/v1/auth/" 
AplosAPIkey <- "XYZ" 
AplosAuth <- GET(paste0(AplosURL,AplosAPIkey)) 
AplosAuthContent <- content(AplosAuth, "parsed") 
AplosAuthToken <- AplosAuthContent$data$token 
#This is where the error occurs 
GET("https://www.aplos.com/hermes/api/v1/accounts", 
    add_headers(Authorization = paste("Bearer:", AplosAuthToken))) 

這是一個Python代碼段由API文檔提供:

def api_accounts_get(api_base_url, api_id, api_access_token): 
    # This should print a contact from Aplos. 
    # Lets show what we're doing. 
    headers = {'Authorization': 'Bearer: {}'.format(api_access_token)} 
    print 'geting URL: {}accounts'.format(api_base_url) 
    print 'With headers: {}'.format(headers) 

    # Actual request goes here. 
    r = requests.get('{}accounts'.format(api_base_url), headers=headers) 
    api_error_handling(r.status_code) 
    response = r.json() 
    print 'JSON response: {}'.format(response) 
    return (response) 

回答

0

在Python示例中,auth代碼塊的返回是作爲BASE64的api_bearer_token解碼和RSA解密(使用鍵)纔可以使用。

... 
api_token_encrypted = data['data']['token'] 
api_bearer_token = rsa.decrypt(base64.decodestring(api_token_encrypted), api_user_key) 

return(api_bearer_token) 

解碼後的令牌隨後用於api調用以獲取帳戶。

我看到的第二個問題是您的授權標頭與示例的標頭不匹配。具體來說,你錯過後面的空格「承載」

headers = {'Authorization': 'Bearer: {}'.format(api_access_token)} 

VS

add_headers(Authorization = paste("Bearer:", AplosAuthToken))) 

可能的解決這兩個之後,你應該能夠繼續進行。