I’m basically trying to write a C# application to send a push notification to Microsoft Authenticator app something like 2FA authentication.
The user will need to confirm via his/her phone by typing the number shown.
And I’ve got the C# code below and I can I’m able to get the access token.
I’ve created App Registration in Azure.
But I’m getting 405-Method not allowed error on Graph post part.
I think I need to give some permissions but not sure which one(s).
My understanding is I need to give Graph Device related permissions under API Permissions.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.UI;
namespace YourNamespace
{
public partial class PushNotification : Page
{
private readonly string _tenantId = "YOUR_TENANT_ID";
private readonly string _clientId = "YOUR_CLIENT_ID";
private readonly string _clientSecret = "YOUR_CLIENT_SECRET";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string accessToken = GetAccessToken(_tenantId, _clientId, _clientSecret);
if (!string.IsNullOrEmpty(accessToken))
{
string graphApiEndpoint = $"https://graph.microsoft.com/v1.0/applications/{_clientId}/sendCustomNotificationToDevices";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string notificationJson = @"
{
""messageTemplateName"": ""myMessage"",
""notification"": {
""type"": ""basic"",
""title"": ""Hello"",
""body"": ""This is a test notification from your app.""
}
}";
var content = new StringContent(notificationJson, Encoding.UTF8, "application/json");
var response = client.PostAsync(graphApiEndpoint, content).Result;
if (response.IsSuccessStatusCode)
{
ResultLabel.Text = "Notification sent successfully!";
}
else
{
ResultLabel.Text = $"Failed to send notification: {response.ReasonPhrase}";
}
}
}
else
{
ResultLabel.Text = "Failed to obtain access token";
}
}
}
private string GetAccessToken(string tenantId, string clientId, string clientSecret)
{
string tokenUrl = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token";
using (var client = new HttpClient())
{
var requestParams = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("scope", "https://graph.microsoft.com/.default"),
});
var response = client.PostAsync(tokenUrl, requestParams).Result;
if (response.IsSuccessStatusCode)
{
var jsonResult = response.Content.ReadAsStringAsync().Result;
dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResult);
return json.access_token;
}
return null;
}
}
}
}