Skip to content

Commit

Permalink
fix: add token validation in GetEmbedInfo azure function
Browse files Browse the repository at this point in the history
  • Loading branch information
csm-thu committed May 11, 2023
1 parent cb98143 commit 4ef6678
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
2 changes: 1 addition & 1 deletion api/GetEmbedInfo/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ module.exports = async function (context, req) {
};
} else {
// Get the details like Embed URL, Access token and Expiry
const error = utils.validateQuery(req);
const error = await utils.validateQuery(req);
if (error) {
context.res = {
status: 200,
Expand Down
43 changes: 42 additions & 1 deletion api/GetEmbedInfo/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Licensed under the MIT license.

const guid = require('guid');
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');

function getAuthHeader(accessToken) {
// Function to append Bearer against the Access Token
Expand Down Expand Up @@ -51,7 +53,46 @@ function validateConfig() {
}
}

const validateQuery = (req) => {
const _validateAndDecodeQueryToken = async (req) => {
const client = jwksClient({ jwksUri: 'https://login.microsoftonline.com/common/discovery/keys' });
const options = {
// audience check is optional but strongly advised, it won't be checked if CSM_API_TOKEN_AUDIENCE is not defined
audience: process.env.CSM_API_TOKEN_AUDIENCE,
};

const _getSigningKey = (header, callback) => {
client.getSigningKey(header.kid, (error, key) => {
if (error) {
console.error(error);
throw error;
}
const signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
};

const accessToken = req?.headers?.authorization?.replace('Bearer ', '');
if (!accessToken) {
throw new Error('token is missing in query.');
}

return new Promise((resolve, reject) =>
jwt.verify(accessToken, _getSigningKey, options, (err, decoded) => {
return err ? reject(err) : resolve(decoded);
})
);
};

const validateQuery = async (req) => {
try {
const token = await _validateAndDecodeQueryToken(req);
if (!token) return "Unauthorized: can't decode token";
if (!token.roles || token.roles.length === 0) return 'Unauthorized: missing roles for Cosmo Tech API';
} catch (error) {
console.error('Token validation error: ' + error);
return 'Unauthorized: ' + error;
}

const reportsIds = req?.body?.reports;
if (!Array.isArray(reportsIds)) {
return 'Query is invalid. Parameter "reports" must be an array.';
Expand Down

0 comments on commit 4ef6678

Please sign in to comment.