How to Connect-AzAccount in Powershell Core (without prompt)? - azure

I did see this q/a: Connect-AzAccount without prompt
But when I tried the accepted answer, I get the following error:
[6/12/2020 12:36:20 AM] ERROR: Connect-AzAccount : Username + Password authentication is not supported in PowerShell Core. Please use device code authentication for interactive log in, or Service Principal authentication for script log in.
So I went to example 3 of the Connect-AzAccount documentation which specifies the "Service Principal" authentication method, so I mix the two because the suggested vanilla Get-Credential triggers another interactive session. So here's the script now:
$User = "myemail#gmail.com"
$PWord = ConvertTo-SecureString -String "**********" -AsPlainText -Force
$tenant = "f*********************************"
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User,$PWord
# $Credential = Get-Credential
Connect-AzAccount -Credential $Credential -Tenant $tenant -ServicePrincipal
which brings my next error: [6/12/2020 12:45:45 AM] ERROR: Connect-AzAccount : AADSTS700016: Application with identifier 'myemail' was not found in the directory 'f*********************************'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.
I'm really confused at this point because all I have done at this point in Azure is:
Create a new Azure account
Provision an Azure API Management instance through the UI (which btw, takes like 20 minutes)
Try the above code to connect to Azure inside of a Powershell Azure Function locally.
I think something is wrong with the information I've provided or how I've configured something.
$User is the email I signed up to Azure with.
$PWord is my Azure password
$tenant is the first thing I saw when I opened Azure AD:
What's wrong with how I'm trying to connect to Azure through Powershell Core?

Based on Example 3, it asks for entering your application ID for the username and service principal secret as the password.
So you need to create a service principal at first. And then use its application ID and client secret as the credential.
$User = "{application id}"
$PWord = ConvertTo-SecureString -String "{client secret}" -AsPlainText -Force

I don't like Azure documentation. It gives off a very different vibe from GCP and feels much less beginner friendly.
With that said, they did have some kind of write-up that addresses my issue of creating a service principal and using it to authenticate.
I actually ended up just finding a video (and I never do this) because I wanted to skip past all the technical jargon and just create the darn service principal.
It's not even intuitive - it's like Microsoft could have added a button in AZ AD or IAM that said "Create Service Principal" but no, you have to go to a bunch of other pages that say nothing about service principals. You'll see:
In Azure Portal, navigate to the App Registrations page in Azure Active Directory. What an "app registration" has to do with a service principal, I couldn't tell you. I also couldn't tell you what a service principal is, but I'd imagine it has something to do with service accounts.
Make a New Registration and give it some sort of name to describe what the scope of this service principal will entail. Like normal service account naming conventions. I don't think the account type matters but I chose Multitenant. Redirect URL has nothing to do with service principals, and honestly makes it all the more confusing. I would never associate service accounts with any kind of redirect url, but here we are.
You're going to arrive at a page with Display Name (the name of the service principal you gave it in step 2), Application (client) ID (this is actually your service account username, which is imo non-intuitive), and Object ID (I have no idea what this is but I never needed to use it.
Guess what, you have only created 1/3 of your service account. It doesn't even have a password yet. Within your created app registration, there's a Certificates & Secrets page. On that page, you want to add a new client secret. For my description I just put my service principal "display name". I don't think that was necessary because this client secret is within the scope of the app registration, so even if I named it "poop" I could reasonably assume what it was for. Azure will generate a nuanced client secret and display it, but not warn you that this is the only time you will be able to see the key. Copy it. This is, in normal people talk, your service principal password.
For the last step, you need to get out of dodge, I mean Azure AD. Navigate to your Subscriptions page and click on your active subcription. For some reason IAM is here, so click on that. At this point, your service principal has a username and password, but no actual permissions - you have to configure that manually too. Click Add -> Add Role Assignment. For role, you should do your research but if it's not serious Contributor is probably a safe bet. It has read/write but it doesn't supersede Owner. Make sure you're assigning access to a service principal, and search for its display name. Save.
With all of that done, Connect-AzAccount finally worked.

Related

unable to authenticate to azure using powershell

we had an azure tenant.
we opened a new one, and passed our users to the new tenant and then added our users to the old tenants as guests.
Passing means that we deleted our users from the first tenant, then we migrated the domain to the new tenant and we created the users with the same properties in the new tenant.
since then every time we try to connect to azure using powershell with the commend Connect-azaccount -TenantId we get the following error:
Unable to acquire token for tenant '***' with error 'SharedTokenCacheCredential authentication unavailable. No account matching the specified username: *** tenantId: *** was found in the cache.'
does someone knows hoe to fix this?
thank you
we have tried every thing we found online.
we tries clear-azcontext, deleting the certificated from our machines, deleting powershell and reinstalling, etc...
Unable to acquire token for tenant xxx with error SharedTokenCacheCredential authentication unavailable. No account matching the specified username: xxx tenantId: xxx was found in the cache
The error usually occurs if the user is not present in the tenant you are trying to sign-in.
To check the error in detail, you can try debugging like below:
$DebugPreference = "Continue"
Connect-AzAccount -TenantID XXXX
Based on the debug details, you can check which Tenant is the user being connected to or any user details.
Try to connect with Subscription ID like below:
Connect-AzAccount -Subscription SubscriptionID -TenantId TenantID
Check if the user is having MFA enabled and try connecting with Global Admin account. And it might be the scenario where the account might be still cached in the local machine, so try if it works in another machine.
You can also make use of Device Authentication like below:
Connect-AzAccount -Tenant TenantID -UseDeviceAuthentication
Open the browser and enter the code:
Make sure to install the Az module like below:
Initially clear the cache and try to install by setting execution policy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Install-Module Az
Import-Module Az
Update-Module -Name Az
Check whether the user account in the Tenant has required permissions to the subscription.
Try to select the Context in PowerShell:
Get-AzContext -ListAvailable
Select-AzContext -Name Name
Or you can set context to the SubscriptionID by including TenantID:
Set-AzContext -Subscription $subscription -Tenant $tenantId | Out-null
If still the issue persists, it might be some environment problem while migrating the domain.
For me the problem seemed to be related to using a "legacy" account (or whatever they're called). Making and using a new account seemed to resolve the issue for me.

How to reset credentials of an Azure service principal using an automation account PowerShell runbook?

I'm trying to reset the password credentials of a service principal (let's call it SP1) through the following PowerShell commands:
Remove-AzADSpCredential -ObjectId <SP1_objectId> -Force
$Password = New-AzADSpCredential -ObjectId <SP1_objectId>
This works well when I run it through the PowerShell by my own user account, which has an Owner role assigned to SP1.
I also have this code in a runbook in an automation account with a "run as account" service principal (let's call it SP2).
I assigned the ownership of SP1 to SP2 as well through the command Add-AzureADServicePrincipalOwner and confirmed it through Get-AzureADServicePrincipalOwner.
I expected the runbook to be able to run the Remove-AzADSpCredential command on the SP1 after making its service principal the owner of SP1. But I get the following error:
Remove-AzADSpCredential : Insufficient privileges to complete the operation. At line:43 char:9 + Remove-AzADSpCredential -ObjectId $key.Name -Force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Remove-AzADSpCredential], Exception + FullyQualifiedErrorId : Microsoft.Azure.Commands.ActiveDirectory.RemoveAzureADSpCredentialCommand
And the same error for New-AzADSpCredential command as well.
I thought maybe the ownership of SP1 should be assigned to the App for the run as account, instead of its service principal.
So I also ran the following:
Add-AzureADServicePrincipalOwner -ObjectId <SP1_ObjectId> -RefObjectId <runasaccount_app_ObjectId>
But this wasn't possible, as I got the error:
Code: Request_BadRequest
Message: The reference target 'Application_xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx' of type 'Application' is invalid for the 'owners' reference.
So I assume the ownership should have been assigned only to SP2, and not to the app.
I looked at here but the accepted answer says
If your user accounts are the Owner of the service principal(Enterprise application), the command New-AzADSpCredential will work.
which is true in my case, and yet, it's not working when running the runbook.
I also looked at here and it seems I need to do the #1 which the OP describes as easy to do.
Any input on how to do this will be greatly appreciated.
If you want to use a service principal to add/remove credentials for another service principal, it is different from using a user account to do that.
I assigned the ownership of SP1 to SP2 as well through the command Add-AzureADServicePrincipalOwner and confirmed it through Get-AzureADServicePrincipalOwner.
This way is correct, but not only the Owner, also you need to give an Application.ReadWrite.OwnedBy Application permission in Azure Active Directory Graph (Not Microsoft Graph)API after that.
Navigate to the API permissions of your automation account corresponded AD App in the portal -> add the permission like below, don't forget to click the Grant admin consent for xxx button at last.
Then test it in the runbook, it works fine.
New-AzADSpCredential -ObjectId xxxxxxxxxxxxx
The combination of Owner and Application.ReadWrite.OwnedBy is the minimum privilege in this case, there are also other ways, you can also give the Application Administrator directory role as you saw here or Application.ReadWrite.All Application permission in Azure Active Directory Graph, both will work.

