如何使用curl在C / C ++中实现OAuth 2

时间:2019-10-12 00:27:54

标签: c++ c oauth-2.0 swagger api-eveonline

我正在尝试为用C ++编写的本机桌面应用程序实现OAuth 2 PKCE protocol,以便从swagger interface (EVE-Online)检索数据。 有一个python示例,显示了本机应用程序身份验证的工作方式: Python example

因此,基本上,我尝试将代码从python转换为C ++。

Python代码摘要:

import base64
import hashlib
import secrets

#Generate code challenge
random = base64.urlsafe_b64encode(secrets.token_bytes(32))
m = hashlib.sha256()
m.update(random)
d = m.digest()
code_challenge = base64.urlsafe_b64encode(d).decode().replace("=", "")

...

code_verifier = base64.urlsafe_b64encode(random).decode().replace("=", "")

在此之后,它只是发送HTTP请求,检查并再次发送等。

C ++代码摘要:

void SSOAuthentication::generateCodeChallenge()
{
    // Generate PKCE_BYTE_NUM of random bytes
    std::random_device randomDevice;
    unsigned char randomBuffer[PKCE_BYTE_NUM];
    for (unsigned char& i : randomBuffer) {
        i = randomDevice();
    }

    // Encode the raw random bytes to base64-url-safe
    std::string randomEncodedTmp = Base64::base64EncodeUrlSafe(randomBuffer, PKCE_BYTE_NUM);

    // Save the encoded random bytes
    random = (unsigned char*) randomEncodedTmp.c_str();

    // Hash the given code challenge with sha256
    std::string hashedTmp = sha256(randomEncodedTmp);
    auto unsignedHashedTmp = (unsigned char*) hashedTmp.c_str();

    // Encode hashed code challenge
    std::string encodedHashedTmp = Base64::base64EncodeUrlSafe(unsignedHashedTmp, hashedTmp.length());

    // Replace all occurrences of '=' with ''
    encodedHashedTmp.erase(std::remove(encodedHashedTmp .begin(), encodedHashedTmp .end(), '='), encodedHashedTmp .end());

    // Save the hashed code challenge
    hashedCodeChallenge = (unsigned char*) encodedHashedTmp.c_str();

    // Encode random again
    std::string encodedRandomTmp = Base64::base64EncodeUrlSafe(random, randomEncodedTmp.length());

    // Replace all occurrences of '=' with ''
    encodedRandomTmp.erase(std::remove(encodedRandomTmp.begin(), encodedRandomTmp.end(), '='), encodedRandomTmp.end());

    // Save the code verifier
    codeVerifier = (unsigned char*) encodedRandomTmp.c_str();
}

对于Base64编码,我使用了LihO的答案:LihO's answer for Base64 encoding

对于Sha256,我使用了以下指南:Sha256

问题:代码挑战的长度和特征不同:

Python代码质询输出:9iokv3y _-__ 5ihVaQ8u7U0BRuitfva5ZIialcIwokh18

C ++:YmJlZmU1NGE1MDQ0MWYzZGE2YWIxMmQxYzU3ZGY0Y2MwNTk2NTVjODczYWY4NGQwZTJhNTc1M2E1MDNjMDZjMw

此外,变量hashedCodeChallenge似乎存在长度问题,因为变量generateCodeChallenge完成后它将改变其值。

完整项目,用于检查代码:Github

0 个答案:

没有答案