Using powershell to connect to azure ad using access token - azure

I'm writing a powershell script to connect to azure ad using access token. I'm using below command:
Connect-AzureAD -TenantId "$tenantId" -AadAccessToken $tokenResponse.access_token -AccountId "$appId"
I have given application "Contirbute" & "Global Administrator" Role, also Application has all required permissions.
When I execute the script I can connect to Azure AD but if I try to run subsequent commands after this it gives be below error.
Please assist me on this further.
Get-AzureADUser : Error occurred while executing GetUsers
Code: Authentication_ExpiredToken
Message: Your access token has expired. Please renew it before submitting the request.
HttpStatusCode: Unauthorized
HttpStatusDescription: Unauthorized
HttpResponseStatus: Completed
At C:\Users\kajalchaudhari\Desktop\test_connect.ps1:22 char:1
+ Get-AzureADUser -Top 10
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-AzureADUser], ApiException
+ FullyQualifiedErrorId :
Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.GetUser

The error means the AAD Graph token you passed has expired, you need to pass a new one.
Or if you want to automate this, you could follow the steps below.
1.First, make sure you have installed the Az module. Then get the application id, tenant id, client secret of the AD App which is the global admin.
2.Then run the script below, it works fine on my side.
$azureAplicationId ="<application id>"
$azureTenantId= "<tenant id>"
$azurePassword = ConvertTo-SecureString "<client secret>" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
$aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id
Get-AzureADUser

seems like you need to configure the token expiry in Azure AD.
if you have already done that and the error message is instant then see if following blog is helpful
https://www.insight.com/en_US/content-and-resources/tech-tutorials/azure-active-directory-authentication-token.html

Related

How do I get groups from AAD using Powershell Function App?

I want to get all users from certain groups in AAD using Powershell with a Function app, but I keep getting permission errors and I don't know how to assign them.
$groupsAD = [System.Collections.ArrayList]#()
$groupsAD.Add('Group1')
$groupsAD.Add('Group2')
foreach ($groupAD in $groupsAD) {
$group = Get-AzADGroup -DisplayName $groupAD
# further code
}
The error:
[Error] ERROR: Insufficient privileges to complete the
operation.Exception :Type : System.ExceptionMessage :
Insufficient privileges to complete the operation.HResult :
-2146233088CategoryInfo : InvalidOperation: (:) [Get-AzADGroup], ExceptionFullyQualifiedErrorId :
Microsoft.Azure.Commands.ActiveDirectory.GetAzureADGroupCommandInvocationInfo
:MyCommand : Get-AzADGroupScriptLineNumber : 16OffsetInLine
: 14HistoryId : 1ScriptName :
C:\home\site\wwwroot\HttpTrigger1\run.ps1Line : $group =
Get-AzADGroup -DisplayName $groupADPositionMessage : At
C:\home\site\wwwroot\HttpTrigger\run.ps1:16 char:14+ $group =
Get-AzADGroup -DisplayName $groupAD
When creating this function locally it works fine after I authenticate with Connect-AzAccount.
Also tried to create an identity and authenticate it with it, but as far as I know it's for Azure resources not AAD.
For this problem, here provide two solutions for your reference:
1. If you use username/password to do authentication in Connect-AzAccount command, you need to make sure the user account has required permission for get AD group. Then use the code below in your function:
$User = "{username}"
$PWord = ConvertTo-SecureString -String "{password}" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
Connect-AzAccount -Credential $Credential
$group = Get-AzADGroup -DisplayName "{group name}"
2. If you do not want to use username/password to do authentication in your function. You can use service principal to do it.
First you need to register an app in your Azure AD, I registered an app named "huryGetToken6" in my Azure AD.
Then click "Certificates & secrets" tab, new client secret. Copy the client secret to your notepad.
Then add the permission to the registered app, do it with the steps in below screenshots.
Please do not forget click "Grant admin consent for xxx" after add the permissions to registered app.
After that, you can use the code below in your function to get AD group:
$username = "{client id/application id}"
$password = "{client secret}"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd
Connect-AzAccount -Credential $Credential -Tenant "{tenant id}" -ServicePrincipal
$group = Get-AzADGroup -DisplayName "huryGroup"
For the params in above commands, you can find the client id/application id and tenant id on the "Overview" page of your registered app.