New-AzKeyVault - The provided information does not map to an AD object id

I am trying to add a Keyvault with PowerShell. I am always getting below two warnings while creating this. Though the vault is getting created successfully but, but want to understand how can I elminiate this warnings?
New-AzKeyVault -VaultName "kvxxxxxxxxxxx" `
-ResourceGroupName "RG-xxxx" -Location "South Central US"
WARNING: The provided information does not map to an AD object id.
WARNING: Access policy is not set. No user or application have access permission to use this vault. This can happen if the vault was created by a service principal. Please use Set-AzKeyVaultAccessPolicy to set access policies.
I can reproduce your issue on my side. The two WARNINGs were caused by your account is a Personal Account/Microsoft account(e.g. outlook, hotmail account) in your Azure AD tenant, your user type is Guest.
Actually you can just ignore them, or use the -WarningAction Ignore parameter as mentioned in the comment.
When using a work account/member user type to create a keyvault, it will add the account which used to create the keyvault to the access policy of the keyvault automatically. In your case, you could use the command Set-AzKeyVaultAccessPolicy to set the access policy after creating the keyvault.

Automate registering application to Azure AD for SSO

my organization has around 2000 applications which are required to be configured With Azure AD SSO and for that they need to be registered and allowed access to users on Azure AD.
I know how to do it manually, but is there any way to automate this whole process so that, I can register the application and grant users access they required?
thank you
Dheeraj Kumar
You can automate creation with Microsoft Graph API or Azure AD Graph API (though you should prefer MS Graph when possible).
In this case since you have what is basically a batch scenario in your hands, I feel PowerShell might be a good option.
There is a PowerShell module for administering Azure AD:
https://learn.microsoft.com/en-us/powershell/azure/active-directory/install-adv2?view=azureadps-2.0
https://www.powershellgallery.com/packages/AzureADPreview/2.0.0.127
First you sign in with
Connect-AzureAD
Then we can create an Application:
$app = New-AzureADApplication -DisplayName 'Created from PS' -IdentifierUris #('https://mytenant.onmicrosoft.com/PSTest1')
Then we need to create the service principal, this is normally done by the portal:
$sp = New-AzureADServicePrincipal -AppId $app.AppId -AppRoleAssignmentRequired $true
Note the AppRoleAssignmentRequired parameter.
Setting it to true will require users to be assigned to the app before they can login.
If you don't want that, just leave it out.
Now we can assign users.
You will need a user's ObjectId to assign them to the app.
You can use Get-AzureADUser in various ways to get the users you want to assign.
But the assignment can then be done like this:
New-AzureADUserAppRoleAssignment -Id '00000000-0000-0000-0000-000000000000' -PrincipalId $user.ObjectId -ResourceId $sp.ObjectId -ObjectId $user.ObjectId
If you had specified roles in your app for users, you could use the role's id instead of all zeros.
All zeros translates to "Default access" in the portal.

Running New-AzureRmResourceGroupDeployment from within a Function App

I need to wire up a stateless worker ad-hoc to perform a long running job based off a user action that self destructs when its done. I am trying to run New-AzureRmResourceGroupDeployment from within a PoSh Function App and cannot figure out how to authenticate to Azure from within the PoSh script.
I tried this:
$accountName = "myID#mydomain.com"
$pwd = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = new-object PSCredential($accountName, $pwd)
Add-AzureRmAccount -Credential $cred
New-AzureResourceGroupDeployment -ResourceGroupName yadda yadda
And I get an error message that I need to use an Organization ID (which I am, our Azure AD is federated and we use AD Sync (and SiteMinder w/o WS-* if that matters)):
Add-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials. For more information, please refer to http://go.microsoft.com/fwlink/?linkid=331007&clcid=0x409 for more information about the difference between an organizational account and a Microsoft account.
I tried "Login-AzureRMAccount -Credential $cred" with similar results.
If I do the Add- or Login- cmdlets from a PoSh window on my local machine (which is member joined to AD) with the -Credential flag I get a similar error. If I run the cmdlets without the credential I am prompted for credentials through an interactive ID/PW window (I do not have to enter my password once I type in my ID).
Does anyone know how I can do the authentication? I would be okay with authenticating like above, some sort of pass through credential from our web layer, or even an Option C I don't know about.
You will need to use service principal for authentication. A sample with instructions can be found here.
Azure Function role like permissions to Stop Azure Virtual Machines
For that you would need to use Service Principal auth. I don't think there is any sense of copypasting Azure Doc's to this answer, just consult this document:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal

Resources