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.