entra id
67 TopicsUpdate Entra ID Device Extension Attributes via PowerShell & Create Dynamic Security Groups.
2) Overview of Extension Attributes and Updating via PowerShell What Are Extension Attributes? Extension attributes (1–15) are predefined string fields available on Entra ID device objects. They are exposed to Microsoft Graph as the extensionAttributes property. These attributes can store custom values like department, environment tags (e.g., Prod, Dev), or ownership details. Why Use Them? Dynamic Group Membership: Use extension attributes in membership rules for security or Microsoft 365 groups. Policy Targeting: Apply Defender for Endpoint (MDE) policies, Conditional Access or Intune policies to devices based on custom tags. For details on configuration of the policies refer below documentation links. https://learn.microsoft.com/en-us/defender-endpoint/manage-security-policies https://learn.microsoft.com/en-us/intune/intune-service/ https://learn.microsoft.com/en-us/entra/identity/conditional-access/ Updating Extension Attributes via PowerShell and Graph API Use Microsoft Graph PowerShell to authenticate and update device properties. Required permission: “Device.ReadWrite.All”. 3) Using PowerShell to Update Extension Attributes create app registration in Entra ID with permissions Device.ReadWriteall and Grant admin Consent. Register an app How to register an app in Microsoft Entra ID - Microsoft identity platform | Microsoft Learn Graph API permissions Reference. For updating Entra ID device properties you need “Device.ReadWrite.all” permission and Intune administrator role to run the script. Microsoft Graph permissions reference - Microsoft Graph | Microsoft Learn Below is the script Important things to note and update the script with your custom values. a) update the path of the excel file in the script. column header is 'DeviceName' Note: You may want to use CSV instead of excel file if Excel is not available on the admin workstation running this process. b) update the credential details - tenantId,clientId & clientSecret in the script. Client id and client secret are created as a part of app registration. c) update the Externsionattribute and value in the script. This is the value of the extension attribute you want to use in dynamic membership rule creation. ___________________________________________________________________________ #Acquire token $tenantId = "xxxxxxxxxxxxxxxxxxxxx" $clientId = "xxxxxxxxxxxxxxxx" $clientSecret = "xxxxxxxxxxxxxxxxxxxx" $excelFilePath = "C:\Temp\devices.xlsx" # Update with actual path $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/ $tenantId/oauth2/v2.0/token" -Method POST -Body $tokenBody $accessToken = $tokenResponse.access_token # Import Excel module and read device names Import-Module ImportExcel $deviceList = Import-Excel -Path $excelFilePath foreach ($device in $deviceList) { $deviceName = $device.DeviceName # Assumes column header is 'DeviceName' Get device ID by name $headers = @{ "Authorization" = "Bearer $accessToken"} $deviceLookupUri = "https://graph.microsoft.com/beta/devices?`$filter=displayName eq '$deviceName'" try { $deviceResponse = Invoke-RestMethod -Uri $deviceLookupUri -Headers $headers -Method GET } catch { Write-Host "Error querying device: $deviceName - $_" continue } if ($null -eq $deviceResponse.value -or $deviceResponse.value.Count -eq 0) { Write-Host "Device not found: $deviceName" continue } $deviceId = $deviceResponse.value[0].id # Prepare PATCH request $uri = "https://graph.microsoft.com/beta/devices/$deviceId" $headers["Content-Type"] = "application/json" $body = @{ extensionAttributes = @{ extensionAttribute6 = "MDE" } } | ConvertTo-Json -Depth 3 try { $response = Invoke-RestMethod -Uri $uri -Method Patch -Headers $headers -Body $body Write-Host "Updated device: $deviceName"} catch { Write-Host "Failed to update device: $deviceName - $_" } } Write-Host "Script execution completed." ________________________________________________________________________________________________________________________ Here’s a simple summary of what the script does: Gets an access token from Microsoft Entra ID using the app’s tenant ID, client ID, and client secret (OAuth 2.0 client credentials flow). Reads an Excel file (update the path in $excelFilePath, and ensure the column header is DeviceName) to get a list of device names. Loops through each device name from the Excel file: Calls Microsoft Graph API to find the device ID by its display name. If the device is found, sends a PATCH request to Microsoft Graph to update extensionAttribute6 with the value "MDE". Logs the result for each device (success or failure) and prints messages to the console. 4) Using Extension Attributes in Dynamic Device Groups Once extension attributes are set, you can create a dynamic security group in Entra ID: Go to Microsoft Entra admin center → Groups → New group. Select Security as the group type and choose Dynamic Device membership. Add a membership rule, for example: (device.extensionAttributes.extensionAttribute6 -eq "MDE") 4. Save the group. Devices with extensionAttribute6 = MDE will automatically join. 5) Summary Extension attributes in Entra ID allow custom tagging of devices for automation and policy targeting. You can update these attributes using Microsoft Graph PowerShell. These attributes can be used in dynamic device group rules, enabling granular MDE policies, Conditional Access and Intune deployments. Disclaimer This script is provided "as-is" without any warranties or guarantees. It is intended for educational and informational purposes only. Microsoft and the author assume no responsibility for any issues that may arise from the use or misuse of this script. Before deploying in a production environment, thoroughly test the script in a controlled setting and review it for compliance with your organization's security and operational policies.Using Entra ID Authentication with Arc-Enabled SQL Server in a .NET Windows Forms Application
Introduction: This guide demonstrates how to securely connect a .NET Framework Windows Forms application to an Arc-enabled SQL Server 2022 instance using Entra ID (Azure AD) authentication. It covers user authentication, token management, and secure connection practices, with code samples and screenshots. In many modern applications, it is common practice to use an application web service to mediate access to SQL Server. This approach can offer several advantages, such as improved security, scalability, and centralized management of database connections. However, there are scenarios where directly connecting to SQL Server is more appropriate. This guide focuses on such scenarios, providing a solution for applications that need direct access to SQL Server. This model is particularly useful for applications like SQL Server Management Studio (SSMS), which require direct database connections to perform their functions. By using Entra ID authentication, we can ensure that these direct connections are secure and that user credentials are managed efficiently. By following the steps outlined in this guide, developers can ensure secure and efficient connections between their .NET Windows Forms applications and Arc-enabled SQL Server instances using Entra ID authentication. This approach not only enhances security but also simplifies the management of user credentials and access tokens, providing a robust solution for modern application development. SAMPLE CODE: GitHub Repository Prerequisites Arc-enabled SQL Server 2022/2025 configured for Entra ID authentication Entra ID (Azure AD) tenant and app registration .NET Framework 4.6.2 Windows Forms application (Not required .NET version, only what the solution is based on) Microsoft.Identity.Client, Microsoft.Data.SqlClient NuGet packages Application Overview User authenticates with Entra ID Token is acquired and used to connect to SQL Server Option to persist token cache or keep it in memory Data is retrieved and displayed in a DataGridView Similar setup to use SSMS with Entra ID in articles below. Windows Form Sample Check User Button shows the current user The Connect to Entra ID at Login button will verify if you are logged in and try to connect to SQL Server. If the user is not logged in, an Entra ID authentication window will be displayed or ask you to log in. Once logged in it shows a Connection successful message box stating the connection to the database was completed. The Load Data button queries the Adventure Works database Person table and loads the names into the datagridview. The Cache Token to Disk checkbox option either caches to memory when unchecked and would require reauthentication after the application closes, or the option to cache to disk the token to be read on future application usage. If the file is cached to disk, the location of the cached file is (C:\Users\[useraccount]\AppData\Local). This sample does not encrypt the file which is something that would be recommended for production use. This code uses MSAL (Microsoft Authentication Library) to authenticate users in a .NET application using their Microsoft Entra ID (Azure AD) credentials. It configures the app with its client ID, tenant ID, redirect URI, and logging settings to enable secure token-based authentication. //Application registration ClientID, and TenantID are required for MSAL authentication private static IPublicClientApplication app = PublicClientApplicationBuilder.Create("YourApplicationClientID") .WithAuthority(AzureCloudInstance.AzurePublic, "YourTenantID") .WithRedirectUri("http://localhost") .WithLogging((level, message, containsPii) => Debug.WriteLine($"MSAL: {message}"), LogLevel.Verbose, true, true) .Build(); This method handles user login by either enabling persistent token caching or setting up temporary in-memory caching, depending on the input. It then attempts to silently acquire an access token for Azure SQL Database using cached credentials, falling back to interactive login if no account is found. private async Task<AuthenticationResult> LoginAsync(bool persistCache) { if (persistCache) TokenCacheHelper.EnablePersistence(app.UserTokenCache); else { app.UserTokenCache.SetBeforeAccess(args => { }); app.UserTokenCache.SetAfterAccess(args => { }); } string[] scopes = new[] { "https://database.windows.net//.default" }; var accounts = await app.GetAccountsAsync(); if (accounts == null || !accounts.Any()) return await app.AcquireTokenInteractive(scopes).ExecuteAsync(); var account = accounts.FirstOrDefault(); return await app.AcquireTokenSilent(scopes, account).ExecuteAsync(); } Connecting to SQL Server with Access Token This code connects to an Azure SQL Database using a connection string and an access token obtained through MSAL authentication. It securely opens the database connection by assigning the token to the SqlConnection object, enabling authenticated access without storing credentials in the connection string. This sample uses a self-signed certificate, in production always configure SQL Server protocols with a certificate issued by a trusted Certificate Authority (CA). TrustServerCertificate=True bypasses certificate validation and can allow MITM attacks. For production, use a trusted Certificate Authority and change TrustServerCertificate=True to TrustServerCertificate=False. Configure Client Computer and Application for Encryption - SQL Server | Microsoft Learn string connectionString = $"Server={txtSqlServer.Text};Database=AdventureWorks2019;Encrypt=True;TrustServerCertificate=True;"; var result = await LoginAsync(checkBox1.Checked); using (var conn = new SqlConnection(connectionString)) { conn.AccessToken = result.AccessToken; conn.Open(); // ... use connection ... } Fetching Data into DataGridView This method authenticates the user and connects to an Azure SQL Database using an access token, and runs a SQL query to retrieve the top 1,000 names from the Person table. It loads the results into a DataTable, which can then be used for display or further processing in the application. private async Task<DataTable> FetchDataAsync() { var dataTable = new DataTable(); var result = await LoginAsync(checkBox1.Checked); using (var conn = new SqlConnection(connectionString)) { conn.AccessToken = result.AccessToken; await conn.OpenAsync(); using (var cmd = new SqlCommand("SELECT TOP (1000) [FirstName], [MiddleName], [LastName] FROM [AdventureWorks2019].[Person].[Person]", conn)) using (var reader = await cmd.ExecuteReaderAsync()) { dataTable.Load(reader); } } return dataTable; } Configure Azure Arc SQL Server to use Entra ID authentication Using SQL Server 2022 follow the instructions here to setup the key vault and certificate when configuring. This article can also be used to configure SSMS to use Entra ID authentication. Detailed steps located here: Set up Microsoft Entra authentication for SQL Server - SQL Server | Microsoft Learn Using SQL Server 2025 the setup is much easier as you do not need to configure a Key Vault, or certificates as it is relying on using the managed identity for the authentication. Entra ID App Registration Steps Register a new app in Azure AD Add a redirect URI (http://localhost) Add API permissions for https://database.windows.net/.default On the Entra ID app registration, click on API Permissions. Add the API’s for Microsoft Graph: User.Read.All Application.Read.All Group.Read.All Add a permission for Azure SQL Database. If Azure SQL database is not shown in the list ensure that the Resource Provider is registered for Microsoft.Sql. Choose Delegated permissions and select user_impersonation, Click Add permission for the Azure SQL Database. NOTE: Once the permissions are added ensure that you grant admin consent on the items. Security Considerations Never store client secrets in client apps Use in-memory token cache for higher security, or encrypted disk cache for convenience Use user tokens for auditing and least privilege References Microsoft Docs: Azure AD Authentication for SQL Server MSAL.NET Documentation Arc-enabled SQL Server Documentation Conclusion: By following the steps outlined in this guide, developers can ensure secure and efficient connections between their .NET Windows Forms applications and Arc-enabled SQL Server instances using Entra ID authentication. This approach not only enhances security but also simplifies the management of user credentials and access tokens, providing a robust solution for modern application development. *** Disclaimer *** The sample scripts are not supported under any Microsoft standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.Creating Claims Mapping Policy in Entra ID
I am attempting to create a Claims Mapping Policy using PowerShell, Entra ID and Microsoft Graph via a script or a PowerShell Window, In neither case, I was able to do it. The script is: # Define the Application (Client) ID and Secret $applicationClientId = 'XXXXXXXXXXX' # Application (Client) ID $applicationClientSecret = 'XXXXXXXXXXX' # Application Secret Value $tenantId = 'XXXXXXXXXXXX' # Tenant ID Connect-Entra -TenantId $tenantId -ClientSecretCredential $clientSecretCredential $params = @{ definition = @( '{"ClaimsMappingPolicy":{"Version":1,"IncludeBasicClaimSet":"false","ClaimsSchema":[{"Source":"user","onpremisesssamaccountname":"name","SamlClaimType": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"}]}}' ) displayName = "ClaimTest" } New-MgPolicyClaimMappingPolicy -BodyParameter $params Get-MgPolicyClaimMappingPolicy Disconnect-Entra I keep getting the error: New-MgPolicyClaimMappingPolicy : One or more errors occurred. At C:\Users\eigog\Documents\Poweshell Scripts\test.ps1:24 char:1 + New-MgPolicyClaimMappingPolicy -BodyParameter $params + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [New-MgPolicyClaimMappingPolicy_Create], AggregateException + FullyQualifiedErrorId : System.AggregateException,Microsoft.Graph.PowerShell.Cmdlets.NewMgPolicyClaimMappingPolicy_Create I don't understand, because this was similar to the example they gave here: https://learn.microsoft.com/en-us/entra/identity-platform/claims-customization-powershell And yes, I tried to do it manually in a PowerShell window with my credentials and I tried the beta version as well. The application does have the scope of Policy.ReadWrite.ApplicationConfiguration. I can't seem to see the error. Can anyone see something I'm missing or point me in a direction? Thanks20Views0likes1CommentHow to update the proxyAddresses of a Cloud-only Entra ID user
I currently have a client with an Entra ID user (not migrated from on-premises) that is cloud-based, but has proxyAddresses values assigned. Now, I want to update the proxyAddresses through the Graph Explorer and have used this link as a guide: https://learn.microsoft.com/en-us/answers/questions/2280046/entra-connect-sync-blocking-user-creation-due-to-h. Now this guide is suggesting you can use the BETA model and this URL format... https://graph.microsoft.com/beta/users/%USERGUID% It states you can use that URL to do both 'GET' and 'PATCH' queries - the PATCH query being the one that will change the settings. You have to put forth a body for the proxyAddresses property in the PATCH query, which represents all of the addresses you want the user to utilise as proxy addresses. Now the GET query works... The PATCH query does not... Screenshot provided: Now, regarding the error message, I have applied ALL possible permissions in the 'Modify Permissions' tab. It is still erroring, Now I cannot use Exchange Online PowerShell, as the user does not have a mailbox! Aside from potentially using a license for Exchange Online or provisioning a mailbox for the user, and making the necessary changes, would the only other option be to delete/recreate the user?Solved128Views0likes3Comments