REST HERE API-身份验证和授权错误

时间:2019-12-27 09:32:50

标签: php here-api

我正在尝试按照此页面上的说明在HERE REST API中获取访问令牌https://developer.here.com/olp/documentation/access_control/api-reference-swagger.html

当我提交请求时,API会以httpStatus 401,错误代码401200,“缺少授权标头。”进行响应,同时明确提供了授权标头。

我在PHP中使用cURL。这是我正在使用的功能:

function getHereApiAccessToken()
{
    $API_URL="https://account.api.here.com/oauth2/token";

    $nonce=uniqid();

    $signature_elements=array();
    $signature_elements[urlencode('grant_type')]=urlencode("client_credentials");
    $signature_elements[urlencode('oauth_consumer_key')]=urlencode("xxxx_xxxxxx-xxxxxxxxxx");
    $signature_elements[urlencode('oauth_nonce')]=urlencode($nonce);
    $signature_elements[urlencode('oauth_signature_method')]=urlencode("HMAC-SHA256");
    $signature_elements[urlencode('oauth_timestamp')]=urlencode(time());
    $signature_elements[urlencode('oauth_version')]=urlencode("1.0");

    ksort($signature_elements);

    $base_string="POST&".urlencode("https://account.api.here.com/oauth2/token")."&".urlencode(implode('&', $signature_elements));
    $signing_key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxx-xxxxxxxxxxxxxxx-xxxxx_x-xxxxxxxxxxxxxx&";

    $signature=hash_hmac('sha256', $base_string, $signing_key);

    $headers=array();
    $headers[]="Content-Type: application/x-www-form-urlencoded";
    $headers[]='Authoradization: OAuth oauth_consumer_key="xxxx_xxxxxx-xxxxxxxxxx",oauth_nonce="'.$nonce.'",oauth_signature="'.$signature.'",oauth_signature_method="HMAC-SHA256",oauth_timestamp="'.time().'",oauth_version="1.0"';

    $postData=array();
    $postData['grant_type']="client_credentials";
    $postData['expires_in']=50;
    $postData['client_id']="xxxxxxxxxxxxxxxxxxxx";
    $postData['client_secret']="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxx-xxxxxxxxxxxxxxx-xxxxx_x-xxxxxxxxxxxxxx";

    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $API_URL);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    $response=curl_exec($ch);

    $httpcode=curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if(curl_error($ch))
    {
        echo "cURL error: ". curl_error($ch);

        return false;
    }
        elseif($httpcode!=200)
        {
            echo "API responded with HTTP code: ". $httpcode;

            echo "Response: ".$response;

            return false;
        }
        else
        {
            curl_close($ch);

            $json=json_decode($response, 1);

            if(empty($json))
            {
                echo "Failed to decode JSON";

                return false;
            }

            if(empty($json['access_token']))
            {
                echo "Missing access_token in API response: ".var_export($json, true);
            }

            return $json['access_token'];
        }

    return false;
}

这是我得到的确切答复:

{"errorId":"ERROR-b924b495-53ce-4391-bbd7-e73f50e35c2e","httpStatus":401,"errorCode":401200,"message":"Missing Authorization header.","error":"invalid_request","error_description":"errorCode: '401200'. Missing Authorization header."}

2 个答案:

答案 0 :(得分:0)

原来,这只是标题名称中的错字。

授权->授权

我想我已经从HERE的文档中复制了标题名称,但很有趣的是,我找不到我从中所做的页面。

答案 1 :(得分:0)

Java

public static String getOauthToken(String oauthUrl, String consumerKey, String consumerSecret) {
    JSONObject jsonOauthQueryBody = new JSONObject();
    jsonOauthQueryBody.put("grantType", "client_credentials");

    return getOauthToken(oauthUrl, consumerKey, consumerSecret, jsonOauthQueryBody.toString());
}

public static String getOauthToken(String oauthUrl, String consumerKey, String consumerSecret, String email, String password) {
    JSONObject jsonOauthQueryBody = new JSONObject();
    jsonOauthQueryBody.put("grantType", "password");
    jsonOauthQueryBody.put("email", email);
    jsonOauthQueryBody.put("password", password);

    return getOauthToken(oauthUrl, consumerKey, consumerSecret, jsonOauthQueryBody.toString());
}


private static String getOauthToken(String oauthUrl, String consumerKey, String consumerSecret, String body) {

    LOGGER.info("GET ACCESS TOKEN=" + oauthUrl);
    URI uri = null;
    try {
        uri = new URI(oauthUrl);
    } catch (URISyntaxException e) {
        LOGGER.error("Not proper oauth url=" + oauthUrl);
        throw new RuntimeException(e);
    }

    ValidatableResponse res = given()
            .header("Content-Type", "application/json")
            .auth()
            .oauth(consumerKey, consumerSecret, "", "")
            .body(body)
            .when()
            .post(uri)
            .then();

    int responseCode = res.extract().statusCode();

    if (HttpURLConnection.HTTP_OK == responseCode) {
        String token = res.extract().jsonPath().get("accessToken").toString();
        LOGGER.info("Auth token=" + token);
        return token;
    } else {
        String msg = "Access token retrieve failed. Http response code=" + responseCode;
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    }

}