Encounter 401 authentication issue, to accomplish send a mail / scheduling a meeting via MS graph api
- get access token via this link:https://dzone.com/articles/getting-access-token-for-microsoft-graph-using-oau
var authUrl = "https://login.microsoft.com";
var appId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var appSecret = HttpUtility.UrlEncode("xxxxxxxxxxxxxxxxxxxxx");
var tenantId = "xxxxxxxxxxxxxxxxxxx";
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post,
$"{authUrl}/{tenantId}/oauth2/token");
var bodyStr =
$"grant_type=client_credentials&appId={appId}&resource={HttpUtility.UrlEncode("https://graph.microsoft.com")}&client_secret={appSecret}";
var body = new StringContent(bodyStr);
body.Headers.ContentType.MediaType = "application/x-www-form-urlencoded";
request.Content = body;
var getTokenResult = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
try
{
token = JObject.Parse(getTokenResult)["access_token"].ToString();
}
catch (Exception /*ex*/)
{
throw new Exception(getTokenResult);
}
appId, appSecret, tenantId, please refer to the link https://dzone.com/articles/getting-access-token-for-microsoft-graph-using-oau
- Call ms graph api
using (var client = new HttpClient())
{
//var mail = authContext.ConversationData.GetValue<SendAMail>("SendAMail");
var jsonMail = JsonConvert.SerializeObject(mail);
var content = new StringContent(jsonMail, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _token);
client.DefaultRequestHeaders.Add("Accept", "application/json");
using (
var response =
await
client.PostAsync("https://graph.microsoft.com/v1.0/users/xxxx@dd.com/sendMail/", content))
{
string replyMsg;
if (response.IsSuccessStatusCode)
// replyMsg = "Done";
replyMsg = NLS.Mctwo_TXT_MailDialog_Done;
else
//replyMsg = "I am sorry, I cannot connect to authorization server, email cannot be sent.";
replyMsg = NLS.Mctwo_TXT_MailDialog_IASNC;
await context.PostAsync(replyMsg);
}
}
Here, I apply the application permission, so that https://graph.microsoft.com/v1.0/users/xxxx@dd.com/sendMail/. the url contains users/o365 mail address. If you can apply delegate permission, it should be like this:https://graph.microsoft.com/v1.0/me/sendMail/
conclusion:
- https://dzone.com/articles/getting-access-token-for-microsoft-graph-using-oau to grant ms graph permission
- Your test office 365 account must own the license.or you are one owner of your application in Azure.However this application was created by o365 license account.
- because I apply the application permission to execute MS graph api which requres Admin account to grant permission one time.