r/GraphAPI • • Aug 21 '24

filtering on a upn for auditLogs directoryAudits

3 Upvotes

I want to view the audit logs for a user but I can't seem to figure out how to filter by user I've tried a couple iterations of

https://graph.microsoft.com/v1.0/auditLogs/directoryAudits?`$filter=startsWith(givenName, 'a')

but that is giving me

"message": "Invalid filter clause: Could not find a property named \u0027givenName\u0027 on type
 | \u0027microsoft.graph.directoryAudit\u0027."

anybody been able to hit this endpoint and filter for a user?


r/GraphAPI • • Nov 06 '24

Question regarding what '-DeviceID' New-MgDeviceRegisteredOwnerByRef is requesting

1 Upvotes

Hey all, trying to figure out what Device ID that New-MgDeviceRegisteredOwnerByRef is needing.

I tried entering all versions of the ID I could see when running

GET https://graph.microsoft.com/v1.0/deviceManagement/managedDevices

but none of the IDs seem to work, I just get the error

Get-MgDeviceRegisteredOwner : Resource '{UID}' does not exist or one of its queried reference-property objects are not present.

Status: 404 (NotFound)

Any help would be greatly appreciated!


r/GraphAPI • • Aug 12 '24

Graph Request on email messages fails with "ErrorItemPropertyRequestedFailed"

1 Upvotes

Recently faced a issue in Graph API while requesting details of outlook email messages with error message 'ErrorItemPropertyRequestedFailed' which is said to occur if a property that may exist, but couldn't be retrieved (reference)

I selected all available props of a email message with query
https://graph.microsoft.com/v1.0/me/mailfolders/inbox/messages?$select=*"

To know the prop on which the request fails, I broke down the query by selecting specific props and found that uniqueBody is the one that couldn't be retrieved in graph request. while excluding this from the selected query it doesn't throw any error and including it in query does.

I need UniqeBody content for some use case and I cannot skip it in the request. I guess, the large uniqueBody content might be the reason that makes the retrieval process fail.

Is there anything that I could make like adding parameters to request headers that throttles this case (heavy Uniquebody content) or anything that could help me retrieving those details/just skip the message that face this error. It becomes difficult to get the other message details as no delta or next link is obtained in response while facing this error.

Thanks in advance.


r/GraphAPI • • Sep 17 '23

Best alternative for Distribution List management

1 Upvotes

Hi - looks like there are several limitations of Graph API for managing Distribution Lists - e.g. can't list owners, can't change many properties, etc. What's the best alternative API solution for that? Thanks!

(Graph seems fine of course for managing M365 Groups.)


r/GraphAPI • • Apr 20 '24

Error - deviceIdentityAttestationDetail does not exist when trying to get device info

2 Upvotes

i have PowerBI that used to work last year. i have not used it for a while but now i am getting an error.

DataSource.Error: OData: The property 'deviceIdentityAttestationDetail' does not exist on type 'microsoft.graph.managedDevice'. Make sure to only use property names that are defined by the type or mark the type as open type.
Details:
DataSourceKind=OData
DataSourcePath=https://graph.microsoft.com/beta/deviceManagement/managedDevices

if i change the DataSourcePath to just https://graph.microsoft.com/beta/deviceManagement, i can see the resources under it. i can drill down templates table and see the data. I can also view deviceCategories table and deviceConfigurations table. but when i select managedDevices, i get the deviceIdentityAttestationDetail error. i also get the same error when i select comanagedDevices.

is there anything i can do on the PowerBI side? if it is on the Azure side, any idea what needs to be changed so I can relay it to our admin?

below are steps in PowerBI

let

token_uri = "https://login.windows.net/" & #"Azure AD Tenant ID" & "/oauth2/token",

resource="https://graph.microsoft.com",

tokenResponse = Json.Document(Web.Contents(token_uri,

[

Content = Text.ToBinary(Uri.BuildQueryString(

[

client_id = #"Azure Application Client ID",

resource = resource,

grant_type = "client_credentials",

client_secret = #"Azure Application Client Secret"

]

),)

Headers = [Accept = "application/json"], ManualStatusHandling = {400}

]),)

access_token = tokenResponse[access_token],

Source = OData.Feed("https://graph.microsoft.com/beta/deviceManagement/managedDevices?$filter=operatingSystem eq 'Windows'", [ Authorization = "Bearer " & access_token ], [ ExcludedFromCacheKey = {"Authorization"}, ODataVersion = 4, Implementation = "2.0" ],)

#"Inserted Local Time" = Table.AddColumn(#"Renamed Columns", "lastSyncLocalDate", each DateTimeZone.ToLocal([lastSyncDateTime], type datetimezone))

