In this article, we will show you how to manage a Microsoft 365 user mailbox…
Configure Certificate Based Authentication to run automated PowerShell scripts
Sometimes you want to run an automated Exchange Online PowerShell script without inserting credentials or getting MFA prompts. What is a safe and excellent way to do that? In this article, you will learn how to configure Certificate Based Authentication (CBA) to run automated PowerShell scripts.
Table of contents
Certificate Based Authentication
In the old days, you used to save user credentials in an encrypted file or use basic authentication to run automated scripts in Exchange Online PowerShell. From September 2022 Basic Authentication is depreciated in Exchange Online and can’t be used anymore.
Certificate Based Authentication is a new cryptographic method that allows one to automate Exchange Online PowerShell sessions securely. It is a safe method that avoids the need to provide user credentials each time you run a PowerShell script. It supports unattended scripts and automated sessions using Exchange Online. There is also no need for usernames, passwords, and MFA when authenticating.
How Certificate Based Authentication works
The Exchange Online PowerShell module uses the Active Directory Authentication Library to fetch an app-only token using three parameters:
- Application Id
- Tenant Id (organization)
- Certificate thumbprint
The application you create in Azure AD has a Directory Role assigned to it, which is returned in the access token. Exchange Online configures the session role based access control (RBAC) using the directory role information available in the token.
How to configure Certificate Based Authentication in Exchange Online
We will guide you through the steps to implement Exchange Online Certificate Based Authentication for unattended scripts.
Step 1. Create self-signed certificate
First, you need to generate a self-signed certificate. It’s better to make the certificate on the same machine you want to run the unattended PowerShell script.
Log into any Windows Server or Desktop with Windows PowerShell as administrator.
Note: Self-signed certificate is valid for one year by default.
In our case, we will add 4 years to the self-signed certificate to avoid yearly renewal.
Use the below PowerShell cmdlet to create a certificate.
$mycert = New-SelfSignedCertificate -DnsName "exoip.com" -CertStoreLocation "cert:\LocalMachine\My" -NotAfter (Get-Date).AddYears(4) -KeySpec KeyExchange -FriendlyName "EXO automated scripts"
The certificate is now stored. To view the thumbprint, use the below cmdlet.
$mycert | Select-Object -Property Subject,Thumbprint,NotBefore,NotAfter
Copy the Thumbprint and paste it into Notepad. You will need it later when you connect to Exchange Online PowerShell with CBA.
PS C:\> $mycert | Select-Object -Property Subject,Thumbprint,NotBefore,NotAfter
Subject Thumbprint NotBefore NotAfter
------- ---------- --------- --------
CN=exoip.com 71E8CD2932E252ED4C70A731795D595715905460 07/02/2023 13.04.09 07/02/2027 13.14.09
We want to create a .cer file to upload it later in Azure AD application. With a .cer file you can only connect to Exchange Online from the machine where the self-signed certificate is generated.
Create a folder named temp to save it in the C:\temp.
Use the below PowerShell cmdlet to export the certificate to .cer file.
$mycert | Export-Certificate -FilePath "C:\temp\EXOAutomatedScripts.cer"
See the below output in PowerShell.
PS C:\> $mycert | Export-Certificate -FilePath "C:\temp\EXOAutomatedScripts.cer"
Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 07/02/2023 13.31 796 EXOAutomatedScripts.cer
You can find the .cer file on your computer in C:\temp
We will also create a .pfx file so that you can connect to Exchange Online from any machine. You can copy or send a .pfx file to a person so that when installed on another machine, it can be retrieved during the authentication process.
Export the certificate to .pfx file by using the PowerShell cmdlet.
$mycert | Export-PfxCertificate -FilePath "C:\temp\EXOAutomatedScripts.pfx" -Password $(ConvertTo-SecureString -String "P@ssw0Rd1234" -AsPlainText -Force)
This is how the below output looks in PowerShell.
PS C:\> $mycert | Export-PfxCertificate -FilePath "C:\temp\EXOAutomatedScripts.pfx" -Password $(ConvertTo-SecureString -String "P@ssw0Rd1234" -AsPlainText -Force)
Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 07/02/2023 13.33 2685 EXOAutomatedScripts.pfx
You can find the .pfx file on your computer in C:\temp
Step 2. Create new app registration in Azure AD
Follow the steps to register a new application in Azure AD:
- Sign in to Microsoft Azure
- Click Menu > Azure Active Directory
- Click on App registrations
- Click New registration
- Name your application EXO PowerShell automated
- Select Accounts in this organizational directory only – (Single tenant)
- Click Register
You will get a notification stating Successfully created application, and it will show the EXO PowerShell automated overview.
- Copy the Application (client) ID and paste it into Notepad, as we will use it when connecting to Exchange Online
Step 3. Set up Azure app API permissions
You must assign API permissions to the EXO PowerShell automated application you created. To configure API permissions, we will use a script and edit the manifest properties.
From the EXO PowerShell automated overview:
- Click on Manifest
- Scroll down in the editor to line 42, “requiredResourceAccess”
- Select the script from line 43 to 52
- Copy the below PowerShell syntax
{
"resourceAppId": "00000002-0000-0ff1-ce00-000000000000",
"resourceAccess": [
{
"id": "dc50a0fb-09a3-484d-be87-e023b12c6440",
"type": "Role"
}
]
}
],
- Paste the PowerShell syntax in the manifest
- Click Save
You will get a notification stating Successfully updated application manifest.
- Click API permission
- Click Grant admin consent for exoip365
- Click Yes
A green check mark appears that you granted admin consent successfully!
Step 4. Upload certificate to application
Now we need to upload the self-signed certificate you created earlier.
From the EXO PowerShell automated overview:
- Click Certificates & secrets
- Select Certificates
- Click Upload certificate
- Click on the browse icon to search in C:\temp and select the EXOAutomatedScripts.cer file
- Add description EXO Automated Scripts
- Click Add
The certificate appears in the list.
Note: Always ensure it has the same certificate thumbprint as the one you created previously.
Step 5. Assign required Azure AD roles to application
The last step for the configuration is the RBAC roles with the required permissions for the registered application.
- Click on Menu > Azure Active Directory
- Select Roles and administrators
- Select All roles
- Search for exchange
- Click on Exchange Administrator
- Click on Assignments
- Click Add assignments
- Search for the Azure application name EXO PowerShell automated
- Select the application from the results
- Click Add
The Azure assignment name EXO PowerShell automated is added successfully to the Exchange Administrator role assignments list.
Connect to Exchange Online PowerShell with Certificate Based Authentication
Note: You have to install Exchange Online PowerShell module before you proceed further.
We will use Certificate Based Authentication (CBA) to connect to EXO PowerShell. You need to get the values from the Microsoft Azure portal and add these values to the following variables:
- $AppId
- $CertificateThumbPrint
- $Organization
In the previous steps, we showed how to get the $AppId and $CertificateThumbprint values. Now we will find the organization name in Azure Active Directory and add the value to the $Organization variable.
- Click Custom domain names from the menu
- Find it in the domain list
Once you have found all the values, fill in the below three variables to connect to Exchange Online PowerShell with Certificate Based Authentication:
$AppId = "89e1d6c0-5105-41a0-b741-894b2331ca07"
$CertificateThumbprint = "71E8CD2932E252ED4C70A731795D595715905460"
$Organization = "exoip365.onmicrosoft.com"
Connect-ExchangeOnline -AppId $AppId -CertificateThumbprint $CertificateThumbprint -Organization $Organization -ShowBanner:$false
An excellent way to check that you are connected successfully is to run the Get-EXOMailbox cmdlet to view the mailboxes.
PS C:\> Get-EXOMailbox -ResultSize 5 | ft Name,UserPrincipalName
Name UserPrincipalName
---- -----------------
Zoe Howard Zoe.Howard@exoip.com
Amanda Morgan Amanda.Morgan@exoip.com
Amelia Nash Amelia.Nash@exoip.com
Stephen Hunter Stephen.Hunter@exoip.com
Carol Baker Carol.Baker@exoip.com
Run PowerShell automated script with CBA
Use the below automated PowerShell script that will export the list of mailboxes in Exchange Online to a CSV file in C:\temp. This script is added to a scheduled task that will run every day.
Note: Add Disconnect-ExchangeOnline -Confirm:$false at the end of the PowerShell script. If the script runs without disconnecting the session, you could use up all the remote PowerShell sessions available, and you’ll need to wait for the sessions to expire.
# Connect Exchange Online PowerShell
$AppId = "89e1d6c0-5105-41a0-b741-894b2331ca07"
$CertificateThumbprint = "71E8CD2932E252ED4C70A731795D595715905460"
$Organization = "exoip365.onmicrosoft.com"
Connect-ExchangeOnline -AppId $AppId -CertificateThumbprint $CertificateThumbprint -Organization $Organization -ShowBanner:$false
# Split path
$Path = Split-Path -Parent "C:\temp\*.*"
# Create variable for the date stamp
$LogDate = Get-Date -f yyyyMMddhhmm
# Define CSV and log file location variables
$Csvfile = $Path + "\AllMailboxes_$logDate.csv"
Get-EXOMailbox -ResultSize Unlimited | Select-Object DisplayName, PrimarySmtpAddress | Sort-Object PrimarySmtpAddress | Export-CSV -Path $Csvfile -NoTypeInformation -Encoding UTF8
# Disconnect Exchange Online PowerShell
Disconnect-ExchangeOnline -Confirm:$false
You can successfully connect with Exchange Online Certificate Based Authentication to run automated PowerShell scripts!
Read more: Increase and improve Azure MFA »
Conclusion
You learned how to configure Certificate Based Authentication to connect to Exchange Online and run automated PowerShell scripts. There are no more user interactions, usernames, passwords, or MFA involved, which makes it much easier.
Did you enjoy this article? You may also like Bulk create shared mailboxes with PowerShell. Don’t forget to follow us and share this article.
This Post Has 0 Comments