Connect-MgGraph with managed identity in Azure Automation produces an error - azure

I am using a system managed identity in an Azure Automation account. Separately, I gave the identity (Application) all the Graph access it requires. I am leveraging the Az module to get the access token, which I then pass to connect-mggraph. Natively, the MgGraph module does not yet support the managed identity natively.
Here is the code I am using to attempt the connection. My expectation is that the "connect-mgraph" will succeed using the managed identity.
Connect-AzAccount -Identity
$token = Get-AzAccessToken -ResourceTypeName MSGraph
Connect-MgGraph -AccessToken $token.token
This is the returned error:
3 | Connect-MgGraph -AccessToken $token.token
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0,
| Culture=neutral, PublicKeyToken=30ad4fe6xxxxxxxx'. The system cannot
| find the file specified.
Get-MgGroup_List: C:\Temp\jka4ters.qmd\f1cc4605-9c45-4b6e-a89a-xxxxxxxxxxxx.ps1:5
I've tried various minor alterations to the code, but always get the same error. Others seem to have success with this online. Any ideas?

I tried in my environment and got below results:
Initially I tried the same commands in automation(powershel-7.1) and got same error.
Console:
Instead of using -ResourceTypeName MSGraph I have used -ResourceUrl "https://graph.microsoft.com" in below commands.
Also please ensure that you have using both module and runbook in same runtimeversion.
#Connect to Microsoft Graph within Azure Automation
Connect-AzAccount -Identity
$token = Get-AzAccessToken -ResourceUrl "https://graph.microsoft.com"
Connect-MgGraph -AccessToken $token.Token
After I executed above commands the MgGraph is connected successfully.
Console:

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.

Automate connecting to Azure for checking and creating resources without prompt

I am required to write a PowerShell script, which can connect to my company's Azure account, check and create Azure resources (eg. Service Bus namespace, Service Bus topic, and Service Bus subscriptions). Everything worked well until I tried to deploy my script as a step in my project's on-premise TeamCity. I keep getting this error message
Exception calling "ShouldContinue" with "2" argument(s): "Windows
PowerShell is in NonInteractive mode. Read and Prompt functionality is
not available."
I investigated and found out that the problem is in this line
Connect-AzAccount
If I run the script manually, it will pop up a prompt asking me to login to Azure. I believe that's what went wrong. Because my project's on-premise TeamCity does not seem have an option to open a prompt for PowerShell command. I have read some workarounds, even on this website, but none of them is applicable to my case. Even a solution like https://stackoverflow.com/a/61099568/8213536 gave me these errors
WARNING: Unable to acquire token for tenant 'organizations' with error
'UsernamePasswordCredential authentication failed: There was an error
parsing WS-Trust response from the endpoint. This may occur if there
is an issue with your ADFS configuration. See
https://aka.ms/msal-net-iwa-troubleshooting for more details. Error
Message: Object reference not set to an instance of an object. See the
troubleshooting guide for more information.
https://aka.ms/azsdk/net/identity/usernamepasswordcredential/troubleshoot'
Connect-AzAccount : UsernamePasswordCredential authentication failed:
There was an error parsing WS-Trust response from the endpoint. This
may occur if there is an issue with your ADFS configuration. See
https://aka.ms/msal-net-iwa-troubleshooting for more details. Error
Message: Object reference not set to an instance of an object. See the
troubleshooting guide for more information.
https://aka.ms/azsdk/net/identity/usernamepasswordcredential/troubleshoot
At line:1 char:1
Connect-AzAccount -Credential $creds
+ CategoryInfo : CloseError: (:) [Connect-AzAccount], AuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
One of the other solutions https://stackoverflow.com/a/52014189/8213536 requires an application's principal id, which is not applicable for my scenario either, as I am not creating a new application. I just need to be able to automatically connect to Azure (without prompt), check and create SB Namespace, SB Topic and SB Subscription.
Could someone please help me on this? Thanks.
As promised, I would like to post my solution. First I created a service principal with a client secret key. Then I asked my company's cloud engineer to assign it to the Azure subscription of my company and to the resource group that I intended to group all my necessary resources into. Finally in my code, I implemented something similar to https://stackoverflow.com/a/61099568/8213536
$applicationId = $azServicePrincipalId
Write-Host "Connecting to Azure using principal $applicationId"
$securePassword = $azServicePrincipalPw | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
Connect-AzAccount -ServicePrincipal -TenantId $azureTenantId -Credential $credential
$azServicePrincipalId and $azServicePrincipalPw came from the Service Principal itself, while $azureTenantId came from my company's Azure subscription.
It is now working as expected.