in

#"Inserted Local Time"


r/GraphAPI • • Mar 09 '24

Add a group with read/write access to a specific folder within a users OneDrive ?

1 Upvotes

tl;dr - I have got as far as scripting everything from getting the user, their one drive id, the folder id and then the permissions on the folder so that it checks if the group exists or not. This is the final hurdle. I am trying to ADD a group ( by group ID ) with read/write permissions to this folder. I don't want to send a sharing link. I just want to straight up ADD the group with access to this folder.

I currently get a "400 - Bad Request" response.

The Graph Explorer doesn't seem to show addining of OneDrive permissions and the documentation around it seems to only focus on sending invite links.

I am making a POST call to https://graph.microsoft.com/v1.0/drives/[$OneDrive_ID]/items/[$Folder_ID]/permissions

and in the request body I am passing JSON:

{
  "roles": ["write"],
  "grantedToIdentities": [
    {
      "user": {},
      "group": {
        "id": "12345"
      }
    }
  ]
}

I have tried many variations of the POST URL

Any help appreciated, thank you


r/GraphAPI • • Sep 25 '24

Graph Batch Request & Azure App Service Failing

1 Upvotes

I have a batch request that works flawlessly when I'm debugging on IIS Express, but as soon as I publish to an Azure App Service the batch returns error 400 for every request in the batch.

The max number of user calendars I'm requesting is around 10, but it fails even if I just add 1 to the batch. I can pull individual calendars using CalendarView.GetAsync locally or on the app service so it's definitely something with the batch request.

List<string> eventRequests = [];

foreach (var user in users)

{

var eventRequest = graphClient.Users[user.UserPrincipalName].CalendarView

.ToGetRequestInformation(requestConfiguration =>

{

requestConfiguration.QueryParameters.StartDateTime = startTime.ToString();

requestConfiguration.QueryParameters.EndDateTime = endTime.Value.ToString();

});

eventRequests.Add(await batchRequestContent.AddBatchRequestStepAsync(eventRequest, user.UserPrincipalName));

}

var returnedResponse = await graphClient.Batch.PostAsync(batchRequestContent);


r/GraphAPI • • Aug 01 '23

Cannot Read User Authentication Methods

1 Upvotes

Edit: Never mind. Even Microsoft recommends I just use the HTTP API. I'm just going to use that instead. JFC.

Starting from a Microsoft-provided C# sample application, I tried to write a small script that reads a user's 2FA authentication methods. My app is registered in Azure, with rights for User and Directory ReadWriteAll. I also placed it in the Authentication Administrator role.

When I read a user, I can read the display name, mail, id, etc. However, Authentication is always null. I'm at a loss as to what other rights I need to add. I'm using Visual Studio 2022, GraphServiceClient 2.13.1, Microsoft.Graph 5.12.0. If anyone can shed some light I'd be most grateful.

TokenAcquirerFactory tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
IServiceCollection services = tokenAcquirerFactory.Services;
services.AddMicrosoftGraph();
var serviceProvider = tokenAcquirerFactory.Build();
GraphServiceClient graphServiceClient = serviceProvider.GetRequiredService<GraphServiceClient>();
var t = await graphServiceClient.Users.GetAsync((requestConfiguration) =>
{
    requestConfiguration.Options.WithAppOnly();
    requestConfiguration.QueryParameters.Filter = "startsWith(displayName,'<literally any user>')";
    requestConfiguration.QueryParameters.Select = new[] { "*" };
});
foreach (User u in t.Value.ToArray())
{
    //These two work fine
    Console.WriteLine(u.Mail);
    Console.WriteLine(u.Id);
    //Authentication is always null no matter what, and I've checked they indeed have auth phone options
    if (u.Authentication != null)
        foreach (PhoneAuthenticationMethod p in u.Authentication.PhoneMethods)
            Console.WriteLine(p.PhoneNumber + ", " + p.Id);
}

r/GraphAPI • • Feb 01 '25

Requist acces token customer

2 Upvotes

Hey everyone,
I am trying to build an app that can add appointments into their calendar. For this I need an acces token. I use python code to do this:

SCOPES = ["User.Read", "User.Export.All"]
app = PublicClientApplication( O365_CLIENT_ID, authority=AUTHORITY, )
flow = app.initiate_device_flow(scopes=SCOPES)
print(flow["message"])
webbrowser.open(flow["verification_uri"])
result = app.acquire_token_by_device_flow(flow)

