I am working on an Azure Function that interacts with the Azure Active Directory Graph API (@azure/graph). The function API is designed to verify if an email is registered and verified in Azure AD(Entra Id). However, I am encountering an issue with the access token being missing or malformed.
When the function tries to make a request to the Graph API to get the user by email (graphClient.users.list), it throws the following error:
note: I am using postman to test the api http://localhost:7071/api/checkEmail
Error verifying email: RestError: {"odata.error":{"code":"Authentication_MissingOrMalformed","codeForMetrics":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."}}}
This occurs despite using DefaultAzureCredential from @azure/identity to acquire the token.
I have checked my Azure AD configuration and environment variables (AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET) which seem to be correct.
Here's the relevant part of my Azure Function code:
const { GraphRbacManagementClient } = require("@azure/graph");
const { DefaultAzureCredential } = require("@azure/identity");
const tenantId = process.env.AZURE_TENANT_ID;
module.exports = async function (context, req) {
context.log('Checking if email is verified...');
const { email } = req.body;
if (!email) {
context.res = {
status: 400,
body: "Please provide the email"
};
return;
}
try {
const credential = new DefaultAzureCredential();
const graphClient = new GraphRbacManagementClient(
credential,
tenantId
);
const verifyEmail = async (email) => {
try {
const users = await graphClient.users.list({ filter: `mail eq '${email}'` });
const user = users.next().value;
if (user) {
if (user.mailVerified) {
return true;
} else {
return false;
}
} else {
return false;
}
} catch (error) {
console.error("Error verifying email:", error);
return false;
}
};
const isEmailVerified = await verifyEmail(email);
if (isEmailVerified) {
context.res = {
status: 200,
body: "Email is verified"
};
} else {
context.res = {
status: 400,
body: "Email is not verified or does not exist"
};
}
} catch (error) {
console.error("Error:", error);
context.res = {
status: 500,
body: "Internal Server Error"
};
}
};
Also, I have already tried using ClientSecretCredential directly instead of DefaultAzureCredential, but the issue persists. Azure AD permissions seem to be configured correctly for the app registration.
What could be causing this "Access Token missing or malformed" error in my Azure Function? How can I ensure the access token is properly acquired and used for authentication with the Graph API?
Any insights or suggestions would be greatly appreciated. Thank you!