Python 大规模矩阵路由--缺少令牌/API密钥错误

Python 大规模矩阵路由--缺少令牌/API密钥错误,python,here-api,Python,Here Api,我正在尝试使用Python 3.7.7运行一些查询。我相信我已经成功地创建了一个访问令牌,但是我对API的请求表明我的令牌丢失了 我生成令牌的代码完全来自文档(添加了一些打印语句),而查询API时使用的语法如所示 在上面的代码中,oauth_consumer_key和access_key_secret的(未填充的)字段分别由Projects>REST>oauth 2.0(JSON Web令牌)生成的密钥和密钥填充 当我运行这段代码时,令牌成功地生成了——我得到了如下形式的响应 {'access_

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

我生成令牌的代码完全来自文档(添加了一些打印语句),而查询API时使用的语法如所示

在上面的代码中,
oauth_consumer_key
access_key_secret
的(未填充的)字段分别由Projects>REST>oauth 2.0(JSON Web令牌)生成的密钥和密钥填充

当我运行这段代码时,令牌成功地生成了——我得到了如下形式的响应

{'access_token': [long string], 'token_type': 'bearer', 'expires_in': 86399}
但是,当我尝试查询API时,我得到一个401错误,并显示以下消息:

{'error': 'Unauthorized', 'error_description': 'Token or apiKey is missing.'}
我认为我的错误是两种形式之一:

  • 我正确地生成了一个令牌,但不是用于查询大规模矩阵路由的正确令牌。如果是这种情况,那么我应该使用什么输入来创建我的令牌
  • 我查询大规模矩阵API的语法不正确。我的请求遵循上所示的语法,因此我不确定我遗漏了什么。我是否需要包含来自Projects>REST>API密钥的API密钥

  • 尝试使用以下代码段生成令牌

    import CryptoJS from 'crypto-js';
    import axios from 'axios';
    
    export const getToken = (app_key, app_secret) => {
        let url = "https://account.api.here.com/oauth2/token";
        let key = app_key;
        console.log(key);
        let secret = app_secret;
        console.log(secret);
        let nonce = btoa(Math.random().toString(36)).substring(2, 13);
        let timestamp = Math.floor(Date.now()/1000);
        let normalizedUrl = encodeURIComponent(url);
        console.log(normalizedUrl);
        let signing_method = "HMAC-SHA256";
        let sig_string = "oauth_consumer_key="
        .concat(key)
        .concat("&oauth_nonce=")
        .concat(nonce)
        .concat("&oauth_signature_method=")
        .concat(signing_method)
        .concat("&oauth_timestamp=")
        .concat(timestamp)
        .concat("&").concat("oauth_version=").concat("1.0");
    
        console.log(sig_string)
    
        let normalised_string = "POST&".concat(normalizedUrl).concat("&").concat(encodeURIComponent(sig_string));
    
        console.log(normalised_string);
        let signingKey = secret.concat("&");
        console.log(signingKey);
    
        let digest = CryptoJS.HmacSHA256(normalised_string, signingKey);
        console.log(">>>>>>>>>>>>>");
        console.log(digest);
        let signature = CryptoJS.enc.Base64.stringify(digest);
    
    
    
        let auth = 'OAuth oauth_consumer_key="'
        .concat(key)
        .concat('",oauth_signature_method="')
        .concat(signing_method)
        .concat('",oauth_signature="')
        .concat(encodeURIComponent(signature))
        .concat('",oauth_timestamp="')
        .concat(timestamp)
        .concat('",oauth_nonce="')
        .concat(nonce)
        .concat('",oauth_version="1.0"')
    
        console.log(auth)
    
        return axios({
            method: 'post',
            url: url,
            data: JSON.stringify({grantType: "client_credentials"}),
            headers: {
                'Content-Type': "application/json",
                'Authorization': auth
            }
        });
    }
    

    谢谢保罗的帖子,它真的帮助了我。 我按照python示例的链接获取令牌,通过复制粘贴代码,我也可以获得令牌。但是我也失败了,就像你一样,我得到了401:未经授权

    我的密钥是,在“身份验证令牌”下

    最后一位“承载(令牌)”是我需要使其工作的缺失位。最后,这里是我的代码:

    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'])
    

    您有Python代码的版本吗?这似乎是用JavaScript编写的。
    curl https://weather.ls.hereapi.com/weather/1.0/report.json
    ?product=observation
    &name=Berlin
    -H "Authorization: Bearer {YOUR_TOKEN}"
    
    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'])