Add-AzureAccount : Index was out of range. Must be a non-negative and less than the size of the collection - powershell

On 4th of August a new version of the Azure powershell module (0.8.7.1) was released. In it is the ability to create credentials which you could then pass to the Add-AzureAccount function. Add-AzureAccount allows you to pull in an account to work with in the current PowerShell session.
$userName = "buildmaster#someaccount.onmicrosoft.com"
$securePassword = ConvertTo-SecureString -String "somepassword." -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($userName, $securePassword)
Add-AzureAccount -Credential $cred
This allowed me to get away from a popup window or messing with a settings file.
It seems to have stopped working! Both Add-AzureAccount (which pops up a window) and the credential based way. They now return an index was out of range issue.
Add-AzureAccount : Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
At S:\QA\Azure Scripts\cm-azure-helpers.psm1:1128 char:5
+ Add-AzureAccount
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Add-AzureAccount], ArgumentOutOfRangeException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.AddAzureAccount
Digging deeper with Fiddler shows that the OAuth call to the back end service seems to work. I get a token returned. But then I also get a 302 in the middle of the process stating that the page has moved. I don't know if that redirect was there when it was working previously or not.
Has anyone else experienced the Add-AzureAccount function just stop working like this? And more importantly - have you found a way around it?
Update - More info
I have now tried on several boxes under different azure accounts and seem to have the same results. I get a valid auth token returned with a redirect in the middle (not sure if that is an issue or not) and then get the index was out of range.
I have done this with the following variations:
PS:3 Azure Module: 0.8.6
PS:3 Azure Module: 0.8.7
PS:4 Azure Module: 0.8.6
PS:4 Azure Module: 0.8.7

I know exactly what caused this error for me, and how I worked around it (I thought I was the only one who had seen this :))
What had happened is that I had accidentally added a bogus/empty subscription to my account. And this empty subscription had been set to my "default" subscription.
Run "get-azuresubscription -default" to see what your default subscription is. You can then "remove" any junk subscriptions using "remove-azuresubscription" command.
You can then of course set a new azure subscription for your "default" using PS.
I actually reported this to the Azure PowerShell team now to get a better error message during this scenario.
Hopefully this solved your problem, it's possible other errors manifest the same error message.

If you do a fiddler trace, you should see that right after the login call (where PowerShell passes in your username/password, there should be 1 or multiple calls to GET /subscriptions.
Check the response to see whether there is anything suspicious there. Like, any of them return an empty body, empty array, subscription with id, name, etc..

I had a similar problem recently. The "fix" was for me was to delete the files at C:\Users[username]AppData\Roaming\Windows Azure Powershell (esp. the WindowsAzureProfile.xml file). The next time I ran Add-AzureAccount, the necessary files were created and all was well.

Please use:
Add-AzureRmAccount -SubscriptionId "id";
for login

Related

Wait for Active Directory Authentication URL list to update within a Powershell Azure Function

I need to ensure a reply url is added to a v2 Active Directory App before returning a HTTP response within a Powershell Serverless Function.
Currently I've successfully managed connecting to azure using a service principal, getting the active directory application & updating the authentication list with a new reply url.
This works great but there seems to be some propagation period on completing the job. Everything happens as mentioned in a Powershell Serverless Function & returns a 200 HTTP status when finished.
Once the response (HTTP 200 OK) is received I'm using the Active Directory Authentication Library (ADAL) to log in from some JS app using a full page redirect.
This is where the issue lies, once the Powershell runs & returns the client app tries to login with ADAL but that Active Directory prompts with an error, the supplied url isn't one currently on the authentication list.
I've looked into Start-ThreadJob & Wait-Job but not sure if number one I'm using it correctly or number two it is the best approach.
Example code:
$appId = <ACTIVE_DIRECTORY_APP_ID>
$url = <NEW REPLY URL>
$password = ConvertTo-SecureString -String $env:SERVICE_PRINCIPAL_SECRET -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($env:SERVICE_PRINCIPAL_ID, $password)
Connect-AzAccount -ServicePrincipal -Credential $credential -Tenant $env:TENANT_ID
$app = Get-AzADApplication -ApplicationId $appId
$replyUrlList = $app.ReplyUrls
$replyUrlList.Add($url)
Update-AzADApplication -ApplicationId $appId -ReplyUrl $replyUrlList
$status = [HttpStatusCode]::Created
$body = "URL Added Successfully"
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = $status
Body = $body
})
At the moment the AD authentication list is updated anywhere from 1 minute - 5 minutes in some cases. Depending if the function is booting from cold-start.
Should I use a loop to check the AD Application information within the Powershell script?
Should I use job threading & wait job cmdlets?
Maybe throw in a bit of sleep?
Just looking for the best approach here to guarantee the new callback url is 100% added before trying to authenticate with the ADAL library.
Any help would be great!
This is not an answer with a solution. But I think I'm reading something that I have experienced on several occasions.
I've been using python and Hashicorp vault to try and manage tokens/RBAC on applications. But very often it would break because it had not updated yet, due to the propagation from AAD to back end being asynchronous from what I was told.
I even did checks where I used ADAL to loop over the application to verify if it was good. But even then it would still fail on some occasions. Which hurt the automation I was trying to put in place.
Now you are having some issue that seems similar, but instead while adding the reply url to an existing application.
My question for testing is; does the reply URL work when it is supplied upon creation of the application? If so, and testing is 100%, then you are having the same issue.
For me, pre-creation of all necessary properties on applications is what helped me circumvent this annoying issue. As I don't think adding a sleep anywhere is a good way to move forward, and the reply from the API isn't reliable enough to work on.
If pre-creation is not an option, I suppose the sleep timer is probably some way forward. For me, that ended up being 2-5m in some cases. And in some lucky cases 7-30s

