Teams PowerShell: Access token validation failure - powershell

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

Related

Execute an App registration without AzureAD

For a professional project, a chunk of the pipeline must be able to create an application (the first App registration, so I only have a global Admin) automatically within Azure AD. So far I used AzureAD which works well with Powershell 5.6 on Windows.
I now must be able to run the code with Ubuntu 20.04 and its Powershell 7.2. Unfortunately for me, AzureAD module is only supported on non-core Windows PowerShell, therefore it does not work on core PS6 or PS7. A very simplified piece of code is the following:
# Connection infos
$tenantId = "abcdef12345-1234-1234-124-abcdef12346789"
$account = "my_admin#domain.com" # Is cloud Admin by default
$password = ConvertTo-SecureString "MyPassword" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($account, $password)
Connect-AzureAD -Credential $psCred -Tenant $tenantId
# Create app
$appName = "MyApp"
New-App -appName $appName -tenant_id $tenantId
I am stuck and my question is the following: how could I run such an operation with Powershell 7.2 considering AzureAD is not usable? I did check Connect-MgGraph for the connection part only (https://github.com/microsoftgraph/msgraph-sdk-powershell) but the clientId is an infos that I don't have -and want to create-.
Thanks in advance
You can use DeviceLogin as explained in this article to obtain an oAuth access token for you Global Administrator account in PowerShell (independent of the version) but this first step needs a human interaction.
After obtaining the token, you can use it to make Graph API calls with your Global Administrator permissions to create an application.
Once you create your first application, you must attribute required permissions and use it to automate the process (obtain token programmatically using API calls) for application creation in PowerShell.
You could use Resource Owner Password Credentials (ROPC) to authenticate, however Microsoft actively discourages it in their documentation due to the security implications of sending a password over the wire.
If the security issues present with this method of authentication are still tolerated within your acceptance criteria, you would still need a ClientID. Luckily, AzureAD has a well-known ClientID that you can use to authenticate. This ID is 1950a258-227b-4e31-a9cf-717495945fc2
The below Powershell code should get you started. I've basically translated the HTTP request within Microsoft's documentation into a splatted Invoke-RestMethod command.
$LoginWithROPCParameters = #{
URI = "https://login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token"
Method = "POST"
Body = #{
client_id = "1950a258-227b-4e31-a9cf-717495945fc2"
scope = "user.read openid profile offline_access"
username = "username#contoso.onmicrosoft.com"
password = "hunter2"
grant_type = "password"
}
}
Invoke-RestMethod #LoginWithROPCParameters

Authentication error using SharePoint (Online) Migration?

Using SharePoint Migration Tool for document migration to SharePoint Online. Everything is going pretty smoothly, but for some unknown reason it keeps spitting back this error:
Task 5f91e154-64ad-4f64-bf26-c73368fcd77b did NOT pass the parameter validation, the error message is 'Username or password for target site https://{company}.sharepoint.com/sites/it-test-team/Temp%20Location/Forms/AllItems.aspx is not correct'
Have checked and doublechecked my credentials. I even changed my password (and updated it in my code) in case that was the issue. My guess is that something with multi-factor authentication is causing an issue. In order to login, my company requires the use of the Microsoft Authenticator app (I need to input a code that the app gives me). If that's the issue, how do I work that into my code? If it's not, what IS the issue?
Notes: I have the correct permissions (I am owner of the SharePoint Online site, I am running Powershell ISE as an administrator, I've set the correct Execution Policies)
Here's my code:
Import-Module Microsoft.SharePoint.MigrationTool.PowerShell
$Global:SPOUrl = "https://o365gcoslo.sharepoint.com/sites/it-test-team/Temp%20Location/Forms/AllItems.aspx"
$cred = (Get-Credential ~my company email~)
$Global:SPOCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $cred
#Define SPMT task vars
$Global:FileshareSource = "I:\Applications\Temp_PTAX"
$Global:TargetListName = "Temp Location"
#Register the SPMT session with SPO credentials#
Register-SPMTMigration -SPOCredential $Global:SPOCredential -Force
#File Migration task
Add-SPMTTask -FileShareSource $Global:FileshareSource -TargetSiteUrl $Global:SPOUrl -TargetList $Global:TargetListName
Start-SPMTMigration -NoShow
$session = Get-SPMTMigration
#migration stuff here

How to get tenant properties through PowerShell with SharePointPnP?

I have been given a task to setup a scheduled task which will run daily to pull down the list of allowed domains from SPO. This is not an issue if I use Connect-SPOService and Get-SPOTenant, like this:
Connect-SPOService –url https://xxxx-admin.sharepoint.com
Get-SPOTenant | select -ExpandProperty SharingAllowedDomainList > d:\allowedDomains.txt
The issue issue is that this has to be automated. There is also a requirement to use an ClientId and Secret in the script, rather than providing me with an account which bypasses MFA and has SP Admin rights.
Because of that, I've turned to SharePointPnP, which does allow you to connect with ClientId and Secret. I'm able to connect to connect with the following:
Connect-PnPOnline -url https://xxxx-admin.sharepoint.com -ClientId "xxxxx" -ClientSecret "xxxxx"
Where I'm struggling now is trying to how I can retrieve the SharingAllowedDomainList property through SharePointPnP, or if that is even possible?
#THTX,
Can you please have a try below pnp powershell cmdlet?
Get-PnPTenant
Get-PnPTenantSite
It has SharingAllowedDomainList property:
BR

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

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

Validate Service Account Powershell

I want to write a Powershell script that will validate a large number of service accounts that was provided to me by my AD team. Not that I don't trust them but I want to cycle thru each domain username and password to see if it logs in or fails. I am looking for some suggestions so far my attempts have failed (see post http://tjo.me/fKtvPM).
Thanks
P.S. I don't have access to AD so I have to try to login using the credentials to test.
This is really hacky (ugly for least-privileged model), but if you know that all of the service accounts have access to a particular program / file, you can try to start a process using their credentials.
$cred = get-credential # however you're getting the info from AD team, pass it hear to get-credential
start-process powershell -argumentlist "-command","exit" -cred (get-credential)
$? # if $true, process started (and exited) successfully, else failed (either bad creds or account can't access powershell.exe
Unfortunately, since you can't query AD directly, I think any solution is going to be a bit of a hack, since by definition you're going to have to simulate logging in as the user account.