I'm using this tutorial: Sign in users and call the Microsoft Graph API from a React single-page app (SPA) using auth code flow to my registered app on in Azure Active Directory
I want to get contacts from my Outlook Contacts so I added the Contacts.Read
delegated permission.
After logging in (after I consent to the permission to read contacts) I can successfully issue a GET call to https://graph.microsoft.com/v1.0/me
using the auth token.
When I use the same to token to call the https://graph.microsoft.com/v1.0/me/contacts
endpoint, I get an HTTP 404
error:
{
"error": {
"code": "ResourceNotFound",
"message": "Resource could not be discovered.",
"innerError": {
"date": "2023-03-23T14:50:53",
"request-id": "d4e9c0cc-06f4-4c2a-9969-7889a968f5ba",
"client-request-id": "d4e9c0cc-06f4-4c2a-9969-7889a968f5ba"
}
}
}
I can use Graph Explorer to retrieve my contacts, but when using my own token I get above error.
I'm not sure why this happen, am I miss something?
I agree with @Nam Nguyen, to resolve the error make use of
@microsoft/microsoft-graph-client
in the code.
Install and import the module by using below command:
npm install @microsoft/microsoft-graph-client
import @microsoft/microsoft-graph-client
Modify the code like below to fetch the contacts:
export async function getUser(authProvider: AuthCodeMSALBrowserAuthenticationProvider): Promise<User> { ensureClient(authProvider);
const user: User = await graphClient!.api('/me')
.select('displayName, mail, mailboxSettings, userPrincipalName')
.get();
return user;
var response: PageCollection = await graphclient!
.api('/me/contacts')
.get();
For more in detail, refer the GitHub Blog by jasonjoh : GitHub - This sample demonstrates how to use the Microsoft Graph JavaScript SDK to access data.
I tried to reproduce the same in my environment in Postman and got the results like below:
I created an Azure AD SPA Application and granted API permissions:
Now, I generated access token using PKCE flow like below:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientID
scope:https://graph.microsoft.com/.default
grant_type:authorization_code
code:code
code_verifier:S256
redirect_uri:https://jwt.ms
By using the above generated access token, I am able fetch the contacts like below:
https://graph.microsoft.com/v1.0/me/contacts