Piiy
Piiy

Reputation: 1

How to authenticate Flask web app with Azure Active Directory using a self-signed certificate from Azure Key Vault?

I have created a self-signed certificate in Azure Key Vault, and I would like to use it to authenticate my Flask web app in Azure Active Directory.

I started by using a local certificate instead of a one in Azure Key Vault, and it works fine. See the code below

cert_file_path = "app/cert.pem"
key_file_path = "app/key.pem"

with open(cert_file_path, "rb") as cert_file:
    cert_obj = load_pem_x509_certificate(cert_file.read(), default_backend())
    cert_thumbprint = cert_obj.fingerprint(hashes.SHA1()).hex()

with open(key_file_path, "rb") as key_file:
    private_key = serialization.load_pem_private_key(
        key_file.read(),
        password=None,  # replace with your password if the key is encrypted
        backend=default_backend()
    )

client_credential = {
    "private_key": private_key.private_bytes(
        serialization.Encoding.PEM,
        serialization.PrivateFormat.PKCS8,
        serialization.NoEncryption()
    ).decode("utf-8"),
    "thumbprint": cert_thumbprint,
}

load_dotenv()
tenant_id = os.getenv('AZURE_TENANT_ID')
client_id = os.getenv('AZURE_CLIENT_ID')
authority = f"https://login.microsoftonline.com/{tenant_id}"

msal_app = ConfidentialClientApplication(
    client_id=client_id,
    authority=authority,
    client_credential=client_credential,
)

server = Flask(__name__)
server.secret_key = os.environ.get("FLASK_SECRET_KEY")
server.wsgi_app = ProxyFix(server.wsgi_app, x_proto=1, x_host=1)

@server.route("/login")
def login():
    auth_url = msal_app.get_authorization_request_url(["User.Read"])
    return redirect(auth_url)

@server.route("/login/azure/authorized")
def auth():
    code = request.args.get('code')
    result = None
    if code:
        result = msal_app.acquire_token_by_authorization_code(code, ["User.Read"], redirect_uri=url_for("auth", _external=True))
        if "error" in result:
            return f"Login failure: {result['error']} - {result['error_description']}"
        if "access_token" in result:
            session["user_info"] = result["id_token_claims"]
            return redirect("/")
    return "No code provided. Login failed."

However, I am not sure how to use the certificate in Azure Key Vault to do something similar to above?

Upvotes: 0

Views: 184

Answers (1)

Florian Vuillemot
Florian Vuillemot

Reputation: 655

You can create a self-signed certificate with Azure Key Vault that you download locally and then upload as you did with your local certificate.

You can automate certificate rotation using Azure Event Grid and Azure Function or Automation.

Upvotes: 0

Related Questions