Unable to Access SharePoint using PowerShell

I have registered an Application on Azure and I am trying to get an access token using the following command.
$Auth=Get-ODAuthentication -ClientId 01xex4x7-f0e2-xbx4-8aa3-1ac7a46c784c -AppKey "Xm1234~x555Sr-ATtpyCBOzkYiakI.PCVkEuBZ" -RedirectURI "http://localhost/login" -ResourceId "https://xyz.sharepoint.com/" -RefreshToken $LastAuth.refresh_token .
I am getting the following error.
Add-Member : Cannot bind argument to parameter 'Name' because it is an
empty string. At
C:\Users\Administrator\Documents\WindowsPowerShell\Modules\OneDrive\2.2.7\OneDrive.psm1:127
char:47
... thentication | add-member Noteproperty $element.split("=")[0] $elemen ..
However, when I save the command to a script and add a timeout, I am able to get the access token.
I have set the REDIRECT URI as http://localhost/login (Not an actual working URL). Can this be the reason. I tried to look this up but a little confused about the value this should have. Any pointers are greatly appreciated.
We have tested the same in our environment to access the sharepoint by using powershell and it works fine at our end. Below is the workaround :-
Register an application in Azure AD , Added redirect uri as http://localhost/ and enabled ID token .
Given the below permissions to our application and granted admin consent in Azure Ad.
Installed the one drive module by using Install-Module -Name OneDrive -Scope CurrentUser -force
Used the below command to get the access token after login with connect-azaccount , Ensure that you have provided all the permissions as mentioned above and added the correct resource ID of your sharepoint application and redirect uri as followed.
Cmdlt:-
$Auth=Get-ODAuthentication -ClientId "60xxxxxxxxxxxxxxxxx" -AppKey "3aXXXXXXXXXXXXXXXXXXXXXXXXXX=" -RedirectURI "http://localhost/" -ResourceId "https://mytest-admin.sharepoint.com/" -RefreshToken $LastAuth.refresh_token
OUTPUT DETAILS :-
POWERSHELL VERSION:
For more information please refer this GitHub| OneDrive for Business

Powershell command to find access and refresh token time

In the past we configured token lifetime for access and refresh tokens but now i would like to find the time line set in the past.
I found PS commands to change the token lifetime but not able to find the command to validate it.
Is there a powershell command which i can run to find the access and refresh tokens lifetime set in Azure AD for the portal and applications?
I suppose you configured the token lifetime with azure ad policy, if so, you could try the command as below, make sure you have installed the AzureADPreview powershell module.
Sample:
Get-AzureADPolicy - Get all the TokenLifetimePolicys in your AAD tenant :
Get-AzureADPolicy | Where-Object {$_.Type -eq 'TokenLifetimePolicy'} | ConvertTo-Json
Get-AzureADServicePrincipalPolicy - Get the policy which has been assigned to the service principal :
Get-AzureADServicePrincipalPolicy -Id "<object id of service principal>" | ConvertTo-Json
Get-AzureADApplicationPolicy - Get the policy which has been assigned to the AAD application:
Get-AzureADApplicationPolicy -Id "<object id of application>" | ConvertTo-Json
For more details, refer to this doc - Configurable token lifetimes in Azure Active Directory (Preview).

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