How to use a TLS/SSL certificate in your Python code in Azure App Service

This post has been republished via RSS; it originally appeared at: New blog articles in Microsoft Tech Community.

If you want to know how to use it in C#/Java, there are some sample code in this document: https://docs.microsoft.com/en-us/azure/app-service/configure-ssl-certificate-in-code. Basically, to refer certificates uploaded in Azure App Service Linux using Python does not make much difference from in a local machine. It can be divided into three steps:
Steps:
1. Upload or import the certificates in Azure Portal to make it accessible to the app service:
KevinLi_0-1653143538366.png

 

2. Load certificate by setting WEBSITE_LOAD_CERTIFICATES to * or a specific thumbprint which belong to the certificate you want to use.
Then the certificate(s) will be injected into the python container in the path "/var/ssl/":
 
3. Refer to the certificate using Python Code.
Firstly, we can check if they exist by going to their directories in SSH:
KevinLi_1-1653142682079.png

 

Then leverage below sample code to use the certificate, replacing the thumbprint with yours:
Sample Code:
Sample1(using pyOpenSSL):
# load OpenSSL.crypto from OpenSSL import crypto # open it, using password. Supply/read your own from stdin. p12 = crypto.load_pkcs12(open("/var/ssl/private/6E619CF099EC156414E939B53358C98841234567.p12", "rb").read(), b"") # get various properties of said file. # note these are PyOpenSSL objects, not strings although you # can convert them to PEM-encoded strings. p12.get_certificate() # (signed) certificate object p12.get_privatekey() # private key. p12.get_ca_certificates() # ca chain.
Output1:
KevinLi_2-1653142682081.png
Sample2(using cryptography):
from cryptography.hazmat.primitives.serialization import pkcs12 with open("/var/ssl/private/6E619CF099EC156414E939B53358C98841234567.p12", "rb") as f: private_key, certificate, additional_certificates = pkcs12.load_key_and_certificates(f.read(), b"") print(certificate.not_valid_after)‚Äč
Output2:
KevinLi_3-1653142682083.png

 

Note that those certificates are stored in format "p12" and their password is empty.
 

All done. Thanks for reading! I hope you have fun in it!

 

REMEMBER: these articles are REPUBLISHED. Your best bet to get a reply is to follow the link at the top of the post to the ORIGINAL post! BUT you're more than welcome to start discussions here:

This site uses Akismet to reduce spam. Learn how your comment data is processed.