the problem is when I input my code into the signin website and sign in with my account, I get the error that the code is epired. Iam using the codes immedialty after generation and am allowed to log in but when it should go to the authorization screen it tells me that my code expired. Which is unexpected, because normally it give that error before login.

when I set the authorization url to AUTHORITY = 'https://login.microsoftonline.com/your_tenant_id' I am able to login, but only with my orginistation emails and not emails of customers.

is there anybody that can help me with this. If anybody knows how to do this in curl that would be good as well.


r/GraphAPI • • Jul 19 '23

Anyone got any experience setting Sharepoint site permissions using Graph API?

2 Upvotes

When we signed a new client, our old method was to create a folder on our file server named after the client, and to create an security group with modify permissions on said folder.

I've been tasked with moving this process into sharepoint and to script the process so it happens automatically as part of our 'project creation' Jenkins job.

I've used Python and Graph API and managed to successfully create the sharepoint and the security group. I just can't then assign the permissions and can't see any instructions online. I can see instructions on how to view access control lists, but not how to set them.

I've searched the internet and haven not found a solution! Not helpful that when I search graph API site permissions it assumes you're talking about the permission of your Azure app. Chat GPT wasn't much helpful either.

Has anyone got any experience of this or am I going to have to use another module (not ideal as feels unclean and will probably also mean updating our Jenkins workers which is a pain)


r/GraphAPI • • Aug 15 '23

Device + configuration profiles

1 Upvotes

Hey everyone, Kind of losing it looking through this nonsense documentation. Is there any flipping way to get a configuration profile, list off all devices that are connected to it and it's compliance state?

Or devices, configuration profiles, and the state?

Even if they were 2-3 different exports I can connect them but I can grab the list of profiles /Beta/deviceManagement And the devices /Beta/devices

But I can not find a way to expand either of them enough to connect the dots.

My request is to basically say.. $Configurationpolicyid = "1234abcd" List Devices with this policy and there state.

I. E. CIS policy | workstation | compliant

Any help would be appreciated


r/GraphAPI • • Jul 17 '23

Report of mailboxes that are shared

1 Upvotes

Hello,

I am new to Graph and trying to find practical reports I can generate and was thinking a good one would be a list of mailboxes (users) that have been shared with others.

Maybe a CSV that lists.

Mailbox Name, Access by, SendAs, Full Control

John CEO, Sally Assistant, SendAs, Full Control

Betsy COO, Bill Assistant, FullControl

Anyone have any insight how I can approach this?

Thanks - starting to feel the power of Graph API!


r/GraphAPI • • Jan 09 '25

how to send a Chat message to a user using Microsoft Graph from postman?

1 Upvotes

i used the followig method

POST https://graph.microsoft.com/v1.0/users/UserId/chats/{ChatID}/messages

First i created OneOnOne chat and then with the Chat Id i tried to send a message

I have applied permissions that documentation recommend for the App, but i´m having this issue

"error": {
"code": "Unauthorized",
"message": "Message POST is allowed in application-only context only for import purposes. Refer to https://docs.microsoft.com/microsoftteams/platform/graph-api/import-messages/import-external-messages-to-teams for more details."


r/GraphAPI • • Feb 17 '25

Can you use Github repo's OIDC token in Powershell to Connect-Mggraph?

1 Upvotes

I have a github repo that has a federated credential with Entra. My github actions workflow works perfectly with OIDC.

I would like to know if I could leverage to OIDC token to connect to Mg Graph from a powershell script in the same repo.

Has anyone done this? can you let me know how?


r/GraphAPI • • Apr 02 '24

To apply SiteDesign to a site

1 Upvotes

Is there a way in graph api to apply site design to a SharePoint site?


r/GraphAPI • • Aug 20 '23

Getting user sign in attempt success/failure state

2 Upvotes

Hi, This morning when I was messing around with graph api data, i saw a lastsign in date filled out for last week on a disabled user account (mailbox account which is disabled for a long time). It showed last login date (?!) sign in state however showed as "failed" in the azure portal .. For this reason I am looking for a way to get the sign in state for successfull login or failed login. The only method I found so far is to loop through signinauditlog for the last sign in attempt for each user.. but this takes more then 5hours for 6000+ accounts .. has anyone found a better method for this ?


r/GraphAPI • • Aug 19 '24

PowerBi Odata from Graph, for Sites

1 Upvotes

Following numerous tutorials online, I have successfully configured a query in PowerBi to connect to Microsoft Graph and pull down a list of SharePoint Online Sites (and subsites). It uses a Azure app to provide the relevant permissions to get the data, with a shared seceret for authentication.

Here's the advanced query:

let 
    resource="https://graph.microsoft.com",
    tokenResponse = Json.Document(Web.Contents("https://login.windows.net/",
    [
        RelativePath = #"Tenant ID" & "/oauth2/token",
        Content = Text.ToBinary(Uri.BuildQueryString(
            [
                client_id = #"Azure Application ID",
                resource = resource,
                grant_type = "client_credentials",
                client_secret = #"Azure Application Client Secret"
            ]
        )),
        Headers = [Accept = "application/json"], ManualStatusHandling = {400}
    ])),
    access_token = tokenResponse[access_token],
    Source = OData.Feed("https://graph.microsoft.com/beta/sites", [ Authorization = "Bearer " & access_token ], [ ExcludedFromCacheKey = {"Authorization"}, ODataVersion = 4, Implementation = "2.0" ]),
    #"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1, Int64.Type)
in
    #"Added Index"

Next I want to reduce the amount of data being imported, to speed things up. No point importing all of it and then filtering it, its going to be slow.

The most obvious filter to start with is ignoring OneDrive sites by checking 'isPersonalSite' = FALSE. No matter syntax I try, it does not work.

Alternatively, looking in the 'id' for only <domainname>.sharepoint.com. ignoring all those that are <domainname>-my.sharepoint.com.

Any suggestions on how to get one of these working with Sites? (Ideally the 'isPersonalSite' one)

Thanks in advanced for ideas and suggestions :)