Connect-MsolService : Authentication Error: Unexpected authentication failure

I'm trying to connect to azure AD using "App Passwords" as authentication MFA method through powershell script.
this is my script:
$username = 'user#example.com'
$Password = ConvertTo-SecureString 'MyPassword' -AsPlainText -Force
$creds = new-object System.Management.Automation.PSCredential($username, $password)
Connect-MsolService -Credential $creds
But I got this error:
Connect-MsolService : Authentication Error: Unexpected authentication failure
I had a similar issue. I ran the PowerShell below:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Connect-MsolService
You cannot put the password in the parameter, because the user logs in using MFA, not the username/password, you should let it pop up the login box and trigger MFA.
There is a similar problem here.

Access denied for setting up Azure B2B allow list domain using Graph API

I've created an registered app in Azure and I'be given the following API permissions for Graph API as follows:
**
Directory.ReadWrite.All
Policy.Read.All
Policy.ReadWrite.TrustFramework
User.Invite.All
User.Read
**
My plan is to add an allow list to the Azure B2B directory and then invite the guest user to my directory using the service principle i created above.
With the above permissions , I can read the current policy and send the invite to the guest user. But, I cannot append the exiting allowed domain list in my B2B directory.
Each time i try to update the existing policy I'm getting access denied as shown below:
**
Set-AzureADPolicy -Definition $policyValue -Id $currentpolicy.Id | Out-Null**
Error
Set-AzureADPolicy : Error occurred while executing SetPolicy
Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.
InnerError:
RequestId: 4f161b70-f71c-4507-8b91-788457429fcc
DateTimeStamp: Wed, 08 Apr 2020 16:57:39 GMT
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed
At line:1 char:1
+ Set-AzureADPolicy -Definition $policyValue -Id $currentpolicy.Id | Ou ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Set-AzureADPolicy], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.MSGraphBeta.Client.ApiException,Microsoft.Open.MSGraphBeta.PowerShell.SetPolicy
Does anyone had any ideas what is missing here?
Also can i confirm this operation is supported with Graph API at the moment?
Thanks
Balaip
According to some test, I just add the other three permissions under "Policy" to the app you registered. And then I can use Set-AzureADPolicy command success(with connecting to Azure AD with a service principle).
Update:
I provide all of the steps for your reference:
1. Run the command below in powershell
# 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 = "xxxxxxx"
$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 "huryttt1234" -IdentifierUris "https://huryttt1234"
New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "Huryttt1234" -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
2. Now I go to the new application(Huryttt1234) in AD on Azure portal and add the five permissions to it, and grant admin consent to it.
3. Then run command below:
# 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
Get-AzureADPolicy -Id xxxxxxxxxxxxxxxxxxxx
Set-AzureADPolicy -Definition #('{"TokenLifetimePolicy":{"Version":1,"MaxInactiveTime":"20:00:00"}}') -Id xxxxxxxxxxxxxxxxxxxx | Out-Null
I can run the bottom two lines(the get operation and set operation) successfully.

Connect-AzAccount - how to avoid azure device authentication?

I have installed the PowerShell 6.1.3 version and
I want to get a connection to the Azure account using the following Azure PowerShell command:
Connect-AzAccount -Tenant <tenantId> -Subscription <subId>
After entering this command I get the warning with the url and some code.
Then I have to go to the URL and enter the code there. After that, I get a connection to the Azure account.
Are there any ways to avoid this confirmation?
I've also tried to do it using the following command:
az login -u <username> -p <password>
This command only returns some account information(subscriptionId, tenantId etc) but it doesn't install a connection to this account.
1.To login with the user account, try the command as below, make sure your account doesn't enable the MFA(Multi-Factor Authentication).
$User = "xxx#xxxx.onmicrosoft.com"
$PWord = ConvertTo-SecureString -String "<Password>" -AsPlainText -Force
$tenant = "<tenant id>"
$subscription = "<subscription id>"
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User,$PWord
Connect-AzAccount -Credential $Credential -Tenant $tenant -Subscription $subscription
2.You can also use a service principal to login, use the command as below.
$azureAplicationId ="Azure AD Application Id"
$azureTenantId= "Your Tenant Id"
$azurePassword = ConvertTo-SecureString "strong password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
See a similar issue I answered here, it use the old AzureRM module, for Az, just change the last line.
If you are not familiar with service principal, Also see : How to: Use the portal to create an Azure AD application and service principal that can access resources, the application id and authentication key are the Azure AD Application Id and strong password you need.
You have 2 options.
Sign in with credentials (Requires Az.Accounts v 1.2.0 or higher)
You can also sign in with a PSCredential object authorized to connect to Azure. The easiest way to get a credential object is with the Get-Credential cmdlet. When run, this cmdlet will prompt you for a username/password credential pair.
$creds = Get-Credential
Connect-AzAccount -Credential $creds
Sign in with a service principal
Service principals are non-interactive Azure accounts. Like other user accounts, their permissions are managed with Azure Active Directory. By granting a service principal only the permissions it needs, your automation scripts stay secure.
To learn how to create a service principal for use with Azure PowerShell, see Create an Azure service principal with Azure PowerShell.
Source: https://learn.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azps-1.3.0
If Multi Factor Enabled then also below logic should work
$clientId = "***********************"
$clientSecret = "********************"
$tenantId = "***********************"
$tempPassword = ConvertTo-SecureString "$clientSecret" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($clientId ,
$tempPassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal

login to azure account without popup using powershell

I'm trying to create Azure VM using powershell.I have also the script to create it.
First I need to login into Azure account :
Login-AzureRMAccount
This gives a pop-up to enter the credentials.
Second I need to run the below script:
$UserName = "username"
$Password = ConvertTo-SecureString "password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)
New-AzureRmVm `
-ResourceGroupName "RG1" `
-Name "VM1" `
-ImageName "Image1" `
-Location "West US" `
-Credential $psCred
This is creating the VM successfully.
But now , I need to make these scripts run automatically, when ever there is requirement. The problem I'm facing is, the login step gives a popup to enter the credentials which I do not want. So I have tried something like this, but didn't work.
$username = "loginname#organization.com"
$SecurePassword = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $SecurePassword)
Login-AzureRmAccount -Credential $cred
The error message it is giving is :
Login-AzureRmAccount : accessing_ws_metadata_exchange_failed: Accessing WS metadata exchange failed: The underlying connection was closed: An unexpected error occurred on a send.
At line:4 char:1
+ Login-AzureRmAccount -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Connect-AzureRmAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
Can anyone tell me what this means and how to rectify this? Thanks!
If you are planning to automate any services into Azure using PowerShell, then I'd recommend connecting azure using Service Principal rather than your own credentials, it will be a secure way to connect.
What is Service principal?
An Azure service principal is a security identity used by user-created
apps, services, and automation tools to access specific Azure
resources. Think of it as a 'user identity' (username and password or
certificate) with a specific role, and tightly controlled permissions.
It only needs to be able to do specific things, unlike a general user
identity. It improves security if you only grant it the minimum
permissions level needed to perform its management tasks.
Follow this tutorial to create a service principal
I also have published a sample PowerShell workflow into Microsoft gallery for creating Service Principal you can also follow that.
Once you created your service principal, you can use the below PowerShell commands to login into azure without any popup's
$applicationId = "<service prinicple application id>";
$securePassword = "<service prinicple password>" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
Connect-AzureRmAccount -ServicePrincipal -Credential $credential -TenantId "<your tenantid>"
Update1:
For some reason/bug the above will get fails. Refer this github issue
To solve this
Add the two lines before the script
Import-Module -Name AzureRM.Profile
Remove-AzureRmAccount
Update 2:
AzureRM will no longer receive new cmdlets or features. However, the AzureRM module is still officially maintained and will get bug fixes through December 2020.
You have to use the new Azure PowerShell Az module
Basically you can achieve this for all of your PowerShell sessions by adding the Logging in part as part of the $PSProfile. I use this trick to skip the login popup, so whenever i open powershell my account is automatically logged in.
Open Windows PowerShell as an administrator
Type Notepad $profile
A notepad file will be opened and here you can paste the below code to
log in automatically whenever it is opened.
$username = “”
$password = “”
$securepasswd = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($username, $ securepasswd)
Connect-AzureRmAccount -Credential $cred

Resources