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

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.

Related

How to create a service principal without app, and create an app without service principal in Azure AD

Recently I watched a course on Pluralsight.com, Getting Started with Azure Active Directory for Developers. In the section, Service Principals->Apps and Service Principals, the author said that we can create a service principal without app, and it's also possible to create an app without service principal. But he didn't show how to do so, and I cannot find out online how to do so either. So how can we do so? And can we do so from the Azure Portal?
Yes it is possible to create an azure ad app without creating a service principle(using powershell only) . Through portal if you will create it will create service princple along with app.
You can view the newly created app in the App registrations blade, under All applications in the Azure portal
Powershell cmdlet.
New-AzureADApplication -DisplayName "MTS Demo App"
It is not possible to create a service principle without creating an application. Service Principle will create an azure active directory as an application
# Create a service principal for a resource group using a preferred name and role
az ad sp create-for-rbac --name myServicePrincipalName \
--role reader \
--scopes /subscriptions/mySubscriptionID/resourceGroups/myResourceGroupName
Note : For creating Service Principle you need to admin role at the subscription level and Adminsitator role at Azure Active Directory Level.
Reference : https://learn.microsoft.com/en-us/cli/azure/create-an-azure-service-principal-azure-cli#code-try-0***

How to synchronize Azure Active Directory User that is given a CRM License to Dynamics 365 Online

My understanding regarding the synchronization are as follows:
Create Member User in Active Directory
Assign CRM License in Active Directory
User will be created in Dynamics CRM
However, I'm not sure when will point no 3 is triggered.
Should the new member user login for the first time inside the CRM to change password for it to be created in CRM? (This is the behavior that I observed)
Or will it auto synchronized after some time?
Thank you Henk van Boeijen for your comment adding more to your comment to make it as answer and understandable to other users.
The below answer is publish by soundharya subhash under Power Platform Learning
When an new Environment is created, it takes more than an hour or some times a day to sync users from Azure AD to CRM.
Through Power Shell cmdlets, we can sync user immediately.
Install Module
Microsoft.PowerApps.Administration.PowerShell
Install-Module -Name Microsoft.PowerApps.Administration.PowerShell
Connect to Power Apps using any of these
User Name and Password
Add-PowerAppsAccount -Endpoint “prod” -Username “” -Password “”
Tenant Id, Client Id and Client Secret
Add-PowerAppsAccount -Endpoint “prod” -TenantID “” -ClientSecret “” `
-ApplicationId “”
Tenant Id, Client ID and Certificate Thumbprint
Add-PowerAppsAccount -Endpoint “prod” -TenantID “” -CertificateThumbprint “” `
-ApplicationId "
"
Get-AdminPowerAppEnvironment cmdlet gives list of environments available in Tenant, note down the environment name (guid) to which you want to sync the Users
Go to Azure Portal : https://portal.azure.com -> Azure AD -> Users -> note down the Object Id of the user you want to sync
Run the cmdlet in Power Shell
Add-AdminPowerAppsSyncUser -EnvironmentName <Guid> -PrincipalObjectId…
Reference : https://nishantrana.me/2021/01/20/force-sync-users-from-azure-ad-to-dynamics-crm/

Override Office 365 group naming policy

As stated in this article from microsoft on group naming policies, selected administrators are exempted and able to override any given naming policy.
In my case I have registered an app that is used to run azure functions creating unified groups through the graph api.
I want to override the naming policy when using the app but I can't find a way to make it happen.
Any ideas?
The application you registered will have a service principal in Azure AD. Your application performs the actions under the service principal's identity.
You can assign the exempted roles to the service principal object of your application and then your application should be exempted as well.
You can find the role ID using this command :
Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Helpdesk Administrator'}
You can find the object ID of the service principal either by searching directly under enterprise applications or through PS using this command:
Get-AzureADServicePrincipal -searchstring (your enterprise application name)
Finally, you can assign the role to your application using this command:
Add-AzureADDirectoryRoleMember -ObjectId $AADRole.ObjectId -RefObjectId $service princiapl.ObjectId
Hope this helps.

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.

Access denied error while adding certificate credential to Azure AD Application

I am adding a certificate credential to a registered application on an Azure AD tenant by executing following commands:
connect-msolservice
$cer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate
$cer.Import("<Cert path>")
$binCert = $cer.GetRawCertData()
$credValue = [System.Convert]::ToBase64String($binCert);
New-MsolServicePrincipalCredential -AppPrincipalId "<AppID>" -Type asymmetric -Value $credValue -Usage verify
These commands are taken from this sample . I am signing with the account of a user on the directory. However, the last command is throwing an exception of 'Access Denied. You do not have permissions to call this
cmdlet'. According to the documentation, it is not mentioned if this command execution requires to be from an administrator account. If i change the user role to be service/global administrator on the Azure AD, the command succeeds. Interestingly, I am able to execute the command on a different Azure AD, where the account is just an user. Is there anything else in play here? Can a user account be given permission to execute this cmdlet?
Probably you have reached your subscription limit or your subscription has expired.
you need to follow up with ms team. This is not a code issue.

Resources