Teams PowerShell: Access token validation failure

I am trying to create a team with the new Teams Powershell. Looks like everything is working, until I try to use my service account instead of my own.
The code below is working, if I replace the $credential line and use my own credentials. If I use the automation account, then I got this:
New-Team : Error occurred while executing
Code: InvalidAuthenticationToken
Message: Access token validation failure.
I tried searching for this error message, but I only found Graph API samples, that happen behind the scenes of the Teams PowerShell. I also tried other scripts, like PnP, they all work fine with the same automation account. Is this a bug in the Teams API self or can I do something on my side?
$credential = Get-AutomationPSCredential -Name 'provisioning'
$connection = Connect-MicrosoftTeams -Credential $credential
$t = Get-Team -DisplayName "TEST"
Assuming your service account has proper privileges to create channel.
Reference: https://learn.microsoft.com/en-us/graph/api/team-put-teams?view=graph-rest-1.0
If you reckon you have proper privileges to create teams and channels then make sure you give full scope to the service account
Connect-PnPOnline -Scopes "Group.ReadWrite.All"
Hope it will give you some idea to solve the error. Thanks

Login-AzureRMAccount returns "Unknown User Type"

As the title implies, I'm trying to automate the login process to AzureRMAccount in Powershell.
I've scoured every forum on every website I can find trying every different combination of solutions (well, except for the solution that works).
Every time I try to automate the login process of my Azure account, I get an error :
Unknown User Type
Yes, I have full access to this account, and Yes it does work fine if I omit all of the parameters and allow for the interactive username/password dialog.
I have even tried to simply call the Get-Credentials and push those into a variable and then call Login-AzureRMAccount using those creds....no luck.
Add-AzureRMAccount fails too.
Any help would be appreciated.
I did find one solution, although it's not the most secure solution as it generates a disk file putting your information at risk if someone were to gain access to the machine on which the Powershell code is executing.
You can login interactively and immediately export the context to a json file, Then at a later time, import that json file as the current context to bypass login
PS C:\> Save-AzureRmContext -Profile (Add-AzureRmAccount) -Path C:\test.json
then in a later session, Import the context
PS C:\> Import-AzureRmContext -Path C:\test.json
Again, this is not the most secure option but it did achieve the results. I would love to have a more secure option.

Configurable token lifetimes in Azure Active Directory

