Trying to connect via PowerShell to Azure with new AZ Module - azure

I'm desperate here with Powershell and Azure.
I use PowerShell 7.0.1 and AZ 4.1.0.
When I try to connect (by the way, as global admin via 'Connect-AzAccount'), I get this prompt every time: "WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code xxxxxxxxx to authenticate."
Of course I do that and then I get this error message every time:
Connect-AzAccount: xxxxxxxxxxxxx: Device authentication is required.
Trace ID: xxxxxxxxxxxxxxxxxxxxxxxxx
Correlation ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Timestamp: 2020-05-20 09:12:18Z: Response status code does not indicate success: 401 (Unauthorized).
Does anyone have an idea why this does not work? I have also tried it temporarily without MFA, with the same result.

As Allen pointed, the right thing to do in this case is to engage the ActiveDirectory authentication team.
Meanwhile, can you try the preview of the new authentication experience here.
This uses a vastly updated authentication experience, and may unblock you while we work out the underlying issue.
Use the below script to install Az.Accounts 2.0.1-preview module.
Install-Module -Name Az.Accounts -AllowPrerelease
For more details, you could refer to this issue.

I have installed Az.Accounts 2.0.1-preview, but now a different error message appears. After connecting all seams working fine, but after calling a function it comes to an error again:
PS> Connect-AzAccount -Subscription 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
WARNING: Attempting to launch a browser for authorization code login.
WARNING: We have launched a browser for you to login. For the old experience with device code flow, please run 'Connect-AzAccount -UseDeviceAuthentication'.
WARNING: Unable to acquire token for tenant 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'
Account SubscriptionName TenantId Environment
------- ---------------- -------- -----------
michael.kristen#inhouse.wko.at INH-Subscription xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx AzureCloud
PS> Get-AzDefault
Get-AzDefault: Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your Azure credentials.

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.

Powershell - Connecting to SQL Server using Connect-AzAccount (With MFA)

We have a SQL Server set up (created by me, with my account as the admin account), and using Management Studio, I can access the database just fine. I'm now trying to achieve the same thing through Powershell.I have created my own user using:
CREATE USER [<my ccount>] FROM EXTERNAL PROVIDER
I start by connecting using MFA (and signing in using the pop-up window/MFA):
Connect-AzAccount -SubscriptionId $subscriptionID
This works fine, and returns the expected values of the subscription specified, and my Azure AD Login as account. I can access my KeyVault and pull secrets from there.
I now would like to connect to my SQL Server using the credentials I'm already signed in with within the PowerShell session, and that's where I get stuck.
I tried a ConnectionString including Authentication=Active Directory Integrated, but that throws an error Exception calling "Open" with "0" argument(s): "One or more errors occurred.".
I then tried using a connection string like this: Server=tcp:<server>.database.windows.net,1433;Initial Catalog=<database>;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30, and adding an AccessToken using SqlConn.AccessToken = $(Get-AzAccessToken -ResourceUrl "Https://database.windows.net/").
However, when I then try to Open the connection, I get the error: "Login failed for user '<token-identified principal>'."
Googling led to several SO articles, but none of those use Connect-AzAccount, but the (what I believe to be outdated) Az Account (I.e. Connecting to SQL Server using Powershell with Azure AD MFA).
Other examples I found all add UID and Password, which should not be needed considering I authenticated already.
Is there a way to use the existing Connect-AzAccount session to authenticate against my Azure SQL Server, and if so, what format should the ConnectionString have? I have a feeling I'm very close to a solution, but just cannot seem to actually achieve the opening of the connection.
Thanks in advance.
After reading more and more, I finally stumbled across this thread. #golfalot's answer was exactly what I needed.
So the proper code to initialize the connection is:
# Sign in to Azure
Connect-AzAccount -SubscriptionID $subscriptionID
$connectionString = "Server=<server>.database.windows.net;Initial Catalog=<database>;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30"
$accessToken = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token
$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = $connectionString
$sqlConn.AccessToken = $accessToken
$sqlConn.Open()

ClientSecretCredential authentication failed: A configuration issue is preventing authentication - check the error message from the server for details

