DEV Community

codemee
codemee

Posted on • Edited on

2 1

在 ESP8266/ESP32 使用 HTTPClient 連接 https 網站

HTTPClient 是個好用的程式庫, 只要叫用其中的 get()等方法就可以幫我們進行 HTTP 請求。不過如果你要連接的是 HTTPS 網站, 正規的作法是你得在程式中驗證連線的網站所提供的電子憑證, 這得在你的程式裡加上憑證相關的資訊, 而且因為憑證是有期限的, 這也表示現在可以正常運作的程式, 可能在一段時間後就會因憑證失效而出錯。

但如果你不那麼在意連線的是不是假網站, 不想驗證憑證的正確性, 那麼可以使用只要網址的 HTTPClient.begin(), 但提供 https 的網址, 不用提供憑證, 沒有提供憑證的情況下, 程式庫預設的方式就是略過檢查憑證:

    bool verify(WiFiClient& client, const char* host) override
    {
        WiFiClientSecure& wcs = static_cast<WiFiClientSecure&>(client);
        if (_cacert == nullptr) {
            wcs.setInsecure();
        } else {
            wcs.setCACert(_cacert);
            wcs.setCertificate(_clicert);
            wcs.setPrivateKey(_clikey);
        }
        return true;
    }
...
Enter fullscreen mode Exit fullscreen mode

上面的 setInsecure() 會在連線時略過憑證的檢查

    if (insecure) {
        mbedtls_ssl_conf_authmode(&ssl_client->ssl_conf, MBEDTLS_SSL_VERIFY_NONE);
        log_i("WARNING: Skipping SSL Verification. INSECURE!");
    } else if (rootCABuff != NULL) {
...
Enter fullscreen mode Exit fullscreen mode

這當然不是正規的作法, 使用前請三思。

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay