Microsoft Graph "Access is denied. Check credentials and try again" in C#
Asked Answered
I

2

7

This is my code to get emails from my email account through Microsoft Graph, but I keep getting an error regardless on credentials.

Code:

var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "";
var clientId = "";
var clientSecret = "";

var clientSecretCredential = new ClientSecretCredential(
    tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var inboxMessages = await graphClient
                        .Users["email"]
                        .MailFolders["inbox"]
                        .Messages
                        .Request()
                        .Expand("attachments")
                        .Top(20)
                        .GetAsync();
Console.WriteLine(inboxMessages);
Console.ReadLine();

Error:

enter image description here

Permissions:

enter image description here

Isabea answered 30/9, 2022 at 16:32 Comment(7)
In the client credential flow there won't be any user authentication, so delegated permissions doesn't work. Please give application permissions in the API permissions in azure as to make it work.Moonrise
Let me know if this worked for you. Will convert it to answer.Moonrise
But the permissions aren't the ones of the printscreen above? @ShivaKeshavVarma Thank you for your replyIsabea
No, there are two types of permissions. Application permissions and delegated permissions. Here if you have a user logging into the app then you would use a different flow and you can use these delegated permissions. But here there is no user as it's a client credential flow. So use application permissions to make the above code work.Moonrise
Got it. Check the post with the updated printscreen of my permissions. Is that what I need to do? If it is, it still doesn't work @ShivaKeshavVarmaIsabea
@ShivaKeshavVarma Actually it worked. Thank you so much! Put it as an awnser !!!! THANKS!Isabea
Glad that it worked for you!! 😊Moonrise
M
5

In the client credential flow there won't be any user authentication, so delegated permissions doesn't work. Please give application permissions in the API permissions in azure ad.

There are two types of permissions. Application permissions and delegated permissions. Here if you have a user logging into the app then you would use a different flow and you can use these delegated permissions. But here there is no user as it's a client credential flow. So use application permissions to make the above code work.

Moonrise answered 1/10, 2022 at 18:9 Comment(3)
Does not work. Even both permissions were i have.Behold
Hi @BarisSenyerli, Please create a stackoverflow question and provide how you are authenticating and what api call you are making and wich account you are using. We will help you :)Moonrise
I check it out from Azure Graph Explorer it is even can not send request. I decided to move another mail service. Honestly it should be about MX records. Thanks for your kind wishes.Behold
S
0

I resolved this issue by correcting the way my scopes were declared in my code. Although my scopes were declared properly in Microsoft Azure, I did not correctly refer to them in my code. Having one scope as scopes = ['myscope'] seems to work fine, but more than one scope cannot be declared by name. For example `scopes = ['myscope1', 'myscope2'] will not work.

In order to access a user's profile with all scopes which are declared in Microsoft Azure, use scopes = ['https://graph.microsoft.com/.default'] (a list is required). https://graph.microsoft.com/.default refers to all scopes set for the program in Microsoft Azure, and the user will be prompted to agree to all scopes when logging in.

Here is my log-in flow code for Python 3.12:

import webbrowser
import msal
from msal import PublicClientApplication
from msgraph import GraphServiceClient
from msgraph.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
applicationID = '_put_yours_here_'
authorityURL = 'https://login.microsoftonline.com/consumers/'
OUTLOOK_BASEURL = 'https://graph.microsoft.com/v1.0/'
scopes = ['https://graph.microsoft.com/.default'] #Sets scopes to all scopes which are set in Microsoft Azure backend
thisApp = PublicClientApplication(applicationID, authority = authorityURL)
logInFlow = thisApp.initiate_device_flow(scopes = scopes)
print(logInFlow['user_code']) #User must type this into the Outlook login page
webbrowser.open(logInFlow['verification_uri'])
userToken = thisApp.acquire_token_by_device_flow(logInFlow)['access_token']
headers = {'Authorization': 'Bearer ' + userToken}
OUTLOOK_HEADERS = headers
OUTLOOK_SERVICE = GraphServiceClient(headers, scopes)
response = requests.get(OUTLOOK_BASEURL + '/me', headers = OUTLOOK_HEADERS)
OUTLOOK_BASEURL = OUTLOOK_BASEURL + '/me/'
Subdebutante answered 2/8 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.