Created
April 14, 2023 20:59
-
-
Save ntotten/889577e02bfaca65eeaee994369760cd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ZuploContext, ZuploRequest, ZoneCache, environment } from "@zuplo/runtime"; | |
// Get environment variables | |
// AZURE_AD_TENENT_ID: The tenant ID of your Azure AD (UUID) | |
// AZURE_AD_CLIENT_ID: The client ID of the "zuplo" Azure AD application (UUID) | |
// AZURE_AD_CLIENT_SECRET: The secret for the "zuplo" Azure AD application | |
// API_HOST: The url of your Azure App service i.e. https://zup-demo1.azurewebsites.net/ | |
const { AZURE_AD_TENENT_ID, AZURE_AD_CLIENT_ID, AZURE_AD_CLIENT_SECRET, API_HOST } = environment; | |
const TOKEN_CACHE_KEY = "ad-token" | |
// The the token cache for slightly less than the token expiration | |
const TOKEN_CACHE_TTL = 60 * 55 | |
export default async function (request: ZuploRequest, context: ZuploContext) { | |
const cache = new ZoneCache("tokens", context); | |
let accessToken = await cache.get(TOKEN_CACHE_KEY); | |
if (!accessToken) { | |
accessToken = await getAccessToken(); | |
// cache for 55 minutes | |
cache.put(TOKEN_CACHE_KEY, accessToken, TOKEN_CACHE_TTL) | |
} | |
// Create new Headers and add Authorization | |
const headers = new Headers(request.headers); | |
headers.set("Authorization", `Bearer ${accessToken}`); | |
const url = new URL(request.url); | |
// Forward request to Azure App | |
return fetch(`${API_HOST}${url.pathname}${url.search}`, { | |
headers, | |
body: request.body, | |
method: request.method | |
}); | |
} | |
async function getAccessToken() { | |
const body = new URLSearchParams({ | |
client_id: AZURE_AD_CLIENT_ID, | |
scope: `${AZURE_AD_CLIENT_ID}/.default`, | |
client_secret: AZURE_AD_CLIENT_SECRET, | |
grant_type: "client_credentials" | |
}); | |
const response = await fetch(`https://login.microsoftonline.com/${AZURE_AD_TENENT_ID}/oauth2/v2.0/token`, { | |
headers: { | |
"content-type": "application/x-www-form-urlencoded" | |
}, | |
method: "POST", | |
body | |
}); | |
const result = await response.json(); | |
return result.access_token; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment