Check if user exist in AD using Azure CLI - azure-active-directory

I have installed the Azure CLI to connect to the tenant.
Now I want to import a CSV containing several emails to get cross checked if they exist in the AD.
There a tons of ways to do it with 'Get-ADUser' (which I'm not using since I'd need to set up the server locally) but I could not find any with Azure CLI.
Anyone managed to do this?

This is the list of commands to manage users with AZ CLI
https://learn.microsoft.com/en-us/cli/azure/ad/user?view=azure-cli-latest
Also, there is a PowerShell module that allows you to manage the user in your Azure AD.
https://learn.microsoft.com/en-us/powershell/module/azuread/?view=azureadps-2.0#users

You can get all the ad users by using below command:
Get-AzureADUser -All $true
If you want to know if the user exists or not follow below commands:
XX- example display name
Step-1
$s= Get-AzureADUser -All $true
Step-2
if($s.DisplayName -eq "XX")
{
Write-Host "Present"
} else
{
Write-Host "Not Present"
}
References taken from:
https://learn.microsoft.com/en-us/powershell/module/az.resources/get-azaduser?view=azps-8.3.0#syntax

Related

Sync complains about not unique Attiribute

AAD complains about errors in the sync process.
But I don't understand what the duplicate is there.
Already tried a full import, delta import, full sync etc.
How do I find the duplicate?
There are three attributes mainly checked during azure ad connect: userPrincipalName, proxyAddresses, and sourceAnchor/immutableID in Azure AD Connect.
You can make use of IDFix tool to identify the duplicate objects.
Please Check below scenarios if they are the cause:
If you/ User is Global Admin
Try to remove the role and sync the user without admin role or by adding user role.After the sync then you can add the role again.
Or
If it is already in sync ,Disable the directory sync process ,then delete the user
from domain (on-prem directory) and then do the azure ad sync and then add the
user role to admin back if required.
During Azure ad connect , we must take care of SMTP Soft match and ImmutableID hardmatch. soft-vs-hard-match
$credential = Get-Credential
Connect-MsolService -Credential $credential
$ADUser = "username"
$AzureADUser = "username#emaildomainname.com"
$guid =(Get-ADUser $ADUser).Objectguid
$immutableID=[system.convert]::ToBase64String($guid.tobytearray())
Set-MsolUser -UserPrincipalName "$AzureADUser " -ImmutableId $immutableID
This can take care of mismatch .See error-type-attributevaluemustbeunique & this
Note : Please do resync after any changes.
Other references:
Azure AD Sync, duplicate user - Server Fault
Troubleshoot directory synchronization errors | Microsoft Docs
diagnose sync errors (github.com)
AAD connect design concepts

Get-ShardMapManager without Username and Password

Is it possible to call Get-ShardMapManager when creating a new shard map manager without involving username and password (through hardcoding or storing the values in key vault)
Here is the code that I currently have in powershell
$ShardMapManager = Get-ShardMapManager -Username $DbUsrId -Password $DbPwd
can i use token or something like that? just whatever that is not involving username and password? thanks
No, you can't. From the source code of Get-ShardMapManager, UserName and Password are all Mandatory=$true.
In this case, if you want to avoid using them just because of the security issue, you can use azure keyvault to store them via Set-AzKeyVaultSecret as you mentioned. Retrieve them in the commands, then pass them to Get-ShardMapManager, just user/service principal that added to the access policy of the keyvault is able to get them(or has the Key Vault Administrator if you select Azure role-based access control in Access policies blade of the keyvault).
Make sure you have installed Az powershell module, then use the command below.
Connect-AzAccount
$DbUsrId = Get-AzKeyVaultSecret -VaultName "keyvaultname" -Name "username" -AsPlainText
$DbPwd = Get-AzKeyVaultSecret -VaultName "keyvaultname" -Name "password" -AsPlainText
$ShardMapManager = Get-ShardMapManager -Username $DbUsrId -Password $DbPwd

How to Connect to azuread module non-interactively when MFA is enabled?

I need to connect to AD in azure function app using powershell script. (as it is in function i need to do it without prompt) I am trying this:
Import-Module D:\home\site\wwwroot\HttpTrigger1\AzureAD\AzureAD.psd1 -UseWindowsPowershell
$creds = Connect-AzureAD -TenantId $tenantId -Credential $Credential
In my function app I have enabled Authentication through Log in with Azure Active Directory.
Is there a way to use that authentication in powershell script to connect to azuread module. I mean the user clicks on the function-app url, logs-in with their credentials and that authentication can be used in the script for connect-azuread. The current script is not working as MFA is enabled, which cannot be removed as per our use-case.
Use-case: I have an application in the form of an ARM template that would be deployed as a managed application.
The ARM template is supposed to deploy a set of resources on the tenant of the user, whoever purchases the app. But I need "client id"
and "client secret" of the application registration on user/customer's tenant with O365 mgt api permissions, as input to
my mainTemplate.json.
This App registration is a one-time thing and is not possible through ARM template, that is why I am trying to achieve the above via
powershell. I am creating a powershell function-app, enabled Authentication through Log in with Azure Active Directory.
Idea behind this approach is that at the time of purchasing the app, while filling-in other details(like Resource group name and region) at the UI(created by createUIDefinition.json), the user clicks on the function app link,
logs-in and the script runs in the background. The script should be able to create the app registration at the user's tenant and provide
back the client id and client secret of that app reg.
Unfortunately No !
If MFA is enabled, you will not be able to login non-interactively. This is kind of intentional considering to make it more secure. You cannot as well pass along the authentication.
The workaround for this you could possibly make use of the Azure Service Principal.Get the function authenticated and make the Azure Service Principal to do the job.
What Are Azure Service Principal ?
Service principals are non-interactive Azure accounts. Like other user accounts, their permissions are managed within Azure Active Directory.
Sharing some reference articles to get a deeper insight on the Azure Service Principal:
Creating the Service Principal (The creation is one time process)
https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal#app-registration-app-objects-and-service-principals
Creating the Service Principal through Powershell
https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-authenticate-service-principal-powershell#create-service-principal-with-self-signed-certificate
Authenticating the Service Principal
https://learn.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azps-5.1.0
Coming back to your scenario, to execute Connect-AzureAD with out the interactive login using the service principal you could use the below snippet
# Login to Azure AD PowerShell With Admin Account
Connect-AzureAD
# Create the self signed cert
$currentDate = Get-Date
$endDate = $currentDate.AddYears(1)
$notAfter = $endDate.AddYears(1)
$pwd = ""
$thumb = (New-SelfSignedCertificate -CertStoreLocation cert:\localmachine\my -DnsName com.foo.bar -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $notAfter).Thumbprint
$pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
Export-PfxCertificate -cert "cert:\localmachine\my\$thumb" -FilePath c:\temp\examplecert.pfx -Password $pwd
# Load the certificate
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate("C:\temp\examplecert.pfx", $pwd)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
# Create the Azure Active Directory Application
$application = New-AzureADApplication -DisplayName "test123" -IdentifierUris "https://test123"
New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "Test123" -StartDate $currentDate -EndDate $endDate -Type AsymmetricX509Cert -Usage Verify -Value $keyValue
# Create the Service Principal and connect it to the Application
$sp=New-AzureADServicePrincipal -AppId $application.AppId
# Give the Service Principal Reader access to the current tenant (Get-AzureADDirectoryRole)
Add-AzureADDirectoryRoleMember -ObjectId 5997d714-c3b5-4d5b-9973-ec2f38fd49d5 -RefObjectId $sp.ObjectId
# Get Tenant Detail
$tenant=Get-AzureADTenantDetail
# Now you can login to Azure PowerShell with your Service Principal and Certificate
Connect-AzureAD -TenantId $tenant.ObjectId -ApplicationId $sp.AppId -CertificateThumbprint $thumb
Short Explanation of the code :
The above script creates Service Principal, grants a Read Access at the tenant level and connects to the Azure AD at the end using the created Service Principal.

Assigning Custom Azure AD Role to a Security Group

I've created a custom Azure AD role for the purpose of reading service principals within the directory. This is so users can troubleshoot without needing to find additional support. However, I'm not able to assign this custom role to an entire security group. How can I assign this role to all users within a group?
You could use the powershell to assign this role to all users in this group, try the script below.
First, you need to install the AzureADPreview powershell module.
Install-Module -Name AzureADPreview
Connect-AzureAD
$members = Get-AzureADGroupMember -ObjectId "<ObjectId of the Security Group>"
$roleDefinition = Get-AzureADMSRoleDefinition -Filter "displayName eq '<Custom role name>'"
# Get app registration and construct resource scope for assignment.
$appRegistration = Get-AzureADApplication -Filter "displayName eq 'joyttt'"
$resourceScope = '/' + $appRegistration.objectId
foreach($member in $members){
New-AzureADMSRoleAssignment -DirectoryScopeId $resourceScope -RoleDefinitionId $roleDefinition.Id -PrincipalId $member.ObjectId
}
Reference - https://learn.microsoft.com/en-us/azure/active-directory/users-groups-roles/roles-create-custom#assign-the-custom-role-using-azure-ad-powershell

How to complete a recommendation - 'An Azure Active Directory administrator should be provisioned for SQL servers' sent by Azure?

We have a SQL database located in Azure. We got a recommendation from Microsoft Azure saying to provision Active Directory administrator for SQL servers. When I log into Azure portal, I'm able to see a default active directory.
I'm not familiar with Active Directory. I referred this link https://learn.microsoft.com/en-us/azure/sql-database/sql-database-aad-authentication-configure but I'm not getting the exact steps to follow the recommendation.
EDIT1 This is the Active Directory admin page we could see.
EDIT2 Users list page in the Default Directory
Any help is appreciated
It refers to the AAD integration of Azure SQL DB: https://learn.microsoft.com/en-us/azure/sql-database/sql-database-aad-authentication
Doing this, you can for many scenarios get rid of extra logins and password for SQL and instead use SSO with Azure AD and things like MFA.
This ms doc includes a script that can be run in powershell to provision the user for AAD.
1) In the Azure portal, in the upper-right corner, select your connection to drop down a list of possible Active Directories.
2) Choose the correct Active Directory as the default Azure AD.
This step links the subscription associated with Active Directory
with Managed Instance making sure that the same subscription is used
for both Azure AD and the Managed Instance.
3)Navigate to Managed Instance and select one that you want to use for Azure AD integration.
4) Select the banner on top of the Active Directory admin page and grant permission to the current user. If you're logged in as Global/Company administrator in Azure AD, you can do it from the Azure portal or using PowerShell with the script below. Grant permissions-portal
Here is the Powershell script:
# Gives Azure Active Directory read permission to a Service Principal representing the managed instance.
# Can be executed only by a "Company Administrator", "Global Administrator", or "Privileged Role Administrator" type of user.
$aadTenant = "<YourTenantId>" # Enter your tenant ID $managedInstanceName = "MyManagedInstance"
# Get Azure AD role "Directory Users" and create if it doesn't exist $roleName = "Directory Readers" $role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq $roleName} if ($role -eq $null) {
# Instantiate an instance of the role template
$roleTemplate = Get-AzureADDirectoryRoleTemplate | Where-Object {$_.displayName -eq $roleName}
Enable-AzureADDirectoryRole -RoleTemplateId $roleTemplate.ObjectId
$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq $roleName} }
# Get service principal for managed instance $roleMember = Get-AzureADServicePrincipal -SearchString $managedInstanceName $roleMember.Count if ($roleMember -eq $null) {
Write-Output "Error: No Service Principals with name '$ ($managedInstanceName)', make sure that managedInstanceName parameter was entered correctly."
exit } if (-not ($roleMember.Count -eq 1)) {
Write-Output "Error: More than one service principal with name pattern '$ ($managedInstanceName)'"
Write-Output "Dumping selected service principals...."
$roleMember
exit }
# Check if service principal is already member of readers role $allDirReaders = Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId $selDirReader = $allDirReaders | where{$_.ObjectId
-match $roleMember.ObjectId}
if ($selDirReader -eq $null) {
# Add principal to readers role
Write-Output "Adding service principal '$($managedInstanceName)' to 'Directory Readers' role'..."
Add-AzureADDirectoryRoleMember -ObjectId $role.ObjectId -RefObjectId $roleMember.ObjectId
Write-Output "'$($managedInstanceName)' service principal added to 'Directory Readers' role'..."
#Write-Output "Dumping service principal '$($managedInstanceName)':"
#$allDirReaders = Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId
#$allDirReaders | where{$_.ObjectId -match $roleMember.ObjectId} }
else {
Write-Output "Service principal '$($managedInstanceName)' is already member of 'Directory Readers' role'."
}
5)After the operation is successfully completed, the following notification will show up in the top-right corner:
6) Now you can choose your Azure AD admin for your managed instance. For that, on the Active Directory admin page, select Set admin command.
I will try this tomorrow, but if you get to it, let me know how it goes. Good luck.

Resources