r/GraphAPI • • Jan 24 '25

Help with graph query against immutable Id

4 Upvotes

I'm writing Graph queries to pull message metadata from Exchange. It GENERALLY works great, but there are some exceptions where the message exists, but Graph cannot find it by searching for the Internet Message Id. I can find the message in my mailbox, and in Defender 365 Explorer.

From what I'm reading, I think I may need to find the message using its ImmutableId. Seems simple enough, but I cannot for the life of me figure out how to search mailbox messages by Immutable ID. Does anyone have any idea?

I have spent hours searching and testing, I wish I kept a log of my attempts. But I have face planted and wound up on this page, where people have complained about inability to search messages on Immutable Id since 2023:

https://learn.microsoft.com/en-us/answers/questions/1282123/idtype-immutableid

Does anyone here know anything better? Or am I destined to put in a ticket tomorrow and see how long that takes to get a reply? Or be told that I need to do it another way, which will somehow work worse than what I've already been doing? :)


r/GraphAPI • • Mar 27 '24

List all SharePoint sites in a script without an app?

2 Upvotes

Am I understanding the docs here correctly that when it says "Delegated: Not Supported" it means I must create an app to access this data? I've tried in PowerShell and Graph Explorer and I cannot get it to list all SharePoint sites.

I've also tried Get-MgSite and it returns nothing.

Is it because I'm not using an app? Do I really have to?


r/GraphAPI • • Jan 09 '24

Why do I need Graph to generate the most basic report?

2 Upvotes

If you copy and paste this link, you should have a view of all your users with a Last Interactive sign-in time column (Tenant Global Admin role or other needed to view).

https://portal.azure.com/#blade/Microsoft_AAD_UsersAndTenants/UserManagementMenuBlade/search//filter/%257B%257D/select/displayName%2CuserType%2CsignInActivity

All I want is a report on blank or > 12-month-old logins. I can filter on 12-month-old logins, but not blank. You can't sort the column for some reason, and if you Download Users, it doesn't include the relevant columns.

Everything I read online (AI included) is telling me to use Graph API. Is this true? I can't tell you how frustrating it is to see the data but not get it out to the people who need it. I've already manually copied and pasted user by user for a report for the last two quarters, but I want to start fresh for 2024 and do this right. Any tips?


r/GraphAPI • • Nov 29 '23

Getting a list of all meeting and call IDs

1 Upvotes

Hi

I am trying to get full call stats, a bit like the VoIP platforms offer. 

Most of the information I need is accessible using "List sessions". But this can only be used for a single "Meeting or call ID". 

How can I get a list of all users 'Meeting or call ID' as shown on https://admin.teams.microsoft.com/ in this section 'users/Manage Users/[user]/Meetings and calls'? I opened a ticket with support, but they don't seem to know.

Note: The information shown with getPstnCalls is incomplete (e.g., call transfer is not shown), and it does not provide a proper call ID to be used with 'List sessions'.

Thanks


r/GraphAPI • • Jul 01 '24

Permissions

2 Upvotes

Hello guys

Is there any way to send calendar events to my university account without when i do not have permissions to register applications in azure ?

