本文介绍了大规模矩阵路由-缺少令牌/API密钥错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用大型矩阵API 使用Python 3.7.7运行一些查询.我相信我已经成功创建了访问令牌,但是我对API的请求却表明我的令牌丢失了.

I'm trying to use the Large-Scale Matrix API to run some queries using Python 3.7.7. I believe I've successfully created an access token, yet my requests to the API state that my token is missing.

我生成令牌的代码完全来自文档此处(添加了一些打印语句),在查询API时会使用此页面.

My code to generate the tokens is drawn entirely from the documentation here (a few print statements added), while querying the API uses the syntax shown on this page.

import time #To generate the OAuth timestamp
import urllib.parse #To URLencode the parameter string
import hmac #To implement HMAC algorithm
import hashlib #To generate SHA256 digest
from base64 import b64encode #To encode binary data into Base64
import binascii #To convert data into ASCII
import requests #To make HTTP requests


grant_type = 'client_credentials'
oauth_consumer_key =
oauth_nonce = str(int(time.time()*1000))
oauth_signature_method = 'HMAC-SHA256'
oauth_timestamp = str(int(time.time()))
oauth_version = '1.0'

def create_parameter_string(grant_type, oauth_consumer_key,oauth_nonce,oauth_signature_method,oauth_timestamp,oauth_version):
    parameter_string = ''
    parameter_string = parameter_string + 'grant_type=' + grant_type
    parameter_string = parameter_string + '&oauth_consumer_key=' + oauth_consumer_key
    parameter_string = parameter_string + '&oauth_nonce=' + oauth_nonce
    parameter_string = parameter_string + '&oauth_signature_method=' + oauth_signature_method
    parameter_string = parameter_string + '&oauth_timestamp=' + oauth_timestamp
    parameter_string = parameter_string + '&oauth_version=' + oauth_version
    return parameter_string

parameter_string = create_parameter_string(grant_type, oauth_consumer_key,oauth_nonce,oauth_signature_method,oauth_timestamp,oauth_version)
encoded_parameter_string = urllib.parse.quote(parameter_string, safe='')


url = 'https://account.api.here.com/oauth2/token'
encoded_base_string = 'POST' + '&' + urllib.parse.quote(url, safe='')
encoded_base_string = encoded_base_string + '&' + encoded_parameter_string


access_key_secret =
signing_key = access_key_secret + '&'

def create_signature(secret_key, signature_base_string):
    encoded_string = signature_base_string.encode()
    encoded_key = secret_key.encode()
    temp = hmac.new(encoded_key, encoded_string, hashlib.sha256).hexdigest()
    byte_array = b64encode(binascii.unhexlify(temp))
    return byte_array.decode()

oauth_signature = create_signature(signing_key, encoded_base_string)
encoded_oauth_signature = urllib.parse.quote(oauth_signature, safe='')

body = {'grant_type' : '{}'.format(grant_type)}

headers = {
            'Content-Type' : 'application/x-www-form-urlencoded',
            'Authorization' : 'OAuth oauth_consumer_key="{0}",oauth_nonce="{1}",oauth_signature="{2}",oauth_signature_method="HMAC-SHA256",oauth_timestamp="{3}",oauth_version="1.0"'.format(oauth_consumer_key,oauth_nonce,encoded_oauth_signature,oauth_timestamp)
          }

response = requests.post(url, data=body, headers=headers)

print(eval(response.text))

access_token = eval(response.text)['access_token']

url = 'https://largescalematrix.router.hereapi.com/v1/matrix'
body = {
    "origins": [{"lat": 0.0, "lng": 0.0}, {"lat": 0.1, "lng": 0.1}],
    # "destinations": [...],  // if omitted same as origins
    "regionDefinition": {
        "type": "circle",
        "center": {"lat": 0.0, "lng": 0.0},
        "radius": 10000
    }
}

headers = {
            'Authorization' : 'Bearer="{0}"'.format(access_token),
            'Content-Type' : 'application/json'
          }

response = requests.post(url, data=body, headers=headers)
print(eval(response.text))

在上面的代码中,oauth_consumer_keyaccess_key_secret的(未填充)字段分别填充有从Projects> REST> OAuth 2.0(JSON Web令牌)生成的密钥和秘密密钥.

In the above code, the (unfilled) fields of oauth_consumer_key and access_key_secret are filled with the key and secret key, respectively, generated from Projects>REST>OAuth 2.0 (JSON Web Tokens).

运行此代码时,令牌成功生成-得到以下形式的响应

When I run this code, the token successfully generates -- I get a response of the form

{'access_token': [long string], 'token_type': 'bearer', 'expires_in': 86399}

但是,当我随后尝试查询API时,出现401错误,并显示以下消息:

However, when I then attempt to query the API, I get a 401 error with the following message:

{'error': 'Unauthorized', 'error_description': 'Token or apiKey is missing.'}

我认为我的错误是以下两种形式之一:

