Mar 21 2021 08:05 AM - edited Mar 21 2021 08:09 AM
Hi All,
I need to use an App password in a PowerShell script that will be running constantly. The script needs to monitor an item on a server so needs to be running 24 hours a day, 7 days a week. It works OK if I use an Office 365 user account that has MFA disabled and I use its username and password, but it stops working if MFA is enabled and I use an App Password.
This is the procedure I use in using an App password:
1) MFA is enabled on the Office 365 user account.
2) Create an App Password for the user account.
3) Run the credentials script to create the username and password encrypted text files:
#################################################################
$Location = ".\"
$securecred = Get-Credential
$securecred.UserName | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | set-content $Location"Username.txt"
$securecred.Password | ConvertFrom-SecureString | set-content $Location"Password.txt"
#################################################################
4) Run the main script that uses the credentials txt files:
#################################################################
# additional variable and setup code above...
$username = Get-Content $PassLocation"Username.txt" | ConvertTo-SecureString
$BSTRU = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($username)
$username = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTRU)
$AdminUserName = $username
$SecurePassword = Get-Content $PassLocation"Password.txt" | ConvertTo-SecureString
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminUserName, $SecurePassword
$AdminSiteURL = "https://mySubscription.sharepoint.com/sites/Demo/"
Connect-PnPOnline -Url $AdminSiteURL -Credentials $Cred
# additional variable and setup code below...
#################################################################
5) Error messages when using username with App password credentials:
---------------------------------
50126: Error validating credentials due to invalid username or password.
Trace ID: 94e...248618f34a00
Correlation ID: 7c7df2...80dcac538d78
Timestamp: 2021-03-21 14:09:59Z
Error Connecting: AADSTS50126: Error validating credentials due to invalid username or password.
Trace ID: 40337fb4...513e9474900
Correlation ID: 04bb5...cb733d5110f6
Timestamp: 2021-03-21 14:10:00Z
Error Connecting: AADSTS50126: Error validating credentials due to invalid username or password.
Trace ID: 589e2968cc3c...f5d1c4700
---------------------------------
I know the main script is OK because it works perfectly when I disable MFA and create the credential text files using the user account username and password.
Is using a username and App Password the best and secure way to run a PowerShell script that needs to run constantly?
I hope you can help
Colin
Mar 21 2021 10:10 AM
Mar 21 2021 10:11 AM