std::string Util::GetAADToken()

in cvm-securekey-release-app/AttestationUtil.cpp [290:350]


std::string Util::GetAADToken(const std::string &KEKUrl)
{
    TRACE_OUT("Entering Util::GetAADToken()");

    auto clientId = std::getenv("AKV_SKR_CLIENT_ID");
    auto clientSecret = std::getenv("AKV_SKR_CLIENT_SECRET");
    auto tenantId = std::getenv("AKV_SKR_TENANT_ID");

    std::string resourceUrl = getResourceUrl(KEKUrl, false);
    std::string tokenUrl = "https://login.microsoftonline.com/" + std::string(tenantId) + "/oauth2/v2.0/token";
    std::string postData = "client_id=" + std::string(clientId) + "&client_secret=" + std::string(clientSecret) + "&grant_type=client_credentials&scope= " + resourceUrl;

    CURL *curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, tokenUrl.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, postData.length());

        curl_slist *headers = nullptr;
        headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        std::string response;
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        CURLcode result = curl_easy_perform(curl);
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);

        if (result == CURLE_OK)
        {
            std::string token;
            json jsonResponse = json::parse(response);
            if (jsonResponse.contains("access_token"))
            {
                token = jsonResponse["access_token"].get<std::string>();
            }
            else
            {
                TRACE_ERROR_EXIT("access_token not found in AAD auth response")
            }

            TRACE_OUT("Response: %s\n", token.c_str());
            TRACE_OUT("Exiting Util::GetAADToken()");
            return token;
        }
        else
        {
            TRACE_ERROR_EXIT("curl_easy_perform() failed for URL")
        }
    }
    else
    {
        TRACE_ERROR_EXIT("curl_easy_init() failed")
    }

    std::cerr << "Failed to obtain AKV AAD token" << std::endl;
    exit(-1);
}