I am trying to get the access token of the service principal using the following code.
$authUrl = "https://login.windows.net/" + $tenantid + "/oauth2/token/"
$body = #{
grant_type = "client_credentials"
client_id = $serviceprincipalid
resource = "https://management.azure.com/"
client_secret = $serviceprincipalkey
};
$response = Invoke-RestMethod –Uri $authUrl –Method POST –Body $body
Write-Host $response
Write-Output $response.access_token
##vso[task.setvariable variable=myToken;]$response.access_token
The above code is working perfectly at my local machine's PowerShell but it is giving the following error when I am running the same code base in the Azure DevOps pipeline.
ClientSecretCredential authentication failed: A configuration issue is preventing
authentication - check the error message from the server for details. You can modify the
configuration in the application registration portal. See https://aka.ms/msal-net-invalid-
client for details. Original exception: AADSTS7000222: The provided client secret keys are
expired. Visit the Azure Portal to create new keys for your app, or consider using certificate
credentials for added security: https://learn.microsoft.com/azure/active-
directory/develop/active-directory-certificate-credentials
Trace ID: 98787ui7-e8ae-4712-b8b5-7678u8765rt5
Correlation ID: yhjnbv43-56sy-9ksy-b8b5-mj876yu78i90
Timestamp: 2021-03-16 12:32:28Z
There was an error with the service principal used for the deployment.`
I checked the secret keys, but the secret keys not expired, it's expiry date is already set for the year 2022. And if it would expire then the code should not have worked at my local machine's PowerShell.
Does anyone have any idea? please let me know to resolve this issue.
Well, actually the error was not caused by the script above, per my test, it works fine in devops.
If you use the Azure PowerShell task, it will let you configure a service connection to use, when you run the task, it will connect Azure powershell with the service principal configured in the service connection automatically. The error was caused by the expired secret of the service principal configured in the service connection, not the one in your script.
I can also reproduce your issue on my side.
To solve this issue, please follow the steps below.
1.Navigate to the Azure PowerShell task, check which service connection you used.
2.Navigate to the Project Settings in devops -> Service connections -> find the one you used -> click it -> Manage Service Principal.
Then it will open the related AD App page, just create a new secret and service connection, use it in the Azure Powershell task, follow the same steps I have mentioned here.
3.After configuration, test it again, it will work fine.

How to create AzureProfile.json file using AzModule command in PowerShell?

I want to create the AzureProfile.json file using the Az Module command in PowerShell, so that I can import the json file anytime I want to login to Azure to start\stop my VM's.
Below is the command\script I am using to create it but it is giving me error as shown in the screenshot.
I tried using the below code as well but it gives same error.
Connect-AzAccount -UseDeviceAuthentication
Save-AzProfile -path "$PSScriptRoot\AzureProfile.json"
WARNING: Unable to acquire token for tenant 'organizations'
Connect-AzAccount : DeviceCodeCredential authentication failed: Retry
failed after 4 tries.
From the error message, it looks like the authentication of your account is failing in the Browser pop-up that comes after Login-AzAccount.
I ran the first set of commands and it ran successfully.
Powershell:
Created File:
Note that my PowerShell version is 5.7.0.18831.
You have tried both :
Connect-AzAccount -UseDeviceAuthentication
Login-AzAccount
Both Interactive and non-interactive mode of login.
The error is occurring while trying you communicate to azure. I am suspecting it could be an issue at a machine level or network level (proxy/firewall)
The above issue usually occurs (reproducible at my end) when there are connection issues with the Microsoft Services - blocked by proxy /firewall/GPO etc...
For a quick test you could run the below PowerShell command :
Invoke-WebRequest -Uri "https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode" -Body "client_id=1950a258-227b-4e31-a9cf-717495945fc2&scope=https%3A%2F%2Fmanagement.core.windows.net%2F%2F.default+offline_access+profile+openid" -Method Post
Sample Success Response :
Why the above command ?
The above end point https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode is hit when you use Connect-AzAccount -UseDeviceAuthentication by powershell.
If you encounter a timeout/Name unresolvable issue - the issue is with the network/machine config.

Cannot connect using Connect-MsolService

Im using powershell to connect to azure but I´m not able to connect using Connect-MsolService. When I try using Connect-AzureAD it shows a prompt asking for my credentials and I enter it and it connects normally. But when I try using Connect-MsolService I put the same credentials on the prompt but it fails saying that the email or password is wrong (but its the same credentials for the Connect-AzureAD command).
You should install the latest AzureAD module.
https://learn.microsoft.com/en-us/powershell/module/azuread/
Logon with Connect-AzureAD
Confirm Domain with Confirm-AzureADDomain

Resources