Casablanca中的HTTP身份验证

HTTP Authentication in Casablanca

本文关键字:身份验证 HTTP 中的 Casablanca      更新时间:2023-10-16

我在访问幻想超级联赛数据时遇到问题,URL https://fantasy.premierleague.com/drf/my-team/1447063/

URL是我特定的,因此需要身份验证才能访问它。我已经在答案中使用了代码来设置Casablanca中的基本HTTP身份验证,更改凭据,基本64的转换,URL到U(" https://fantasy.premierleague.com")和uri ui to l"/drf"/drf/My-Team/1447063/"。

我已经建立了一个虚拟幻想团队,以便可以安全地发布用户ID和密码,以便人们可以尝试一下。我不将此密码用于其他任何内容。

#include "stdafx.h"
#include <vector>
#include <cppresthttp_client.h>
int main()
{
    // These lines are just to show the conversion to base64
    char sCredentials[] = "robin@laddershakers.com:jrhf9YYal";
    std::vector<unsigned char> vCred;
    for (int x = 0; x < (sizeof(sCredentials) / sizeof(sCredentials[0])) - 1; x++)
        vCred.push_back(sCredentials[x]); // There must be an easier way to do this
    auto b64Credentials = utility::conversions::to_base64(vCred);
    using namespace web::http::client;
    using namespace web::http;
    // Creating http_client
    http_client_config config;
    credentials cred(L"robin@laddershakers.com", L"jrhf9YYal");
    config.set_credentials(cred);
    http_client client(U("https://fantasy.premierleague.com/drf/my-team/1447063/"), config);
    // create header
    http_request req(methods::GET);
    // Add base64 result to header
    req.headers().add(L"Authorization", L"Basic cm9iaW5AbGFkZGVyc2hha2Vycy5jb206anJoZjlZWWFs");
    //  req.set_request_uri(L"/drf/my-team/1447063/");
    pplx::task<http_response> responses = client.request(req);
    pplx::task<web::json::value> jvalue = responses.get().extract_json();
    std::wcout << jvalue.get().serialize();
    return 0;
}

产生的输出为

{"详细信息":"未提供身份验证凭据。"}

HTTP_Response已禁止结果403,这表明即使使用凭据也无法访问URL,但输出表明找不到凭据。如果我已经登录到该网站时将完整的URL输入到Chrome中,我将获得所需的JSON数据。如果我将URL输入尚未登录网站的边缘,我将获得与上述相同的输出(未提供凭据)。

我是在这里鞭打一匹死马,还是有办法访问数据?

我不确定是否将其作为对原始答案的评论发布,但是无论如何我没有足够的声誉来做到这一点。对重复的道歉。

您需要使用auth访问数据。方法,您根本不必使用凭据配置,您只需要提供自定义标题数据和客户端URL。

这作为以下作用:

pplx::task<void> HTTPRequestCustomHeadersAsync(){
http_client client(L"https://fantasy.premierleague.com/drf/my-team/1463628/");
// Manually build up an HTTP request with header and request URI.
http_request request(methods::GET);
request.headers().add(L"Authorization", L"Basic am9obi5kb2VAZ21haWwuY29tOmFiYzEyMw==");
pplx::task<http_response> responses = client.request(request);
pplx::task<web::json::value> jvalue = responses.get().extract_json();
std::wcout << jvalue.get().serialize();
return client.request(request).then([](http_response response)
{
    // Print the status code.
    std::wostringstream ss;
    ss << L"Server returned returned status code " << response.status_code() << L"." 
<< std::endl;
    std:: wcout << ss.str();
}
);
}
int main(int argc, char *args[])
{
std::wcout << L"Calling HTTPRequestCustomHeadersAsync..." << std::endl;
HTTPRequestCustomHeadersAsync().wait();
return 0;   
}

不要忘记包含文件。