{"id":19454144,"url":"https://github.com/21bshwjt/microsoftgraph","last_synced_at":"2025-02-25T10:21:59.542Z","repository":{"id":211058176,"uuid":"728092475","full_name":"21bshwjt/MicrosoftGraph","owner":"21bshwjt","description":"Microsoft Graph API","archived":false,"fork":false,"pushed_at":"2025-01-29T06:00:28.000Z","size":291,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-29T06:31:14.029Z","etag":null,"topics":["azure","graphapi","oauth2","powershell","rest-api","serviceprincipal"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/21bshwjt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-12-06T08:02:41.000Z","updated_at":"2025-01-29T06:00:32.000Z","dependencies_parsed_at":"2024-12-31T09:27:48.798Z","dependency_job_id":"16728b06-7564-4727-8d9c-df1852ba4042","html_url":"https://github.com/21bshwjt/MicrosoftGraph","commit_stats":null,"previous_names":["21bshwjt/microsoftgraph"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/21bshwjt%2FMicrosoftGraph","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/21bshwjt%2FMicrosoftGraph/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/21bshwjt%2FMicrosoftGraph/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/21bshwjt%2FMicrosoftGraph/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/21bshwjt","download_url":"https://codeload.github.com/21bshwjt/MicrosoftGraph/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240645844,"owners_count":19834493,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["azure","graphapi","oauth2","powershell","rest-api","serviceprincipal"],"created_at":"2024-11-10T17:08:09.149Z","updated_at":"2025-02-25T10:21:59.429Z","avatar_url":"https://github.com/21bshwjt.png","language":null,"readme":"# Microsoft Graph API\n[Microsoft Graph](https://developer.microsoft.com/en-us/graph/graph-explorer)  or  [https://aka.ms/ge](https://aka.ms/ge)  or  [https://ge.cmd.ms/](https://ge.cmd.ms/)\n\n### Graph Explorer\n\n```powershell\n# Default Query\nhttps://graph.microsoft.com/v1.0/me\n\n# Filtered Attributes\nhttps://graph.microsoft.com/v1.0/me?$select=id,userPrincipalName\n\n# User.Read.All - Permission is needed to run the below query\nhttps://graph.microsoft.com/v1.0/users?$select=id,userPrincipalName\n\n# Get Top three users\nhttps://graph.microsoft.com/v1.0/users?$top=3\u0026$select=id,userPrincipalName\n```\n\n### Retrieve users from the Microsoft Graph API using a User account (Tested with Global Admin)\n\n```powershell\n$url = \"https://graph.microsoft.com/v1.0/users\"\n$token = \"*************************************\"\n$header = @{Authorization = \"Bearer $token\"}\ninvoke-RestMethod -uri $url -Headers $header\n$result =invoke-RestMethod -uri $url -Headers $header\n$result.value\n$result.value | Measure-Object\n$result.value | Select-Object id,userPrincipalName\n```\n\n### Retrieve AAD users \u0026 Azure resources from the Microsoft Graph API using an Azure Service Principal\n\n\u003cimg src=\"https://github.com/21bshwjt/MicrosoftGraph/blob/main/Screenshots/perms.png?raw=true\" width=\"800\" height=\"320\"\u003e\n\n#### Above permissions are needed for that Application to work all the scripts mentioned here.\n- [**scope**](https://graph.microsoft.com/.default) uri is needed to query the AAD users \u0026 [**resource**](https://management.core.windows.net) uri is needed to query the AZ resources.\n- Authorization endpoint is not needed when \"**grant_type**\" is  \"**client_credentials**\". The token endpoint is only needed. **Token type: Access_Token**\n- Token Endpoint (V1) : [https://login.microsoftonline.com/\u003ctenant_Id\u003e/oauth2/token](https://login.microsoftonline.com/\u003ctenant_Id\u003e/oauth2/token) - Use that for AZ Resouces\n- Token Endpoint (V2) : [https://login.microsoftonline.com/\u003ctenant_Id\u003e/oauth2/v2.0/token](https://login.microsoftonline.com/\u003ctenant_Id\u003e/oauth2/v2.0/token) - Use that for AAD Users\n\n```powershell\n\u003c##\n.Description\nRetrieve users from the Microsoft Graph API using an Azure Service Principal\n\nSource: https://github.com/goodworkaround/bluescreen_scripts/blob/main/Working%20with%20the%20Microsoft%20Graph%20from%20PowerShell/get-access-token-manual.ps1\nhttps://github.com/goodworkaround/bluescreen_scripts/blob/main/Working%20with%20the%20Microsoft%20Graph%20from%20PowerShell/get-access-token-sdk.ps1\nhttps://github.com/BohrenAn/GitHub_PowerShellScripts/blob/main/AzureAD/CreateAADApp-MgGraph.ps1\n##\u003e\n\n# Define variables\n$tenantId = \"*********************\"\n$clientId = \"*********************\"\n$clientSecret = \"*****************\"\n\n# Define API endpoint and parameters\n$tokenEndpoint = \"https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token\"\n$tokenParams = @{\n    grant_type    = \"client_credentials\"\n    client_id     = $clientId\n    client_secret = $clientSecret\n    scope         = \"https://graph.microsoft.com/.default\"\n}\n\n# Get access token\n$accessToken = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -Body $tokenParams\n\n# Output access token\n#Write-Output $accessToken.access_token\n\n$result = Invoke-RestMethod \"https://graph.microsoft.com/v1.0/users\" -Headers @{Authorization = \"Bearer $($accessToken.access_token)\"}\n$result.value | Measure-Object\n$result.value | Select-Object id,userPrincipalName\n```\n\n### Microsoft Azure REST API's using Client credential flow\n\n```powershell\n# Microsoft Azure REST API's using Client credential flow\nConnect-AzAccount -Identity\n$tenantid = Get-AzKeyVaultSecret -VaultName \"\u003cKeyVault\u003e\" -Name \"\u003ctenantId_Seceret\u003e\" -AsPlainText\n$openid = Invoke-RestMethod -Uri \"https://login.microsoftonline.com/$tenantid/.well-known/openid-configuration\"\n$tokenendpoint = $openid.token_endpoint\n\n$body = @{\n    grant_type    = \"client_credentials\"\n    client_id     = \"\u003cClient_Id\u003e\"\n    client_secret = \"\u003cClient_Secret\u003e\"\n    redirect_uri = \"https://localhost\"\n    resource = \"https://management.core.windows.net\"\n    tenant = \"\u003cDomainname.com\u003e\" # optional\n    \n}\n\n$token = Invoke-RestMethod -Uri $tokenendpoint -Body $body -Method Post\n$access_token = $token.access_token\n\n$url = \"https://management.azure.com/subscriptions/\u003cSubscription_id\u003e/resources?api-version=2021-04-01\"\n$az_resources = Invoke-RestMethod $url -Headers @{Authorization = \"Bearer $($access_token)\"} -Method Get\n```\n\n### Retrieve AAD Users from the Microsoft Graph PowerShell using System Assigned Managed Identity(MSI) \u0026 KeyVault\n\n```powershell\n#Script is tested from Azure Automation Account \u0026 Azure VM\n#Requires -Module @{ ModuleName = 'Az.Accounts'; ModuleVersion = '2.13.2' }\n#Requires -Module @{ ModuleName = 'Az.KeyVault'; ModuleVersion = '5.0.1' }\n#Requires -Module @{ ModuleName = 'Microsoft.Graph.Authentication'; ModuleVersion = '2.10.0' }\n#Requires -Module @{ ModuleName = 'Microsoft.Graph.Users'; ModuleVersion = '2.10.0' }\nConnect-AzAccount -Identity\n$ApplicationId = Get-AzKeyVaultSecret -VaultName \"\u003cYour_KeyVault\u003e\" -Name \"\u003cClientId_Secret\u003e\" -AsPlainText\n$SecuredPassword = Get-AzKeyVaultSecret -VaultName \"\u003cYour_KeyVault\u003e\" -Name \"\u003cClient_Secret\u003e\" -AsPlainText\n$tenantID = Get-AzKeyVaultSecret -VaultName \"\u003cYour_KeyVault\u003e\" -Name \"\u003cTenantID_Secret\u003e\" -AsPlainText\n\n$SecuredPasswordPassword = ConvertTo-SecureString -String $SecuredPassword -AsPlainText -Force\n$ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList `\n$ApplicationId, $SecuredPasswordPassword\nConnect-MgGraph -TenantId $tenantID -ClientSecretCredential $ClientSecretCredential -NoWelcome\nGet-MgUser | Select-Object DisplayName, Id, UserPrincipalName\n```\n\n### Certificate based authentication using Service principle name\n\n```powershell\n# Permissions are needed as per the above screenshot. \n$client_id = \"*****************\"\n$tenant_id = \"********************\"\n$thumb_print = (Get-ChildItem \"Cert:\\LocalMachine\\my\" | Where-Object { $_.Subject -eq \"CN=*******\" }).Thumbprint\n\nConnect-MgGraph -ClientId $client_id -TenantId $tenant_id -CertificateThumbprint $thumb_print\n\n$result = Invoke-MgGraphRequest -Method GET -Uri \"https://graph.microsoft.com/v1.0/users\"\n$result.value\n$result.value | Select-Object id,displayName,userPrincipalName\n```\n\n### Create an Azure Application using Graph API\n\n```powershell\n# 'Application.ReadWrite.OwnedBy' - Permission is required\n$client_id = \"*****************\"\n$tenant_id = \"********************\"\n$thumb_print = (Get-ChildItem \"Cert:\\LocalMachine\\my\" | Where-Object { $_.Subject -eq \"CN=*******\" }).Thumbprint\nConnect-MgGraph -ClientId $client_id -TenantId $tenant_id -CertificateThumbprint $thumb_print\nNew-MgApplication -DisplayName \u003cMy_New_App1\u003e\n```\n\n### Get AAD Users from Azure Automation PowerShell RunBook\n```powershell\n# Get the Azure Automation connection object\n$connection = Get-AutomationConnection -Name \"\u003cAzure_SPI\u003e\"\n\n# Connect to Azure using the connection object\nTry {\n    Connect-MgGraph -ClientId $connection.ApplicationID `\n        -TenantId $connection.TenantID `\n        -CertificateThumbprint $connection.CertificateThumbprint\n}    \ncatch {\n    Write-Error -Message $_.Exception\n    throw $_.Exception\n}\n# Set the subscription context\nSet-AzContext -SubscriptionId \"\u003cSub_Id\u003e\" | Out-Null\nConnect-MgGraph -ClientId $client_id -TenantId $tenant_id -CertificateThumbprint $thumb_print -NoWelcome\n$result = Invoke-MgGraphRequest -Method GET -Uri \"https://graph.microsoft.com/v1.0/users\"\n#$result.value\n$result.value | Select-Object id,displayName,userPrincipalName\n```\n### Get Tenant Creation Date Using Postman\n- API : https://graph.microsoft.com/v1.0/organization\n- Access Token URL\n- Client ID\n- Client Secret\n- Scope : https://graph.microsoft.com/.default\n- Client Authentication:  Send as Basic Auth Header\n- Attribute : **createdDateTime**\n\n### Get Tenant Creation Date Using PowerShell\n\n```powershell\n# MSFT Graph API : https://learn.microsoft.com/en-us/graph/api/organization-list?view=graph-rest-1.0\u0026tabs=http\n# Define variables\n$tenantId = \"************************\"\n$clientId = \"************************\"\n$clientSecret = \"************************\"\n\n# Define API endpoint and parameters\n$tokenEndpoint = \"https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token\"\n$tokenParams = @{\n    grant_type    = \"client_credentials\"\n    client_id     = $clientId\n    client_secret = $clientSecret\n    scope         = \"https://graph.microsoft.com/.default\"\n}\n\n# Get access token\n$accessToken = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -Body $tokenParams\n\n# Output access token\n#Write-Output $accessToken.access_token\n\n$result = Invoke-RestMethod \"https://graph.microsoft.com/v1.0/organization\" -Headers @{Authorization = \"Bearer $($accessToken.access_token)\" }\n\n[PSCustomObject]@{\n    TenantCreationDate         = $($result.value.createdDateTime)\n    CustomDomain               = $($result.value.verifiedDomains.Name)\n    onPremisesSyncEnabled      = $($result.value.onPremisesSyncEnabled)\n    onPremisesLastSyncDateTime = $($result.value.onPremisesLastSyncDateTime)  \n    countryCode                = $($result.value.countryLetterCode)\n}\n\n```\n\n#### Output\n\u003cimg src=\"https://github.com/21bshwjt/MicrosoftGraph/blob/main/Screenshots/customdomain.png?raw=true\" width=\"800\" height=\"125\"\u003e\n\n### Authentication using SPN \u0026 Certificate\n```powershell\nfunction New-JwtToken {\n    param (\n        [Parameter(Mandatory = $true)]\n        [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,\n        \n        [Parameter(Mandatory = $true)]\n        [string]$ClientId,\n        \n        [Parameter(Mandatory = $true)]\n        [string]$TenantId\n    )\n\n    $header = @{\n        alg = \"RS256\"\n        typ = \"JWT\"\n        x5t = [System.Convert]::ToBase64String($Certificate.GetCertHash())\n    }\n\n    $claims = @{\n        aud = \"https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token\"\n        iss = $ClientId\n        sub = $ClientId\n        jti = [System.Guid]::NewGuid().ToString()\n        exp = [System.DateTimeOffset]::UtcNow.ToUnixTimeSeconds() + 3600\n        nbf = [System.DateTimeOffset]::UtcNow.ToUnixTimeSeconds()\n    }\n\n    $encodedHeader = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes((ConvertTo-Json $header -Compress)))\n    $encodedClaims = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes((ConvertTo-Json $claims -Compress)))\n    $unsignedToken = \"$encodedHeader.$encodedClaims\"\n    \n    $rsaProvider = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Certificate)\n    $signatureBytes = $rsaProvider.SignData([System.Text.Encoding]::UTF8.GetBytes($unsignedToken), [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1)\n    $signature = [System.Convert]::ToBase64String($signatureBytes)\n    \n    return \"$unsignedToken.$signature\"\n}\n# Enter Your TenantID, ClientID \u0026 Thumbprint\n$tenantId = \"\"\n$clientId = \"\"\n$certificateThumbprint = \"\"\n\n# Define API endpoint and parameters\n$tokenEndpoint = \"https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token\"\n$tokenParams = @{\n    grant_type = \"client_credentials\"\n    client_id  = $clientId\n    scope      = \"https://graph.microsoft.com/.default\"\n}\n\n# Get the certificate\n$cert = Get-Item -Path \"Cert:\\LocalMachine\\My\\$certificateThumbprint\"\n\n# Get access token\n$tokenParams[\"client_assertion\"] = New-JwtToken -Certificate $cert -ClientId $clientId -TenantId $tenantId\n$tokenParams[\"client_assertion_type\"] = \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\"\n\n$accessToken = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -Body $tokenParams\n\n# Output access token\nWrite-Output $accessToken.access_token\n\nInvoke-RestMethod \"https://graph.microsoft.com/v1.0/users\" -Headers @{Authorization = \"Bearer $($accessToken.access_token)\" }\n```\n\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F21bshwjt%2Fmicrosoftgraph","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F21bshwjt%2Fmicrosoftgraph","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F21bshwjt%2Fmicrosoftgraph/lists"}