Home >Backend Development >Golang >How to Verify HTTPS Requests Using Certificates in Go?

How to Verify HTTPS Requests Using Certificates in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 00:34:10361browse

How to Verify HTTPS Requests Using Certificates in Go?

HTTPS Request Verification Using Certificates in Go

In an application requiring communication with an HTTPS-enabled REST API served on a different port, it is common to encounter SSL validation errors like "x509: certificate signed by unknown authority." This occurs when the application does not recognize the API's certificate authority (CA).

To resolve this issue, you need to add the CA certificate to your request's transport layer. Here's a Go code snippet demonstrating how to do it:

package main

import (
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    // Read the root CA certificate.
    caCert, err := ioutil.ReadFile("rootCA.crt")
    if err != nil {
        log.Fatal(err)
    }

    // Create a certificate pool from the CA certificate.
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    // Configure the HTTP client with TLS settings.
    client := &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                RootCAs: caCertPool,
            },
        },
    }

    // Make a GET request to the HTTPS URL.
    resp, err := client.Get("https://secure.domain.com")
    if err != nil {
        log.Fatal(err)
    }

    // Process the HTTP response as usual.
    fmt.Println(resp.Status)
}

If you have not created a CA to sign your certificates, here are some steps to guide you:

Generating a CA:

openssl genrsa -out rootCA.key 4096
openssl req -x509 -new -key rootCA.key -days 3650 -out rootCA.crt

Generating a Certificate for Secure.domain.com Signed with the CA:

openssl genrsa -out secure.domain.com.key 2048
openssl req -new -key secure.domain.com.key -out secure.domain.com.csr

In response to the question "Common Name (e.g. server FQDN or YOUR name) []:", enter "secure.domain.com" (your actual domain name).

openssl x509 -req -in secure.domain.com.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -days 365 -out secure.domain.com.crt

The above is the detailed content of How to Verify HTTPS Requests Using Certificates in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn