Search code examples
apigosslx509certificateca

Get "https://zzzztower.zzzz.com/api/v2/hosts/": x509: certificate relies on legacy Common Name field, use SANs instead


I am trying to get the list of hosts from ansible tower using the API defined in here I am using the ansible tower URL -> https://zzzztower.zzzz.com/api/v2/hosts/ and the bearer token -> aaaaaaaaaaaaaaaaaaaaaaaaaaa to hit the API.

When I use postman to hit the API I am getting a proper response but when I use golang code, I am getting error

Get "https://ansibletower.micron.com/api/v2/hosts/": x509: certificate relies on legacy Common Name field, use SANs instead

Here is my code:

package globals

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

// var AUTH_TOKEN string = os.Getenv("AUTH_TOKEN")

func GetAnsibleHosts() (string, error) {

    url := "https://zzzztower.zzzz.com/api/v2/hosts/"
    method := "GET"

    client := &http.Client{}
    req, err := http.NewRequest(method, url, nil)

    if err != nil {
        return "", fmt.Errorf("Error creating request: %v", err)
    }

    bearerToken := "aaaaaaaaaaaaaaaaaaaaaaaaaaa"

    // Add the Bearer Auth token to the request
    req.Header.Add("Authorization", "Bearer "+bearerToken)

    res, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return "", err
    }
    defer res.Body.Close()

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Println(err)
        return "", err
    }
    // fmt.Println(string(body))
    return string(body), err
}

I tried finding the error on google but i didn't find much help. Few articles mentioned to use GODEBUG=x509ignoreCN=0 but it didn't worked.

I would really appreciate you help.


Solution

  • To skip this check, we can use InsecureSkipVerify and set it to true.

    Something like this:

    // Create a new transport with InsecureSkipVerify set to true
    transport := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    
    // Create a new client using the transport
    client := &http.Client{Transport: transport}
    

    And then this client can be used to get the response.

    PS: This worked for me but others pls suggest a better approach if any.