I made a script that scrapes my university schedule and now I want to send it to office calendar in the university account so when any student uses it sends it to the calendar but i do not find a way if i cannot register the apps in azure, permitions that i do not have. Have anybody been through similar or know a solution to the problem ?


r/GraphAPI • • Jan 13 '25

Extension attributes for a serialnumber

1 Upvotes

How to get extension attributes from https://graph.microsoft.com/v1.0/deviceManagement/managedDevices call for a particular serial number


r/GraphAPI • • Mar 26 '24

Getting errors trying to bulk update user contact information in Office 365

1 Upvotes

I am getting the following error when try to bulk update users contact information using PowerShell and a CSV file.

Update-MgUser : Invalid value specified for property 
'officeLocation' of resource 'User'.
Status: 400 (BadRequest)
ErrorCode: Request_BadRequest
Date: 2024-03-26T17:05:02
Headers:
Transfer-Encoding             : chunked
Vary                          : Accept-Encoding
Strict-Transport-Security     : max-age=31536000
request-id                    : e564c626-6a9d-4229-9762-c1c1ff50b3fd
client-request-id             : bcd83082-18c4-40df-a1cf-26fd77908be9
x-ms-ags-diagnostic           : {"ServerInfo":{"DataCenter":"Canada Central","Slice":"E","Ring":"5","ScaleUnit":"001","RoleInstance":"YT1PEPF00001AC2"}}
x-ms-resource-unit            : 1
Cache-Control                 : no-cache
Date                          : Tue, 26 Mar 2024 17:05:01 GMT
At C:\azure\AzureADInport3.ps1:80 char:13

Here is the script that I am using

# Connect to Microsoft Graph
Connect-MgGraph -Scopes User.ReadWrite.All

# Read the CSV file
$users = Import-Csv -Path "C:\Azure\AllAzureADUsers.csv"

# Go through each user in the CSV and update the properties foreach ($user in $users) {
$Userprincipalname = $user.Userprincipalname
$jobTitle = $user.JobTitle
$country = $user.Country
$CompanyName = $user.CompanyName
$StreetAddress = $user.StreetAddress
$City = $user.City
$Postalcode = $user.Postalcode
$State = $user.State
$Country = $user.Country
$MobilePhone = $user.MobilePhone
$BusinessPhones = $user.BusinessPhones

# Check if the user exists
$existingUser = Get-MgUser -UserID $Userprincipalname -ErrorAction SilentlyContinue

if ($existingUser) {
    # Check if the existing properties match the new values
    $updateNeeded = $false

    if ($existingUser.Userprincipalname -ne $Userprincipalname) {
        $existingUser.Userprincipalname = $Userprincipalname
        $updateNeeded = $true
    }

    if ($existingUser.JobTitle -ne $jobTitle) {
        $existingUser.JobTitle = $jobTitle
        $updateNeeded = $true
    }

    if ($existingUser.CompanyName -ne $CompanyName) {
        $existingUser.CompanyName = $CompanyName
        $updateNeeded = $true
    }

    if ($existingUser.StreetAddress -ne $StreetAddress) {
        $existingUser.StreetAddress = $StreetAddress
        $updateNeeded = $true
    }

    if ($existingUser.City -ne $City) {
        $existingUser.City = $City
        $updateNeeded = $true
    }

    if ($existingUser.Postalcode -ne $Postalcode) {
        $existingUser.Postalcode = $Postalcode
        $updateNeeded = $true
    }

    if ($existingUser.State -ne $State) {
        $existingUser.State = $State
        $updateNeeded = $true
    }

    if ($existingUser.Country -ne $country) {
        $existingUser.Country = $country
        $updateNeeded = $true
    }

    if ($existingUser.MobilePhone -ne $MobilePhone) {
        $existingUser.MobilePhone = $MobilePhone
        $updateNeeded = $true
    }

    if ($existingUser.BusinessPhones -ne $BusinessPhones) {
        $existingUser.BusinessPhones = $BusinessPhones
        $updateNeeded = $true
    }

    if ($updateNeeded) {
        # Update the user properties
        Update-MgUser -UserID $userPrincipalName -JobTitle $jobTitle -CompanyName $CompanyName -OfficeLocation $OfficeLocation -StreetAddress $StreetAddress -City $City -Postalcode $Postalcode -State $State -Country $country
        Write-Host "User '$Userprincipalname' updated successfully." -ForegroundColor Green
    }
    else {
        Write-Host "User '$Userprincipalname' properties are up to date." -ForegroundColor Cyan
    }
}
else {
    # User not found
    Write-Host "User '$Userprincipalname' not found." -ForegroundColor Red
}

Any ideas?