Created
April 14, 2019 15:47
-
-
Save Alex-Wauters/e44d294210c31e88f0e1a04dc43d6d51 to your computer and use it in GitHub Desktop.
Firebase: Auth with Azure AD
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
exports.validateAuth = functions.https.onRequest(async (req, res) => { | |
if (req.query && req.query.error) { | |
console.error(`Authentication request error from Azure AD: ${req.query.error_description}. Full details: ${JSON.stringify(req.query)}`); | |
res.status(400).send(`Oh oh, something went wrong. Please contact support with the following message: Invalid authentication request: ${req.query.error_description}`); | |
return; | |
} | |
if (req.body && req.body.id_token) { | |
try { | |
const token = req.body.id_token; | |
const unverified: any = jwt.decode(token, { complete: true }); | |
if (!unverified || !unverified.payload || unverified.payload.iss !== issuerURI) { | |
console.error(`Invalid unverified token (iss): ${token}. Unverified decoding: ${unverified}`); | |
throw new Error("Invalid issuer"); | |
} | |
if (!unverified.header || unverified.header.alg !== "RS256" || !unverified.header.kid) { | |
throw new Error(`Invalid header or algorithm on token: ${token}`); | |
} | |
const k = await getSignatureKeys(); | |
const signatureKey = k.find((c => { | |
return c.kid === unverified.header.kid; | |
})); | |
if (!signatureKey) { | |
throw new Error(`Signature used in token ${token} is not in the list of recognized keys: ${JSON.stringify(k)}`); | |
} | |
const upn = await verifyToken(token, signatureKey.x5c[0]); | |
const customToken = await admin.auth().createCustomToken(upn); | |
res.redirect(`/?jwt=${customToken}`); | |
} catch (err) { | |
console.error(`Failed to create custom token: ${err}`); | |
res.status(400).send(`Oh oh, something went wrong. Please contact support with the following message: see the logs for more information.`); | |
} | |
} else { | |
// Redirect to IdP | |
res.redirect(`https://login.microsoftonline.com/${tenantName}.onmicrosoft.com/oauth2/authorize?client_id=${clientId}&&response_type=id_token&scope=openid&nonce=42&response_mode=form_post`); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment