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

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.

Related

Check if user exist in AD using Azure CLI

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

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

Insufficient privileges while changing password

I am trying to use Azure Powershell (AZ powershell module) inside docker container to create/modify office 365 related configurations including user profiles.
I am trying to change user password using service principal. I have got the following error while using Update-AzADUser. However, I could create the user and modify the display name. I was having issues only with the change password or removing the user.
PS /> Update-AzADUser -ObjectId xyz358c2... -Password $password
Update-AzADUser : Insufficient privileges to complete the operation.
At line:1 char:1
+ Update-AzADUser -ObjectId xyz358c2... -Passw ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Update-AzADUser], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ActiveDirectory.UpdateAzureADUserCommand
On the service principal, I have provided all available application permission and delegated permissions on Microsoft Graph API and Windows Azure Active Directory.
I can't find any of the AD roles that are available in https://learn.microsoft.com/en-us/azure/active-directory/users-groups-roles/directory-assign-admin-roles to assign to the service principal. Please screenshots on the below links.
Permissions
Roles
As discussed in comments, you should try to assign an appropriate directory role to the service principal you are using, so that it can get sufficient privileges.
Here is a quick script to do that. Change the service principal name and roleName as per your requirements.
# Get to the service principal
$svcPrincipalId = (Get-AzureADServicePrincipal -SearchString "your service principal name").ObjectId
# I am using Helpdesk administrator here, but feel free to change this name as per your requirement.
# You can get a complete list of role templates using Get-AzureADDirectoryRoleTemplate.
# Helpdesk admninstrator role can reset passwords for non-administrators.
$roleName = 'Helpdesk administrator'
# Fetch User Account Administrator role instance
$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq $roleName}
# If role instance does not exist, instantiate it based on the role template
if ($role -eq $null) {
# Instantiate an instance of the role template
$roleTemplate = Get-AzureADDirectoryRoleTemplate | Where-Object {$_.displayName -eq $roleName}
Enable-AzureADDirectoryRole -RoleTemplateId $roleTemplate.ObjectId
# Fetch User Account Administrator role instance again
$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq $roleName}
}
# Add user to role
Add-AzureADDirectoryRoleMember -ObjectId $role.ObjectId -RefObjectId $svcPrincipalId

Can we import users to Azure AD from sql server user table

We have .net applications and each have its own user tables (some of them AspNetUsers table). Now we think about using Azure Active Directory as a central place to do authentication&authorization. Is there a way to import users to Azure AD from our existing sql server user tables? I don't seem to find such a way, all I see is something like important from local AD.
Using the AAD Graph API or AAD PowerShell you can programmatically create new Users in your Tenant.
For the AAD Graph API:
POST https://graph.windows.net/myorganization/users
Body:
{
"accountEnabled": true,
"displayName": "Alex Wu",
"mailNickname": "AlexW",
"passwordProfile": {
"password": "Test1234",
"forceChangePasswordNextLogin": true
},
"userPrincipalName": "Alex#a830edad9050849NDA1.onmicrosoft.com"
}
You can find samples to access the AAD Graph API across a number of languages on GitHub.
For AAD PowerShell:
$PasswordProfile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = "Password"
$PasswordProfile.ForceChangePasswordNextLogin = $true
New-AzureADUser -DisplayName "New User" -PasswordProfile $PasswordProfile -UserPrincipalName "NewUser#contoso.com" -AccountEnabled $true -MailNickName "Newuser"
Let me know if this helps.
If you haven't done this already, The query results in SQL can be saved to a CSV. Then use PowerShell to import into Azure. The caveat being you would need an AAD account that can do the import portion. Since PowerShell modules for Azure AD are finicky, it seems, you should update your PowerShell by doing the following.
PS C:\> Install-Module -Name AzureADPreview -RequiredVersion 2.0.2.5 -Verbose -Force
Go to this page to get the latest version info. (Downloading from this site did not work for me, however, running the above script did.
https://www.powershellgallery.com/packages/AzureADPreview/2.0.0.17
Once updated, use the following script to import the file.
$Credential = Get-Credential
Connect-AzureRmAccount -Credential $Credential -Tenant "xxxx-xxxx-xxxx-xxxx" -ServicePrincipal
Account: AzureUser#contosso.onmicrosoft.com
Environment: AzureCloud #usually the region your AAD is located, such as CentralUS.
Subscription: yyyy-yyyy-yyyy-yyyy
Tenant: xxxx-xxxx-xxxx-xxxx
$SecureStringPassword = ConvertTo-SecureString -String "ComplexPasswordString" -AsPlainText -Force
$Users = Import-Csv 'C:\Path to CSV file\SQL_USER_FILE.csv'
$Users | ForEach-Object {
New-AzureRmADUser -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName -Password $SecureStringPassword -MailNickname $_.MailNickName -Verbose
}
And if that doesn't work due to login, the more simplified version will work, but will require you to login with your AAD account.
Connect-AzureRMAccount
$SecureStringPassword = ConvertTo-SecureString -String "ComplexPasswordString" -AsPlainText -Force
$Users = Import-Csv 'C:\Path to CSV file\SQL_USER_FILE.csv'
$Users | ForEach-Object {
New-AzureRmADUser -DisplayName $_.DisplayName -UserPrincipalName $_.UserPrincipalName -Password $SecureStringPassword -MailNickname $_.MailNickName -Verbose
}
I User -Verbose to give me a running status of the import. Without it, the execution is silent. Oh, it took about 15 minutes to do 1500 users on a gigabit connection. Tp give you an idea how long it takes.
The particulars to automating login can be found here.
https://learn.microsoft.com/en-us/powershell/module/azurerm.profile/connect-azurermaccount?view=azurermps-6.12.0
Caveat
The CSV must have the required fields shown above. So you might need to do a little finagling to get them to match. Just know that the only real important field is going to be the -UserPrincipalName = user#contosso.onmicrosoft.com.

Resources