I am looking to update device ownership of a device in AAD using Microsoft Graph API
This closest I have come to is https://learn.microsoft.com/en-us/graph/api/device-post-registeredowners?view=graph-rest-1.0&tabs=csharp but this needs delegated permission.
I would like to do it directly using Application permission type because I have to do the ownership change using a background process without any user involvement.
Note: My devices are not managed by In-tune
I have tried looking for APIs but I was not very successful. I got it working by using new GraphServiceClient(new InteractiveBrowserCredential());
graph api client but it needs user input which is a no for my user case
I got the error when I tried to registered owner of the device using application Api permissions via clientSecretCredential
:
class Program
{
static async Task Main(string[] args)
{
string clientId = "ClientID";
string tenantId = "TenantID";
string clientSecret = "Secret";
string deviceId = "DeviceID";
string ownerId = "OwnerID";
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential);
try
{
var ownerReference = new ReferenceCreate
{
OdataId = $"https://graph.microsoft.com/v1.0/directoryObjects/{ownerId}"
};
await graphClient.Devices[deviceId].RegisteredOwners.Ref.PostAsync(ownerReference);
Console.WriteLine("User added as a registered owner successfully.");
}
catch (ODataError odataError)
{
Console.WriteLine($"OData Error: {odataError.Error?.Message}");
if (odataError.Error?.InnerError != null)
{
Console.WriteLine($"Error Code: {odataError.Error?.Code}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Note that: Application permissions are not supported to add a user as a registered owner of the device and there is no other use application Api permission.
class Program
{
static async Task Main(string[] args)
{
string clientId = "ClientID";
string deviceId = "DeviceID";
string ownerId = "OwnerID";
// Use InteractiveBrowserCredential for interactive login
var interactiveCredential = new InteractiveBrowserCredential();
var graphClient = new GraphServiceClient(interactiveCredential);
try
{
var ownerReference = new ReferenceCreate
{
OdataId = $"https://graph.microsoft.com/v1.0/directoryObjects/{ownerId}"
};
await graphClient.Devices[deviceId].RegisteredOwners.Ref.PostAsync(ownerReference);
Console.WriteLine("User added as a registered owner successfully.");
}
catch (ODataError odataError)
{
Console.WriteLine($"OData Error: {odataError.Error?.Message}");
if (odataError.Error?.InnerError != null)
{
Console.WriteLine($"Error Code: {odataError.Error?.Code}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Reference: