Reputation: 147
i want to use the Graph Api to access the o365 inbox to process the incoming mails.without user signed in ( Application permission) .
with that i can able to get the access token but i cant able to access the inbox. and the code as follows.
//Defining app
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientSecret(config.ClientSecret)
.WithAuthority(new Uri(config.Authority))
.Build();
//Getting access token
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
//graph service client
GraphServiceClient graphClient = new GraphServiceClient(new
DelegateAuthenticationProvider(async (requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
}));
//accessing Ms graph api
var messages = await graphClient.Me.Messages
.Request()
.Select(e => new {
e.Sender,
e.Subject
})
.GetAsync();
Code: BadRequest Message: Current authenticated context is not valid for this request. This occurs when a request is made to an endpoint that requires user sign-in. For example, /me requires a signed-in user. Acquire a token on behalf of a user to make requests to these endpoints. Use the OAuth 2.0 authorization code flow for mobile and native apps and the OAuth 2.0 implicit flow for single-page web apps.
Inner error
I dont know what i am doing wrong here please help me
Upvotes: 0
Views: 233
Reputation: 17702
You cannot use .Me
since there is no authenticated user. You need to instead do something like:
//accessing Ms graph api
var messages = await graphClient.Users["user-id"].Messages
.Request()
.Select(e => new {
e.Sender,
e.Subject
})
.GetAsync();
Where user-id
is either the user's id
from Graph, or their UPN (typically their email address).
Upvotes: 2