I could not assign TokenLifetimePolicy Azure AD application policy from PowerShell. I had an error BadRequest : Message: Open navigation properties are not supported on OpenTypes.Property name: 'policies
I am trying to implement token expiry time from Configurable token lifetimes in Azure Active Directory
See screenshot below, any useful links and solutions on the AzureAD cmdlet Add-AzureADApplicationPolicy are welcome
I made it work by only using New-AzureADPolicy cmdlet and setting -IsOrganizationDefault $true not $false. The effect takes a while for you to see it. So wait for about 30 minutes to an hour (I don't know how long exactly). After that your new policy will be created and applied. Also remember that this is PowerShell, so no whitespaces in the cmdlet.
Example:
New-AzureADPolicy -Definition #('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"02:00:00","MaxInactiveTime":"02:00:00","MaxAgeSessionSingleFactor":"02:00:00"}}') -DisplayName "PolicyScenario" -IsOrganizationDefault $true -Type "TokenLifetimePolicy"
Multi-Line version:
New-AzureADPolicy -Definition #(
'
{
"TokenLifetimePolicy":
{
"Version": 1,
"AccessTokenLifetime": "02:00:00",
"MaxInactiveTime": "02:00:00",
"MaxAgeSessionSingleFactor": "02:00:00"
}
}
'
) -DisplayName "PolicyScenario" -IsOrganizationDefault $true -Type "TokenLifetimePolicy"
Microsoft may fix the issue with IsOrganizationDefault $true. Read more on this in the question: Azure AD Configurable Token Lifetimes not being Applied.
I test this quite a bit for my customers. I run into issues like this every now and then due to not on the latest version of PowerShell.
get-module
Latest Version 2.0.0.114 at the moment for AzureADPreview (V2)
Instructions to download here
There was an issue with -IsOrganizationDefault $true as Seth has pointed out.
Another issue I've found is having multiple versions of PowerShell on your system and it's loading the wrong one that doesn't have the updated bits. I hit this last Friday - I had to wipe everything and reinstall - then it fixed it.
Also -
There is a difference between:
Add-AzureADApplicationPolicy
and
Add-AzureADServicePrincipalPolicy
One is for an application object and the other is for a ServicePrincipal. If you are applying it to say, a SAML-Based application, then you should apply it to the ServicePrincpal.
Note: There is a different ObjectID for the application object and the servicePrincipal object. Don't get these confused. For an experiment, run the two cmds against your application:
Get-AzureADServicePrincipal -SearchString <name of app>
Get-AzureADApplication -SearchString <name of app>
If you grab the wrong ObjectID - no go when you go to apply the policy
The sequence for these Policies are: ServicePrincipal -> Application -> Tenant (organization)
Was the application created in B2C portal?
Assuming the answer is yes, this behavior is expected:
Microsoft has 2 authorization end points, V1 and V2.
B2C portal creates V2 apps. The token lifetime setting from powershell probably only works against the V1 apps.
There are settings on the b2c blade to change this.
The other option is to create an app from the azure active directory blade(as opposed to the b2c blade). Then you can set the token life time using powershell.

Azure Powershell - get-AzureVM returning an accountName does not exist error?

I'm at a bit of a loss with where to start with this one.
I have one Azure account with 2 subscriptions (I'm not the full admin just a co-admin so can't edit them) and both are called Pay-As-You-Go with different IDs.
I can connect powershell to the account and log in, list the subscriptions, select the subscription that I want to use.
However when I issue the get-AzureVM command either in a script or from the
command line I get the error below:
Get-AzureVM : Account with name 'Pay-As-You-Go' does not exist.
Parameter name: accountName
At line:1 char:1
+ Get-AzureVM
+ ~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureVM], ArgumentException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.GetAzureVMCommand
I can enter a specific VM name and service name and get the same error back.
My confusion stems from the fact that I haven't specified that account name as far as I'm aware in the command.
I have been playing around on the machine quite a lot this morning with writing wrapper scripts to allow selection of different user name connections via a prompt and selection of the relevant subscription but nothing I'm aware would have affected this command.
I can still run the commands below and get the output I expect:
Get-AzureAccount
Get-AzureSubscription -current
So the session is working for sure.
The VM I am trying to query was created from a custom image this morning and I can RDP to it and it seems to be running normally
Any ideas would be great?
The best way to do that it is to Execute the command Clear-AzureProfile it will require you to login again the problem it is that you account has been logged out. The sam problem happens when you have 2 different subscription for 2 different accounts and you change from one to another after executing some commands on the first one. Using the clear command after the switch solves that.
Well, I'm not sure of the root cause of this one, restarting the machine, opening closing the IDE etc had no effect.
But I did find by running Remove-AzureAccount and then running Add-AzureAccount again that it resolved.
So I just removed my account from powershell and re-added it to solve...