Enforce TLS 1.2 Minimum in Python

Create an SSL context with a minimum TLS version of 1.2 to enforce secure connections.

Easy Python 3.9+ Aug 9, 2026 Auth & security at scale 13 views 0 copies

Python code

11 lines
Python 3.9+
import ssl

def get_min_tls_version():
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    context.minimum_version = ssl.TLSVersion.TLSv1_2
    return context.minimum_version

if __name__ == "__main__":
    min_version = get_min_tls_version()
    print(f"Minimum TLS version set to: {min_version.name} (value: {min_version})")
    print(f"Is at least TLS 1.2: {min_version >= ssl.TLSVersion.TLSv1_2}")

Output

stdout
Minimum TLS version set to: TLSv1_2 (value: 771)
Is at least TLS 1.2: True

How it works

The ssl.SSLContext is created with PROTOCOL_TLS_CLIENT, which configures the context for client-side TLS connections with default certificate validation. Setting minimum_version to TLSVersion.TLSv1_2 ensures that older, insecure protocols like SSLv3 and TLS 1.0/1.1 are rejected. The name attribute of TLSVersion provides a human-readable label, and the integer value corresponds to the protocol's internal representation. Comparing versions with >= confirms the minimum is met.

Common mistakes

  • Forgetting to set `check_hostname` and `load_default_certs` for real client connections
  • Using `PROTOCOL_TLS` instead of `PROTOCOL_TLS_CLIENT`, which may not enable proper defaults
  • Assuming `minimum_version` is set by default; it falls back to system defaults if not explicit

Variations

  1. Use `context.set_ciphers` to also restrict weak cipher suites
  2. Set `context.minimum_version` directly on a context from `ssl.create_default_context()`

Real-world use cases

  • Securing connections to internal services that still support old TLS versions but must enforce 1.2+
  • Compliance audits where PCI-DSS or HIPAA require minimum TLS 1.2 for data transmission
  • Client-side code that calls third-party APIs with strict security policies and needs guaranteed TLS 1.2

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Auth & security at scale

Related tutorials and quizzes for this topic.