How can I use Azure functions to refresh an Azure Key Vault secret every 1H? Have code but not working
Ayhm Dalila
1
Reputation point
Hello,
I'm trying to refresh a token using an API call every 1 hour by a python function on Azure functions,
The base code is as below:
import requests
import os
# Set the API endpoint URL and the refresh token
api_endpoint = "HIDDEN"
refresh_token = "HIDDEN"
CLIENT_ID = "HIDDEN"
CLIENT_SECRET = "HIDDEN"
# Set the request headers
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
# Set the request payload
payload = {
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET
}
# Send the request to the API endpoint
response = requests.post(api_endpoint, headers=headers, data=payload)
# If the request is successful, print the new auth token
if response.status_code == 200:
data = response.json()
new_auth_token = data["access_token"]
print(new_auth_token)
In azure functions, it's like this:
import requests
import json
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
import datetime
import logging
import azure.functions as func
def main(mytimer: func.TimerRequest) -> None:
utc_timestamp = datetime.datetime.utcnow().replace(
tzinfo=datetime.timezone.utc).isoformat()
# Retrieve secrets from Azure Key Vault
credential = DefaultAzureCredential()
client = SecretClient(vault_url="HIDDEN", credential=credential)
client_id = client.get_secret("Client__Id").value
client_secret = client.get_secret("Client__Secret").value
refresh_token = client.get_secret("Refresh__Token").value
access_token = client.get_secret("Access__Token").value
# Request new access token using refresh token
url = "HIDDEN"
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "refresh_token",
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh_token
}
response = requests.post(url, headers=headers, data=data)
return func.HttpResponse(response)
# Check if request was successful
if response.status_code == 200:
# Store new access token in Azure Key Vault
access_token = response.json()["access_token"]
client.set_secret("AT", access_token)
else:
print("Error refreshing access token:", response.status_code)
if mytimer.past_due:
logging.info('The timer is past due!')
logging.info('Python timer trigger function ran at %s', utc_timestamp)
When I run it, it returns "202 Accepted", but the secret on azure key vault does not change. If I return the output in a func.HttpResponse() then it shows as follows: The access token expiry UTC time '12/26/2022 1:20:29 PM' is earlier than current UTC time '12/26/2022 2:31:41 PM
Tried powershell instead of python
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,911 questions
Sign in to answer