How to pass O365 credentials automatically and securely for scheduled tasks
With everything we can do in any O365 Admin Portal possible to do, even easier and better, in PowerShell, I have tried to create scripts to automate as much of my tasks as possible. When I run these manually its fine, I enter my credentials and approve my MFA popup on Authenticator App.
But what about scripts I want to run regularly, or automatically based on another event happening? Well, basically we need a few things. The first is to have an O365 Admin account, with only the bare minimum role we need, created and NOT enabled for MFA. This is a risk of course but if it can be restricted and controlled (think Conditional Access here) within your environment then this will be more of a benefit than it is a risk.
Once we create this account, we now need to securely save the credentials somewhere so they can be used in an automated/scheduled task.
Storing credentials securely
Step 1: Store your credentials in a variable - for this session only
$credential = Get-Credential
Step 2: Test connectivity using the variable passing
Connect-MsolService -Credential $credential
This should connect with no prompt for MFA:
Step 3: Save the credentials in a secured format in a text
file
Now we use the following command:
$credential.Password | ConvertFrom-SecureString | Out-File C:\Credentials\customera.creds
This command saves the credentials securely into a defined folder and file (the .creds extension is not a mandatory one but helps to define what's happening). The saved file will look similar to the following (clipped).
At this point you should note that the ConvertFrom-SecureString cmdlet encrypts the password using the Windows Data Protection API. Only the user who encrypted the password can decrypt it, also they can only do so on the same computer that it was encrypted on first. The file is useless to anyone else or on any other computer.
Now on your same server, you need to store the PowerShell script you are going to use in your connection. In your PowerShell script you need to use the following lines, #Description above each line to explain:
# Define a variable with your O365 Admin account you are going to use
$username = "Martin.Gibney@domain.ie"
# Define a variable with the Get-Content pointing to the location of the securely saved credentials we showed earlier
$pwdTxt = Get-Content
"C:\Credentials\customera.creds"
# Now we convert this file to a secure string so it can be used when being passed to the server
$securePwd = $pwdTxt | ConvertTo-SecureString
# Here we join both username and password as the credential we are going to pass as a single variable
$credObject = New-Object
System.Management.Automation.PSCredential -ArgumentList $username, $securePwd
# Finally we simply pass the credentials (Including the login name and password) to the connection command
Connect-MicrosoftTeams -Credential $credobject
Comments
Post a Comment