Configure TLS and verify certificates
Configure TLS and verify certificates
TLS protects traffic against interception and modification under its trust assumptions. A client must verify the server certificate chain and intended hostname or IP address. This local test server supplies its own test certificate and a client configured to trust it. It is not a production certificate authority.
package main
import ( "fmt" "io" "net/http" "net/http/httptest")
func localTLS() *httptest.Server { return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "ok") }))}func main() { s := localTLS() defer s.Close() r, e := s.Client().Get(s.URL) if e != nil { panic(e) } defer r.Body.Close() b, e := io.ReadAll(r.Body) fmt.Println(r.StatusCode, string(b), e == nil, r.TLS != nil)}httptest.Server.Client has a test-specific trust configuration. For production use system roots or explicitly approved organizational trust roots. Do not disable certificate verification. Check protocol requirements, configure MinVersion according to supported clients and current policy, use deadlines, and plan certificate renewal. This fixture uses loopback only.
Expected output:
200 ok true trueCheck the intended identity
package main
import ( "fmt" "net/http" "net/http/httptest" "net/url")
func localTLS() *httptest.Server { return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "ok") }))}func main() { s := localTLS() defer s.Close() u, e := url.Parse(s.URL) if e != nil { panic(e) } fmt.Println(s.Certificate().VerifyHostname(u.Hostname()) == nil, s.Certificate().VerifyHostname("other.example") != nil)}VerifyHostname checks certificate names, not the complete trust chain or expiration. For normal TLS handshakes leave the standard verification enabled; for offline certificate inspection use x509.Certificate.Verify with the right roots, intermediates, DNSName and time. Mutual TLS verifies client certificates too, but application authorization still remains necessary.
Expected output:
true trueTry it locally
Create a test server and verify its certificate against an unrelated name. Print whether validation fails.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Security engineering 08: Configure TLS and verify certificates
Check the lesson objective before moving on.
What does VerifyHostname alone check?
How should an unknown test CA be handled?