I think my error's of one of the two forms:

  1. 我正在正确生成令牌,但不是用于查询大型矩阵路由的 correct 令牌.如果是这种情况,那么我应该使用哪些输入来创建我的令牌?
  2. 我查询大型Matrix API的语法不正确.我的请求遵循此上显示的语法页面,所以我不确定当时缺少什么.是否需要从项目">"REST">"API密钥"中包含APIKEY?
  1. I'm generating a token correctly, but not the correct token for querying the Large-Scale Matrix Routing. If this is the case, then what inputs should I be using to create my token?
  2. My syntax for querying the Large-Scale Matrix API is incorrect. My request follows the syntax shown on this page, so I'm not sure what I'm missing then. Do I need to include an APIKEY from Projects>REST>API Keys?

提前谢谢!

推荐答案

感谢Paolo的帖子,它对我有很大帮助.我点击了您发布的页面的链接用于获取令牌的python示例,并通过复制粘贴该代码来获取令牌.但是我也以与您相同的方式失败,我得到了401:未经授权.

Thanks Paolo for your post, it really helped me.I followed the links to the page you posted for the python example to get the token, and by copy pasting that code I could also get the token. However I also failed in the same way you did, I was getting 401: Unauthorized.

对我来说,关键是此页面,位于身份验证令牌"下.

The key for me was this page, under "Authentication Token".

curl https://weather.ls.hereapi.com/weather/1.0/report.json
?product=observation
&name=Berlin
-H "Authorization: Bearer {YOUR_TOKEN}"

最后一位"载体(令牌)"是我需要使其工作的缺失点.最后,这是我的代码:

This last bit, "Bearer (TOKEN)" was the missing bit I needed to make it work. Finally, here is my code:

import time #To generate the OAuth timestamp
import urllib.parse #To URLencode the parameter string
import hmac #To implement HMAC algorithm
import hashlib #To generate SHA256 digest
from base64 import b64encode #To encode binary data into Base64
import binascii #To convert data into ASCII
import requests #To make HTTP requests

import json

grant_type = 'client_credentials'
oauth_consumer_key = 'HERE.ACCESS.KEY.ID' #From credentials.properties file
oauth_nonce = str(int(time.time()*1000))
oauth_signature_method = 'HMAC-SHA256'
oauth_timestamp = str(int(time.time()))
oauth_version = '1.0'

def create_parameter_string(grant_type, oauth_consumer_key,oauth_nonce,oauth_signature_method,oauth_timestamp,oauth_version):
    parameter_string = ''
    parameter_string = parameter_string + 'grant_type=' + grant_type
    parameter_string = parameter_string + '&oauth_consumer_key=' + oauth_consumer_key
    parameter_string = parameter_string + '&oauth_nonce=' + oauth_nonce
    parameter_string = parameter_string + '&oauth_signature_method=' + oauth_signature_method
    parameter_string = parameter_string + '&oauth_timestamp=' + oauth_timestamp
    parameter_string = parameter_string + '&oauth_version=' + oauth_version
    return parameter_string

parameter_string = create_parameter_string(grant_type, oauth_consumer_key,oauth_nonce,oauth_signature_method,oauth_timestamp,oauth_version)
encoded_parameter_string = urllib.parse.quote(parameter_string, safe='')

url = 'https://account.api.here.com/oauth2/token'
encoded_base_string = 'POST' + '&' + urllib.parse.quote(url, safe='')
encoded_base_string = encoded_base_string + '&' + encoded_parameter_string

access_key_secret = 'HERE.ACCESS.KEY.SECRET'#From credentials.properties file
signing_key = access_key_secret + '&'

def create_signature(secret_key, signature_base_string):
    encoded_string = signature_base_string.encode()
    encoded_key = secret_key.encode()
    temp = hmac.new(encoded_key, encoded_string, hashlib.sha256).hexdigest()
    byte_array = b64encode(binascii.unhexlify(temp))
    return byte_array.decode()

oauth_signature = create_signature(signing_key, encoded_base_string)
encoded_oauth_signature = urllib.parse.quote(oauth_signature, safe='')

body = {'grant_type' : '{}'.format(grant_type)}

headers = {
            'Content-Type' : 'application/x-www-form-urlencoded',
            'Authorization' : 'OAuth oauth_consumer_key="{0}",oauth_nonce="{1}",oauth_signature="{2}",oauth_signature_method="HMAC-SHA256",oauth_timestamp="{3}",oauth_version="1.0"'.format(oauth_consumer_key,oauth_nonce,encoded_oauth_signature,oauth_timestamp)
          }

response = requests.post(url, data=body, headers=headers)

r_obj = json.loads(response.text)

token = r_obj['access_token']

print(response.text)

payload = {'name': 'Chicago', 'product': 'forecast_7days_simple'}
r = requests.get('https://weather.ls.hereapi.com/weather/1.0/report.json', params=payload, headers={'Authorization': 'Bearer '+token})
print(r.status_code)
r.encoding = r.apparent_encoding
obj = json.loads(r.text)
print(obj['dailyForecasts'])

这篇关于大规模矩阵路由-缺少令牌/API密钥错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 04:48