I'm trying to get the current user's datas with Graph API. I'd like to get the access token and append it to the request message. So I'd like to skip the login UI. Some reason I get the (401) Unauthorized error, invalid user... I registered my app(mvc) AAD, and the secret, client id, tenant id from there.
This is the method to get the token:
public static string GetToken()
{
string authority = "https://graph.microsoft.com/{tenantID}/oauth2/token";
string clientId = "client id";
string secret = "client secret";
string resource = "https://graph.microsoft.com";
AuthenticationContext authContext = new AuthenticationContext(authority);
ClientCredential clientCredential = new ClientCredential(clientId, secret);
AuthenticationResult authResult = authContext.AcquireToken(resource, clientCredential);
return authResult.AccessToken;
}
And this is the code, where I append the access token:
public static GraphServiceClient GetAuthenticatedClient()
{
GraphServiceClient graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
string accessToken = GetToken();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}));
return graphClient;
}
Any advice would be helpful, beacuse I have no idea.
There are two kinds of access token issued by Azure AD.
The first one is delegate-token which used to delegate the user to operate user's resource.
And the other one is application token which usually used to perform the operation for the resource of all organization and there is no user context(current user) in this token. So we shouldn't use this token to perform the resource as me
which required the user context.
To operate the resources using the application token, we need to specify the user using users collection like code below:
string userId = "";
var user = graphserviceClient.Users[userId].Request().GetAsync().Result;