How to Connect to Exchange Online PowerShell via v2 Module

choubertsprojects

VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

Exchange Online PowerShell is a rich and powerful module that can be used to automate your entire Exchange environment. The v2 release offers the following new capabilities:
– Connectivity with more than one SharePoint server, including cross-forest support;
– New cmdlets for migrating mailboxes and mailbox databases between on-premises Exchange servers;
– Support for native Windows PowerShell 5.0 features such as tab completion, parameterized commands, advanced formatting options, improved debugging tools, common language runtime (CLR) enhancements and multiline scripts;
and much more!

The “connect to exchange online powershell v2” is a PowerShell script that can be used to connect to Exchange Online via the v2 Module. It does not require any additional software or configuration.

How to Connect to Exchange Online PowerShell via v2 Module

You’re definitely utilizing PowerShell scripts to automate numerous Office 365 processes if you’re an administrator. It’s improbable, though, that you’re utilizing MFA to connect to Exchange Online through PowerShell for unattended scripts. This indicates that your scripts continue to use basic authentication.

On October 13, 2020, Microsoft intended to eliminate basic authentication from Exchange Online. After then, the plan was pushed back until the second half of 2021.

Admins must redesign their scripts as soon as possible, taking into account the following:

  • Modern authentication must be used in PowerShell scripts while yet allowing them to operate unattended.
  • In Office 365, PowerShell scripts must authenticate securely without the need to exclude a service account from multi-factor authentication.

Previously, current systems could not meet those two requirements. Fortunately, Microsoft has published version 2.0.3-preview of the Exchange Online V2 PowerShell module. The option to employ certificate-based authentication with an Azure AD app was included in this new version.

In this article, you’ll discover how to get ready to utilize the EXO V2 module with app-only contemporary authentication to execute Exchange Online unattended scripts. You’ll discover how to:

  • Create a new app and activate its service principal in Azure Active Directory.
  • Assign API roles and permissions.
  • Make a self-signed certificate and submit it.
  • Authenticate and connect to Exchange Online PowerShell using the app and certificate.

As a result, don’t expect to see a lot of point-and-click instructions in this post. PowerShell will be used for the majority of the walkthrough instructions.

Prerequisites

Make sure you have the following needs in order to follow along correctly.

  • With Global Admin rights, access to an Office 365 tenant. For testing, use a non-production/dev tenant. Consider up for a free Office 365 trial tenancy.
  • Windows PowerShell 5.1 on a Windows PC. This post will be written on a machine running Windows 10 version 1909.
  • The newest AzureAD PowerShell Module should be installed. This article was written using version 2.0.2.106.
  • Notepad++, Atom, Windows PowerShell ISE, or Visual Studio Code are examples of code editors. Use whatever one seems most natural to you.
  • For your test, create a functioning directory. The working directory in this article is C:exo v2 demo.
  • Save the Create-SelfSignedCertificate.ps1 script to your working directory after downloading it. The script will be saved in the working directory C:exo v2 demo in this article.

Using PowerShell to Set Up App-Only Authentication

You may be accustomed to running your PowerShell scripts using a generic account, sometimes known as a service account. In nature, such sort of account is a “shared” account. Anyone with access to that account’s credentials may log in and execute various administrative tasks on your business, which is a security risk.

App-only authentication aims to address this security issue. App-only authentication necessitates the creation of an Azure AD app with a service principal and certain permissions and roles. To authenticate, use a token or a certificate.

Adding API Permissions to an Azure AD Application

To begin, establish a new Azure AD app with the appropriate API access. To begin, launch an elevated Windows PowerShell session (run as administrator) and Connect to Azure Active Directory.

Connect to Azure Active DirectoryConnect to Azure Active Directory

The code below will create a new Exo V2 App app in Azure AD and attach it to the Exchange. The Office 365 Exchange Online API has the ManageAsApp permission.

If you want to give your app a different name, change the value of the $appName variable in the code below. Copy and execute the code in PowerShell.

# APP REGISTRATION, API PERMISSIONS, AND SERVICE PRINCIPAL ENABLEMENT CODE ## Name the client application $appName = ‘Exo V2 App’ ## Get information about the Office 365 Exchange Online API. (Get-AzureADServicePrincipal -Filter “AppID eq ‘00000002-0000-0ff1-ce00-000000000000’) $api = (Get-AzureADServicePrincipal -Filter “AppID ## Determine the API permission ID. Where-Object

You’re definitely utilizing PowerShell scripts to automate numerous Office 365 processes if you’re an administrator. It’s improbable, though, that you’re utilizing MFA to connect to Exchange Online through PowerShell for unattended scripts. This indicates that your scripts continue to use basic authentication.

On October 13, 2020, Microsoft intended to eliminate basic authentication from Exchange Online. After then, the plan was pushed back until the second half of 2021.

Admins must redesign their scripts as soon as possible, taking into account the following:

  • Modern authentication must be used in PowerShell scripts while yet allowing them to operate unattended.
  • In Office 365, PowerShell scripts must authenticate securely without the need to exclude a service account from multi-factor authentication.

Previously, current systems could not meet those two requirements. Fortunately, Microsoft has published version 2.0.3-preview of the Exchange Online V2 PowerShell module. The option to employ certificate-based authentication with an Azure AD app was included in this new version.

In this article, you’ll discover how to get ready to utilize the EXO V2 module with app-only contemporary authentication to execute Exchange Online unattended scripts. You’ll discover how to:

  • Create a new app and activate its service principal in Azure Active Directory.
  • Assign API roles and permissions.
  • Make a self-signed certificate and submit it.
  • Authenticate and connect to Exchange Online PowerShell using the app and certificate.

As a result, don’t expect to see a lot of point-and-click instructions in this post. PowerShell will be used for the majority of the walkthrough instructions.

Prerequisites

Make sure you have the following needs in order to follow along correctly.

  • With Global Admin rights, access to an Office 365 tenant. For testing, use a non-production/dev tenant. Consider up for a free Office 365 trial tenancy.
  • Windows PowerShell 5.1 on a Windows PC. This post will be written on a machine running Windows 10 version 1909.
  • The newest AzureAD PowerShell Module should be installed. This article was written using version 2.0.2.106.
  • Notepad++, Atom, Windows PowerShell ISE, or Visual Studio Code are examples of code editors. Use whatever one seems most natural to you.
  • For your test, create a functioning directory. The working directory in this article is C:exo v2 demo.
  • Save the Create-SelfSignedCertificate.ps1 script to your working directory after downloading it. The script will be saved in the working directory C:exo v2 demo in this article.

Using PowerShell to Set Up App-Only Authentication

You may be accustomed to running your PowerShell scripts using a generic account, sometimes known as a service account. In nature, such sort of account is a “shared” account. Anyone with access to that account’s credentials may log in and execute various administrative tasks on your business, which is a security risk.

App-only authentication aims to address this security issue. App-only authentication necessitates the creation of an Azure AD app with a service principal and certain permissions and roles. To authenticate, use a token or a certificate.

Adding API Permissions to an Azure AD Application

To begin, establish a new Azure AD app with the appropriate API access. To begin, launch an elevated Windows PowerShell session (run as administrator) and Connect to Azure Active Directory.

Connect to Azure Active DirectoryConnect to Azure Active Directory

The code below will create a new Exo V2 App app in Azure AD and attach it to the Exchange. The Office 365 Exchange Online API has the ManageAsApp permission.

If you want to give your app a different name, change the value of the $appName variable in the code below. Copy and execute the code in PowerShell.

# CODE TO REGISTER APP, ASSIGN API PERMISSIONS, AND ENABLE SERVICE PRINCIPAL ## Define the client app name $appName = ‘Exo_V2_App’ ## Get the Office 365 Exchange Online API details. $api = (Get-AzureADServicePrincipal -Filter “AppID eq ‘00000002-0000-0ff1-ce00-000000000000′”) ## Get the API permission ID $permission = $api.AppRoles | Where-Object { $_.Value -eq ‘Exchange.ManageAsApp’ } ## Build the API permission object (TYPE: Role = Application, Scope = User) $apiPermission = [Microsoft.Open.AzureAD.Model.RequiredResourceAccess]@{ ResourceAppId = $api.AppId ; ResourceAccess = [Microsoft.Open.AzureAD.Model.ResourceAccess]@{ Id = $permission.Id ; Type = “Role” } } ## Register the new Azure AD App with API Permissions $myApp = New-AzureADApplication -DisplayName $appName -ReplyUrls ‘http://localhost’ -RequiredResourceAccess $apiPermission ## Enable the Service Principal $mySP = New-AzureADServicePrincipal -AppID $myApp.AppID ## Display the new app properties $myApp | Format-List DisplayName,ObjectID,AppID

The code is shown in the video below. The DisplayName, ObjectID, and AppID attributes of the new app will be presented at the end. These attributes are saved in the $myApp variable. The service principal’s property values are stored in the $mySP variable.

Create a new Azure Active Directory app.Create a new Azure Active Directory app.

TIP: Save the attributes of the application for future reference.

Use the command below to export the application’s property values.

“$($appName).csv” $myApp | Export-Csv -NoTypeInformation

Adding an Azure Active Directory Role to the Application

The next step is to assign an Azure AD role to the app’s service principal once it has been created. You’ll need to select what kind of role your app should have.

These are the legitimate supported roles for Exchange Online V2.

  • Company administrator
  • Compliance administrator
  • Security reader
  • Security administrator
  • Helpdesk administrator
  • Exchange Service Administrator
  • Global Reader

Only grant the least privileged role to your script that you believe is suitable. The code below assigns the Exchange Service administrator role to the app’s service principal in this case.

## The app’s role to be assigned ## Find the ObjectID of ‘Exchange Service Administrator’ using $directoryRole = ‘Exchange Service Administrator’. (Get-AzureADDirectoryRole | Where-Object

You’re definitely utilizing PowerShell scripts to automate numerous Office 365 processes if you’re an administrator. It’s improbable, though, that you’re utilizing MFA to connect to Exchange Online through PowerShell for unattended scripts. This indicates that your scripts continue to use basic authentication.

On October 13, 2020, Microsoft intended to eliminate basic authentication from Exchange Online. After then, the plan was pushed back until the second half of 2021.

Admins must redesign their scripts as soon as possible, taking into account the following:

  • Modern authentication must be used in PowerShell scripts while yet allowing them to operate unattended.
  • In Office 365, PowerShell scripts must authenticate securely without the need to exclude a service account from multi-factor authentication.

Previously, current systems could not meet those two requirements. Fortunately, Microsoft has published version 2.0.3-preview of the Exchange Online V2 PowerShell module. The option to employ certificate-based authentication with an Azure AD app was included in this new version.

In this article, you’ll discover how to get ready to utilize the EXO V2 module with app-only contemporary authentication to execute Exchange Online unattended scripts. You’ll discover how to:

  • Create a new app and activate its service principal in Azure Active Directory.
  • Assign API roles and permissions.
  • Make a self-signed certificate and submit it.
  • Authenticate and connect to Exchange Online PowerShell using the app and certificate.

As a result, don’t expect to see a lot of point-and-click instructions in this post. PowerShell will be used for the majority of the walkthrough instructions.

Prerequisites

Make sure you have the following needs in order to follow along correctly.

  • With Global Admin rights, access to an Office 365 tenant. For testing, use a non-production/dev tenant. Consider up for a free Office 365 trial tenancy.
  • Windows PowerShell 5.1 on a Windows PC. This post will be written on a machine running Windows 10 version 1909.
  • The newest AzureAD PowerShell Module should be installed. This article was written using version 2.0.2.106.
  • Notepad++, Atom, Windows PowerShell ISE, or Visual Studio Code are examples of code editors. Use whatever one seems most natural to you.
  • For your test, create a functioning directory. The working directory in this article is C:exo v2 demo.
  • Save the Create-SelfSignedCertificate.ps1 script to your working directory after downloading it. The script will be saved in the working directory C:exo v2 demo in this article.

Using PowerShell to Set Up App-Only Authentication

You may be accustomed to running your PowerShell scripts using a generic account, sometimes known as a service account. In nature, such sort of account is a “shared” account. Anyone with access to that account’s credentials may log in and execute various administrative tasks on your business, which is a security risk.

App-only authentication aims to address this security issue. App-only authentication necessitates the creation of an Azure AD app with a service principal and certain permissions and roles. To authenticate, use a token or a certificate.

Adding API Permissions to an Azure AD Application

To begin, establish a new Azure AD app with the appropriate API access. To begin, launch an elevated Windows PowerShell session (run as administrator) and Connect to Azure Active Directory.

Connect to Azure Active DirectoryConnect to Azure Active Directory

The code below will create a new Exo V2 App app in Azure AD and attach it to the Exchange. The Office 365 Exchange Online API has the ManageAsApp permission.

If you want to give your app a different name, change the value of the $appName variable in the code below. Copy and execute the code in PowerShell.

# APP REGISTRATION, API PERMISSIONS, AND SERVICE PRINCIPAL ENABLEMENT CODE ## Name the client application $appName = ‘Exo V2 App’ ## Get information about the Office 365 Exchange Online API. (Get-AzureADServicePrincipal -Filter “AppID eq ‘00000002-0000-0ff1-ce00-000000000000’) $api = (Get-AzureADServicePrincipal -Filter “AppID ## Determine the API permission ID. Where-Object

You’re definitely utilizing PowerShell scripts to automate numerous Office 365 processes if you’re an administrator. It’s improbable, though, that you’re utilizing MFA to connect to Exchange Online through PowerShell for unattended scripts. This indicates that your scripts continue to use basic authentication.

On October 13, 2020, Microsoft intended to eliminate basic authentication from Exchange Online. After then, the plan was pushed back until the second half of 2021.

Admins must redesign their scripts as soon as possible, taking into account the following:

  • Modern authentication must be used in PowerShell scripts while yet allowing them to operate unattended.
  • In Office 365, PowerShell scripts must authenticate securely without the need to exclude a service account from multi-factor authentication.

Previously, current systems could not meet those two requirements. Fortunately, Microsoft has published version 2.0.3-preview of the Exchange Online V2 PowerShell module. The option to employ certificate-based authentication with an Azure AD app was included in this new version.

In this article, you’ll discover how to get ready to utilize the EXO V2 module with app-only contemporary authentication to execute Exchange Online unattended scripts. You’ll discover how to:

  • Create a new app and activate its service principal in Azure Active Directory.
  • Assign API roles and permissions.
  • Make a self-signed certificate and submit it.
  • Authenticate and connect to Exchange Online PowerShell using the app and certificate.

As a result, don’t expect to see a lot of point-and-click instructions in this post. PowerShell will be used for the majority of the walkthrough instructions.

Prerequisites

Make sure you have the following needs in order to follow along correctly.

  • With Global Admin rights, access to an Office 365 tenant. For testing, use a non-production/dev tenant. Consider up for a free Office 365 trial tenancy.
  • Windows PowerShell 5.1 on a Windows PC. This post will be written on a machine running Windows 10 version 1909.
  • The newest AzureAD PowerShell Module should be installed. This article was written using version 2.0.2.106.
  • Notepad++, Atom, Windows PowerShell ISE, or Visual Studio Code are examples of code editors. Use whatever one seems most natural to you.
  • For your test, create a functioning directory. The working directory in this article is C:exo v2 demo.
  • Save the Create-SelfSignedCertificate.ps1 script to your working directory after downloading it. The script will be saved in the working directory C:exo v2 demo in this article.

Using PowerShell to Set Up App-Only Authentication

You may be accustomed to running your PowerShell scripts using a generic account, sometimes known as a service account. In nature, such sort of account is a “shared” account. Anyone with access to that account’s credentials may log in and execute various administrative tasks on your business, which is a security risk.

App-only authentication aims to address this security issue. App-only authentication necessitates the creation of an Azure AD app with a service principal and certain permissions and roles. To authenticate, use a token or a certificate.

Adding API Permissions to an Azure AD Application

To begin, establish a new Azure AD app with the appropriate API access. To begin, launch an elevated Windows PowerShell session (run as administrator) and Connect to Azure Active Directory.

Connect to Azure Active DirectoryConnect to Azure Active Directory

The code below will create a new Exo V2 App app in Azure AD and attach it to the Exchange. The Office 365 Exchange Online API has the ManageAsApp permission.

If you want to give your app a different name, change the value of the $appName variable in the code below. Copy and execute the code in PowerShell.

# CODE TO REGISTER APP, ASSIGN API PERMISSIONS, AND ENABLE SERVICE PRINCIPAL ## Define the client app name $appName = ‘Exo_V2_App’ ## Get the Office 365 Exchange Online API details. $api = (Get-AzureADServicePrincipal -Filter “AppID eq ‘00000002-0000-0ff1-ce00-000000000000′”) ## Get the API permission ID $permission = $api.AppRoles | Where-Object { $_.Value -eq ‘Exchange.ManageAsApp’ } ## Build the API permission object (TYPE: Role = Application, Scope = User) $apiPermission = [Microsoft.Open.AzureAD.Model.RequiredResourceAccess]@{ ResourceAppId = $api.AppId ; ResourceAccess = [Microsoft.Open.AzureAD.Model.ResourceAccess]@{ Id = $permission.Id ; Type = “Role” } } ## Register the new Azure AD App with API Permissions $myApp = New-AzureADApplication -DisplayName $appName -ReplyUrls ‘http://localhost’ -RequiredResourceAccess $apiPermission ## Enable the Service Principal $mySP = New-AzureADServicePrincipal -AppID $myApp.AppID ## Display the new app properties $myApp | Format-List DisplayName,ObjectID,AppID

The code is shown in the video below. The DisplayName, ObjectID, and AppID attributes of the new app will be presented at the end. These attributes are saved in the $myApp variable. The service principal’s property values are stored in the $mySP variable.

Create a new Azure Active Directory app.Create a new Azure Active Directory app.

TIP: Save the attributes of the application for future reference.

Use the command below to export the application’s property values.

“$($appName).csv” $myApp | Export-Csv -NoTypeInformation

Adding an Azure Active Directory Role to the Application

The next step is to assign an Azure AD role to the app’s service principal once it has been created. You’ll need to select what kind of role your app should have.

These are the legitimate supported roles for Exchange Online V2.

  • Company administrator
  • Compliance administrator
  • Security reader
  • Security administrator
  • Helpdesk administrator
  • Exchange Service Administrator
  • Global Reader

Only grant the least privileged role to your script that you believe is suitable. The code below assigns the Exchange Service administrator role to the app’s service principal in this case.

## The role to assign to your app $directoryRole = ‘Exchange Service Administrator’ ## Find the ObjectID of ‘Exchange Service Administrator’ $RoleId = (Get-AzureADDirectoryRole | Where-Object {$_.displayname -eq $directoryRole}).ObjectID ## Add the service principal to the directory role Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose

You should get a result similar to the one displayed in the example below if you execute the command above in PowerShell.

Giving the app an Azure Active Directory roleGiving the app an Azure Active Directory role

Making a self-signed certificate and attaching it to the application

The next step is to create a self-signed certificate and add it to your program. This step will need the Create-SelfSignedCertificate.ps1 script.

The script below will create a self-signed certificate with the subject name of your app, such as Exo V2 App. The certificate is only good for one year.

Update the $certYears value to the desired number of years if you wish to change the certificate’s validity. If you wish to use a different password for the generated certificate (PFX) file, you may alter the $certPassword value.

## Validity of the certificate in years 1 $certYears ## Password for the Certificate (PFX) ‘4mt4G*[email protected]’ is the certificate password. Create-SelfSignedCertificate. -CommonName ps1 $appName ‘ -BeginDate (Get-Date). AddDays(-1) ‘ -FinishDate (Get-Date). AddYears($certYears) ‘ -Force (ConvertTo-SecureString $certPassword -AsPlainText)’-Password (ConvertTo-SecureString $certPassword -AsPlainText

Two files will be produced when you execute the code above in PowerShell, as seen in the sample below.

Create a certificate that is self-signed.Create a certificate that is self-signed.

The next step is to submit your newly generated certificate to your Azure AD app. The code below will find and attach the certificate (.CER) file in your working directory to the Azure AD app. You don’t need to change the code; just copy and execute it in PowerShell.

## Download the certificate (.CER) (Resolve-Path “.$($appName).cer”) $CertificateFilePath Path ## Make a certificate object. $cer = System.Security.Cryptography.X509Certificates.X509Certificate2 New-Object $cer $cer.Import(“$($CertificateFilePath)”) $cer.GetRawCertData $bin () $bin = $cer.GetCertHash $base64Value = [System.Convert]::ToBase64String($bin) () $bin = [System.Convert]::ToBase64String($base64Thumbprint) ## In AzureAD, upload and assign the certificate to the application. -ObjectId $null = New-AzureADApplicationKeyCredential -CustomKeyIdentifier $myApp.ObjectID ‘ -Type AsymmetricX509Cert -Usage Verify’-Value $base64Thumbprint ‘ -StartDate ($cer.NotBefore)’-EndDate ($cer.NotAfter)’$base64Value

If the code above is executed in PowerShell, no output should be expected until an error occurs. When the code is successfully executed, the outcome is shown in the example below.

Adding the certificate to the Azure Active Directory appAdding the certificate to the Azure Active Directory app

Approval of the Application by the Admin

You’re almost finished with your setup. The next step is for a Global Admin to give your Azure AD app permission. This step may be carried out by you or another Global Admin in your company.

From the Azure Active Directory admin center, a Global admin may provide consent. However, PowerShell can also build a consent URL. You may either provide it to the Global admin or use it to grant consent yourself.

This is the format for the consent URL.

https://login.microsoftonline.com/{TenantID}/adminconsent?client id={ApplicationID}

The TenantID value is your Office 365 tenant’s directory ID or confirmed domain. The AppID of the Azure AD application that you previously generated is the value for ApplicationID.

Based on the variables supplied, the code below will construct the consent URL. The consent URL will then be shown on the screen and opened in the default browser on the machine.

## Obtain TenantID $tenantID = $tenantID (Get-AzureADTenantDetail). ObjectID ## Visit this link “https://login.microsoftonline.com/$tenantID/adminconsent?client id=$($myApp.AppId)” $consentURL = “https://login.microsoftonline.com/$tenantID/adminconsent ## Make the consent URL visible. $consentURL ## Use the default browser to access the consent URL. $consentURL -Start-Process

To see what occurs when you execute the code above in PowerShell, look at the example below.

Create a consent URL and provide permission.Create a consent URL and provide permission.

PowerShell Connection to Exchange Online

You must now upload and attach the certificate after establishing the app and giving permissions and roles. You may now use the app’s certificate credentials to login to Exchange Online PowerShell.

The local certificate file (.pfx) and the thumbprint of the certificate put in the current user’s personal certificate store are the two methods to use the certificate credentials.

Using a Local PFX Certificate for Authentication

You’ll need the following information to connect to Exchange Online PowerShell using a local certificate for authentication:

  • Your Azure AD tenant’s Directory ID or confirmed domain.
  • The AppID of the application you already registered.
  • The self-signed PFX certificate’s complete file path.
  • The seld-sign PFX certificate’s password.

Then, in the code below, alter the values of the $tenantID, $appID, $CertificateFilePath, and $pfxPassword variables. Copy the code and execute it in PowerShell after you’ve changed the values of the variables as appropriate.

## Create a tenant ID (directory ID or domain) ‘poshlab.ga’ as $tenantID $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450f (.pfx) ## Get the PFX password using $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’. ‘4mt4G*[email protected]’ as $pfxPassword Connect-ExchangeOnline -CertificateFilePath ## Connect to Exchange Online -CertificatePassword (ConvertTo-SecureString -String $pfxPassword -AsPlainText -Force)’-AppID $CertificateFilePath -Organization $appID $tenantID

The demo below shows that the PowerShell Connection to Exchange Online si successful using the local certificate file authentication.

Using a Local PFX Certificate for AuthenticationUsing a Local PFX Certificate for Authentication

When you examine the code again, you’ll see that the pfx certificate password is visible. For increased protection, you may consider storing the certificate credential in a secret management system.

Using the Certificate Thumbprint for Authentication

This way of authentication is more secure than using a password and a local certificate. You must import the certificate into the Personal certificate store using this approach. Only the thumbprint is required to determine which certificate to use for authentication.

The PFX certificate must first be imported into the Personal certificate repository. This step only has to be done once for the current user.

IMPORT THE PFX CERTIFICATE INTO THE CURRENT PERSONAL CERTIFICATE STORE WITH THIS CODE. ## Get the PFX password $mypwd = Get-Credential -UserName ‘Enter password below’ -Message ‘Enter password below’ ## Set the certificate file path (.pfx) $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’ ## Import the PFX certificate into the personal certificate store of the current user. -CertStoreLocation Cert:CurrentUserMy -Password Import-PfxCertificate -FilePath $CertificateFilePath $mypwd.Password

The demonstration below demonstrates how to import a PFX certificate into your own certificate store.

The PFX certificate is imported.The PFX certificate is imported.

The outcome of the PFX import procedure will be seen as shown above. Make a note of the value of the Thumbprint for future reference.

Your scripts may now use the thumbprint of the certificate to authenticate with Exchange Online PowerShell.

To match your right values, edit the $tenantID, $appID, and $CertificateThumbPrint in the code below. Then, in PowerShell, copy and execute the code.

## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID

If you run the code above in PowerShell, you’ll get something like the example below.

After executing the code in Powershell, this is the output.After executing the code in Powershell, this is the output.

Using App-Only Authentication to Connect and Run Exchange Online PowerShell Scripts

You’ve just been copying and pasting code into PowerShell so far in this tutorial. You should use app-only authentication to execute your PowerShell scripts now that you understand how it works.

The script below connects to Exchange Online PowerShell and authenticates using the certificate thumbprint. The script will then obtain all of the mailboxes accessible once connected. C:exo v2 demoListExoMailbox.ps1 is where the script is stored.

## Clean up Exchange Online Session Get-PSSession | Where-Object {$_.name -like “ExchangeOnline*”} | Remove-PSSession -ErrorAction SilentlyContinue ## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID ## Get All Mailbox Write-Output “Getting all mailboxes” Get-Mailbox -ResultSize Unlimited | Format-Table Name,DisplayName

Run the script in PowerShell once you’ve saved it. The script should automatically connect to Exchange Online and do its purpose. Refer to the findings in the demonstration below.

App-Only Authentication PowerShell ScriptApp-Only Authentication PowerShell Script

Summary

The EXO V2 PowerShell module’s release is a great development. Knowing that Microsoft has opted to remove basic authentication for connecting to Exchange Online through PowerShell, administrators may update their current scripts with this new app-only authentication option.

Implementing EXO V2 app-only authentication, on the other hand, is not without its difficulties.

  • A PFX password is still required when using a local certificate file. You should be able to avoid this password vulnerability problem if you use a credential or secret management approach.
  • In the personal shop, using a certificate gives you extra assurance. However, only the current user has access to the certificate. If you’ve set up a scheduled job to execute the script using UserA’s credentials, the certificate must be imported into UserA’s personal certificate store.
  • Certificates have a time limit. This would need certificate monitoring, renewal, and re-assignment to the Azure AD app. Otherwise, owing to an authentication failure, the script will cease operating.

These disadvantages are outweighed by the advantages of utilizing the new EXO V2 PowerShell module.

In this post, you learnt how to set up app-only authentication for the Exchange Online V2 PowerShell module step by step. You’ve also learned how to use a self-signed certificate to login to Exchange Online PowerShell.

You may now employ app-only certificate-based authentication in your scripts instead of dealing with Exchange Online PowerShell MFA prompts.

If you want to take things a step further, you might use Jenkins or Azure Automation to put everything you’ve learned in this article to the test. Alternatively, you may create your own PowerShell functions and modules.

Thank you for stopping by!

Additional Reading

.Value -eq ‘Exchange.ManageAsApp’ | $permission = $api.AppRoles ## Create the API authorization object (TYPE: Application, Scope: User) [Microsoft.Open.AzureAD.Model] $apiPermission .RequiredResourceAccess] @ ResourceAccess = [Microsoft.Open.AzureAD.Model]; ResourceAppId = $api.AppId .ResourceAccess] @ Type = “Role”; Id = $permission.Id ## Grant API Permissions to the new Azure AD App New-AzureADApplication -DisplayName $myApp ‘http://localhost’ -RequiredResourceAccess $appName -ReplyUrls $apiPermission ## Make the Service Principal active. New-AzureADServicePrincipal -AppID $mySP $myApp.AppID ## Format-List DisplayName,ObjectID,AppID to show the new app properties $myApp

The code is shown in the video below. The DisplayName, ObjectID, and AppID attributes of the new app will be presented at the end. These attributes are saved in the $myApp variable. The service principal’s property values are stored in the $mySP variable.

Create a new Azure Active Directory app.Create a new Azure Active Directory app.

TIP: Save the attributes of the application for future reference.

Use the command below to export the application’s property values.

“$($appName).csv” $myApp | Export-Csv -NoTypeInformation

Adding an Azure Active Directory Role to the Application

The next step is to assign an Azure AD role to the app’s service principal once it has been created. You’ll need to select what kind of role your app should have.

These are the legitimate supported roles for Exchange Online V2.

  • Company administrator
  • Compliance administrator
  • Security reader
  • Security administrator
  • Helpdesk administrator
  • Exchange Service Administrator
  • Global Reader

Only grant the least privileged role to your script that you believe is suitable. The code below assigns the Exchange Service administrator role to the app’s service principal in this case.

## The role to assign to your app $directoryRole = ‘Exchange Service Administrator’ ## Find the ObjectID of ‘Exchange Service Administrator’ $RoleId = (Get-AzureADDirectoryRole | Where-Object {$_.displayname -eq $directoryRole}).ObjectID ## Add the service principal to the directory role Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose

You should get a result similar to the one displayed in the example below if you execute the command above in PowerShell.

Giving the app an Azure Active Directory roleGiving the app an Azure Active Directory role

Making a self-signed certificate and attaching it to the application

The next step is to create a self-signed certificate and add it to your program. This step will need the Create-SelfSignedCertificate.ps1 script.

The script below will create a self-signed certificate with the subject name of your app, such as Exo V2 App. The certificate is only good for one year.

Update the $certYears value to the desired number of years if you wish to change the certificate’s validity. If you wish to use a different password for the generated certificate (PFX) file, you may alter the $certPassword value.

## Validity of the certificate in years 1 $certYears ## Password for the Certificate (PFX) ‘4mt4G*[email protected]’ is the certificate password. Create-SelfSignedCertificate. -CommonName ps1 $appName ‘ -BeginDate (Get-Date). AddDays(-1) ‘ -FinishDate (Get-Date). AddYears($certYears) ‘ -Force (ConvertTo-SecureString $certPassword -AsPlainText)’-Password (ConvertTo-SecureString $certPassword -AsPlainText

Two files will be produced when you execute the code above in PowerShell, as seen in the sample below.

Create a certificate that is self-signed.Create a certificate that is self-signed.

The next step is to submit your newly generated certificate to your Azure AD app. The code below will find and attach the certificate (.CER) file in your working directory to the Azure AD app. You don’t need to change the code; just copy and execute it in PowerShell.

## Download the certificate (.CER) (Resolve-Path “.$($appName).cer”) $CertificateFilePath Path ## Make a certificate object. $cer = System.Security.Cryptography.X509Certificates.X509Certificate2 New-Object $cer $cer.Import(“$($CertificateFilePath)”) $cer.GetRawCertData $bin () $bin = $cer.GetCertHash $base64Value = [System.Convert]::ToBase64String($bin) () $bin = [System.Convert]::ToBase64String($base64Thumbprint) ## In AzureAD, upload and assign the certificate to the application. -ObjectId $null = New-AzureADApplicationKeyCredential -CustomKeyIdentifier $myApp.ObjectID ‘ -Type AsymmetricX509Cert -Usage Verify’-Value $base64Thumbprint ‘ -StartDate ($cer.NotBefore)’-EndDate ($cer.NotAfter)’$base64Value

If the code above is executed in PowerShell, no output should be expected until an error occurs. When the code is successfully executed, the outcome is shown in the example below.

Adding the certificate to the Azure Active Directory appAdding the certificate to the Azure Active Directory app

Approval of the Application by the Admin

You’re almost finished with your setup. The next step is for a Global Admin to give your Azure AD app permission. This step may be carried out by you or another Global Admin in your company.

From the Azure Active Directory admin center, a Global admin may provide consent. However, PowerShell can also build a consent URL. You may either provide it to the Global admin or use it to grant consent yourself.

This is the format for the consent URL.

https://login.microsoftonline.com/{TenantID}/adminconsent?client id={ApplicationID}

The TenantID value is your Office 365 tenant’s directory ID or confirmed domain. The AppID of the Azure AD application that you previously generated is the value for ApplicationID.

Based on the variables supplied, the code below will construct the consent URL. The consent URL will then be shown on the screen and opened in the default browser on the machine.

## Obtain TenantID $tenantID = $tenantID (Get-AzureADTenantDetail). ObjectID ## Visit this link “https://login.microsoftonline.com/$tenantID/adminconsent?client id=$($myApp.AppId)” $consentURL = “https://login.microsoftonline.com/$tenantID/adminconsent ## Make the consent URL visible. $consentURL ## Use the default browser to access the consent URL. $consentURL -Start-Process

To see what occurs when you execute the code above in PowerShell, look at the example below.

Create a consent URL and provide permission.Create a consent URL and provide permission.

PowerShell Connection to Exchange Online

You must now upload and attach the certificate after establishing the app and giving permissions and roles. You may now use the app’s certificate credentials to login to Exchange Online PowerShell.

The local certificate file (.pfx) and the thumbprint of the certificate put in the current user’s personal certificate store are the two methods to use the certificate credentials.

Using a Local PFX Certificate for Authentication

You’ll need the following information to connect to Exchange Online PowerShell using a local certificate for authentication:

  • Your Azure AD tenant’s Directory ID or confirmed domain.
  • The AppID of the application you already registered.
  • The self-signed PFX certificate’s complete file path.
  • The seld-sign PFX certificate’s password.

Then, in the code below, alter the values of the $tenantID, $appID, $CertificateFilePath, and $pfxPassword variables. Copy the code and execute it in PowerShell after you’ve changed the values of the variables as appropriate.

## Create a tenant ID (directory ID or domain) ‘poshlab.ga’ as $tenantID $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450f (.pfx) ## Get the PFX password using $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’. ‘4mt4G*[email protected]’ as $pfxPassword Connect-ExchangeOnline -CertificateFilePath ## Connect to Exchange Online -CertificatePassword (ConvertTo-SecureString -String $pfxPassword -AsPlainText -Force)’-AppID $CertificateFilePath -Organization $appID $tenantID

The demo below shows that the PowerShell Connection to Exchange Online si successful using the local certificate file authentication.

Using a Local PFX Certificate for AuthenticationUsing a Local PFX Certificate for Authentication

When you examine the code again, you’ll see that the pfx certificate password is visible. For increased protection, you may consider storing the certificate credential in a secret management system.

Using the Certificate Thumbprint for Authentication

This way of authentication is more secure than using a password and a local certificate. You must import the certificate into the Personal certificate store using this approach. Only the thumbprint is required to determine which certificate to use for authentication.

The PFX certificate must first be imported into the Personal certificate repository. This step only has to be done once for the current user.

IMPORT THE PFX CERTIFICATE INTO THE CURRENT PERSONAL CERTIFICATE STORE WITH THIS CODE. ## Get the PFX password $mypwd = Get-Credential -UserName ‘Enter password below’ -Message ‘Enter password below’ ## Set the certificate file path (.pfx) $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’ ## Import the PFX certificate into the personal certificate store of the current user. -CertStoreLocation Cert:CurrentUserMy -Password Import-PfxCertificate -FilePath $CertificateFilePath $mypwd.Password

The demonstration below demonstrates how to import a PFX certificate into your own certificate store.

The PFX certificate is imported.The PFX certificate is imported.

The outcome of the PFX import procedure will be seen as shown above. Make a note of the value of the Thumbprint for future reference.

Your scripts may now use the thumbprint of the certificate to authenticate with Exchange Online PowerShell.

To match your right values, edit the $tenantID, $appID, and $CertificateThumbPrint in the code below. Then, in PowerShell, copy and execute the code.

## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID

If you run the code above in PowerShell, you’ll get something like the example below.

After executing the code in Powershell, this is the output.After executing the code in Powershell, this is the output.

Using App-Only Authentication to Connect and Run Exchange Online PowerShell Scripts

You’ve just been copying and pasting code into PowerShell so far in this tutorial. You should use app-only authentication to execute your PowerShell scripts now that you understand how it works.

The script below connects to Exchange Online PowerShell and authenticates using the certificate thumbprint. The script will then obtain all of the mailboxes accessible once connected. C:exo v2 demoListExoMailbox.ps1 is where the script is stored.

## Clean up Exchange Online Session Get-PSSession | Where-Object {$_.name -like “ExchangeOnline*”} | Remove-PSSession -ErrorAction SilentlyContinue ## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID ## Get All Mailbox Write-Output “Getting all mailboxes” Get-Mailbox -ResultSize Unlimited | Format-Table Name,DisplayName

Run the script in PowerShell once you’ve saved it. The script should automatically connect to Exchange Online and do its purpose. Refer to the findings in the demonstration below.

App-Only Authentication PowerShell ScriptApp-Only Authentication PowerShell Script

Summary

The EXO V2 PowerShell module’s release is a great development. Knowing that Microsoft has opted to remove basic authentication for connecting to Exchange Online through PowerShell, administrators may update their current scripts with this new app-only authentication option.

Implementing EXO V2 app-only authentication, on the other hand, is not without its difficulties.

  • A PFX password is still required when using a local certificate file. You should be able to avoid this password vulnerability problem if you use a credential or secret management approach.
  • In the personal shop, using a certificate gives you extra assurance. However, only the current user has access to the certificate. If you’ve set up a scheduled job to execute the script using UserA’s credentials, the certificate must be imported into UserA’s personal certificate store.
  • Certificates have a time limit. This would need certificate monitoring, renewal, and re-assignment to the Azure AD app. Otherwise, owing to an authentication failure, the script will cease operating.

These disadvantages are outweighed by the advantages of utilizing the new EXO V2 PowerShell module.

In this post, you learnt how to set up app-only authentication for the Exchange Online V2 PowerShell module step by step. You’ve also learned how to use a self-signed certificate to login to Exchange Online PowerShell.

You may now employ app-only certificate-based authentication in your scripts instead of dealing with Exchange Online PowerShell MFA prompts.

If you want to take things a step further, you might use Jenkins or Azure Automation to put everything you’ve learned in this article to the test. Alternatively, you may create your own PowerShell functions and modules.

Thank you for stopping by!

Additional Reading

.displayname -eq $directoryRole) $RoleId = (Get-AzureADDirectoryRole | Where-Object

You’re definitely utilizing PowerShell scripts to automate numerous Office 365 processes if you’re an administrator. It’s improbable, though, that you’re utilizing MFA to connect to Exchange Online through PowerShell for unattended scripts. This indicates that your scripts continue to use basic authentication.

On October 13, 2020, Microsoft intended to eliminate basic authentication from Exchange Online. After then, the plan was pushed back until the second half of 2021.

Admins must redesign their scripts as soon as possible, taking into account the following:

  • Modern authentication must be used in PowerShell scripts while yet allowing them to operate unattended.
  • In Office 365, PowerShell scripts must authenticate securely without the need to exclude a service account from multi-factor authentication.

Previously, current systems could not meet those two requirements. Fortunately, Microsoft has published version 2.0.3-preview of the Exchange Online V2 PowerShell module. The option to employ certificate-based authentication with an Azure AD app was included in this new version.

In this article, you’ll discover how to get ready to utilize the EXO V2 module with app-only contemporary authentication to execute Exchange Online unattended scripts. You’ll discover how to:

  • Create a new app and activate its service principal in Azure Active Directory.
  • Assign API roles and permissions.
  • Make a self-signed certificate and submit it.
  • Authenticate and connect to Exchange Online PowerShell using the app and certificate.

As a result, don’t expect to see a lot of point-and-click instructions in this post. PowerShell will be used for the majority of the walkthrough instructions.

Prerequisites

Make sure you have the following needs in order to follow along correctly.

  • With Global Admin rights, access to an Office 365 tenant. For testing, use a non-production/dev tenant. Consider up for a free Office 365 trial tenancy.
  • Windows PowerShell 5.1 on a Windows PC. This post will be written on a machine running Windows 10 version 1909.
  • The newest AzureAD PowerShell Module should be installed. This article was written using version 2.0.2.106.
  • Notepad++, Atom, Windows PowerShell ISE, or Visual Studio Code are examples of code editors. Use whatever one seems most natural to you.
  • For your test, create a functioning directory. The working directory in this article is C:exo v2 demo.
  • Save the Create-SelfSignedCertificate.ps1 script to your working directory after downloading it. The script will be saved in the working directory C:exo v2 demo in this article.

Using PowerShell to Set Up App-Only Authentication

You may be accustomed to running your PowerShell scripts using a generic account, sometimes known as a service account. In nature, such sort of account is a “shared” account. Anyone with access to that account’s credentials may log in and execute various administrative tasks on your business, which is a security risk.

App-only authentication aims to address this security issue. App-only authentication necessitates the creation of an Azure AD app with a service principal and certain permissions and roles. To authenticate, use a token or a certificate.

Adding API Permissions to an Azure AD Application

To begin, establish a new Azure AD app with the appropriate API access. To begin, launch an elevated Windows PowerShell session (run as administrator) and Connect to Azure Active Directory.

Connect to Azure Active DirectoryConnect to Azure Active Directory

The code below will create a new Exo V2 App app in Azure AD and attach it to the Exchange. The Office 365 Exchange Online API has the ManageAsApp permission.

If you want to give your app a different name, change the value of the $appName variable in the code below. Copy and execute the code in PowerShell.

# APP REGISTRATION, API PERMISSIONS, AND SERVICE PRINCIPAL ENABLEMENT CODE ## Name the client application $appName = ‘Exo V2 App’ ## Get information about the Office 365 Exchange Online API. (Get-AzureADServicePrincipal -Filter “AppID eq ‘00000002-0000-0ff1-ce00-000000000000’) $api = (Get-AzureADServicePrincipal -Filter “AppID ## Determine the API permission ID. Where-Object

You’re definitely utilizing PowerShell scripts to automate numerous Office 365 processes if you’re an administrator. It’s improbable, though, that you’re utilizing MFA to connect to Exchange Online through PowerShell for unattended scripts. This indicates that your scripts continue to use basic authentication.

On October 13, 2020, Microsoft intended to eliminate basic authentication from Exchange Online. After then, the plan was pushed back until the second half of 2021.

Admins must redesign their scripts as soon as possible, taking into account the following:

  • Modern authentication must be used in PowerShell scripts while yet allowing them to operate unattended.
  • In Office 365, PowerShell scripts must authenticate securely without the need to exclude a service account from multi-factor authentication.

Previously, current systems could not meet those two requirements. Fortunately, Microsoft has published version 2.0.3-preview of the Exchange Online V2 PowerShell module. The option to employ certificate-based authentication with an Azure AD app was included in this new version.

In this article, you’ll discover how to get ready to utilize the EXO V2 module with app-only contemporary authentication to execute Exchange Online unattended scripts. You’ll discover how to:

  • Create a new app and activate its service principal in Azure Active Directory.
  • Assign API roles and permissions.
  • Make a self-signed certificate and submit it.
  • Authenticate and connect to Exchange Online PowerShell using the app and certificate.

As a result, don’t expect to see a lot of point-and-click instructions in this post. PowerShell will be used for the majority of the walkthrough instructions.

Prerequisites

Make sure you have the following needs in order to follow along correctly.

  • With Global Admin rights, access to an Office 365 tenant. For testing, use a non-production/dev tenant. Consider up for a free Office 365 trial tenancy.
  • Windows PowerShell 5.1 on a Windows PC. This post will be written on a machine running Windows 10 version 1909.
  • The newest AzureAD PowerShell Module should be installed. This article was written using version 2.0.2.106.
  • Notepad++, Atom, Windows PowerShell ISE, or Visual Studio Code are examples of code editors. Use whatever one seems most natural to you.
  • For your test, create a functioning directory. The working directory in this article is C:exo v2 demo.
  • Save the Create-SelfSignedCertificate.ps1 script to your working directory after downloading it. The script will be saved in the working directory C:exo v2 demo in this article.

Using PowerShell to Set Up App-Only Authentication

You may be accustomed to running your PowerShell scripts using a generic account, sometimes known as a service account. In nature, such sort of account is a “shared” account. Anyone with access to that account’s credentials may log in and execute various administrative tasks on your business, which is a security risk.

App-only authentication aims to address this security issue. App-only authentication necessitates the creation of an Azure AD app with a service principal and certain permissions and roles. To authenticate, use a token or a certificate.

Adding API Permissions to an Azure AD Application

To begin, establish a new Azure AD app with the appropriate API access. To begin, launch an elevated Windows PowerShell session (run as administrator) and Connect to Azure Active Directory.

Connect to Azure Active DirectoryConnect to Azure Active Directory

The code below will create a new Exo V2 App app in Azure AD and attach it to the Exchange. The Office 365 Exchange Online API has the ManageAsApp permission.

If you want to give your app a different name, change the value of the $appName variable in the code below. Copy and execute the code in PowerShell.

# CODE TO REGISTER APP, ASSIGN API PERMISSIONS, AND ENABLE SERVICE PRINCIPAL ## Define the client app name $appName = ‘Exo_V2_App’ ## Get the Office 365 Exchange Online API details. $api = (Get-AzureADServicePrincipal -Filter “AppID eq ‘00000002-0000-0ff1-ce00-000000000000′”) ## Get the API permission ID $permission = $api.AppRoles | Where-Object { $_.Value -eq ‘Exchange.ManageAsApp’ } ## Build the API permission object (TYPE: Role = Application, Scope = User) $apiPermission = [Microsoft.Open.AzureAD.Model.RequiredResourceAccess]@{ ResourceAppId = $api.AppId ; ResourceAccess = [Microsoft.Open.AzureAD.Model.ResourceAccess]@{ Id = $permission.Id ; Type = “Role” } } ## Register the new Azure AD App with API Permissions $myApp = New-AzureADApplication -DisplayName $appName -ReplyUrls ‘http://localhost’ -RequiredResourceAccess $apiPermission ## Enable the Service Principal $mySP = New-AzureADServicePrincipal -AppID $myApp.AppID ## Display the new app properties $myApp | Format-List DisplayName,ObjectID,AppID

The code is shown in the video below. The DisplayName, ObjectID, and AppID attributes of the new app will be presented at the end. These attributes are saved in the $myApp variable. The service principal’s property values are stored in the $mySP variable.

Create a new Azure Active Directory app.Create a new Azure Active Directory app.

TIP: Save the attributes of the application for future reference.

Use the command below to export the application’s property values.

“$($appName).csv” $myApp | Export-Csv -NoTypeInformation

Adding an Azure Active Directory Role to the Application

The next step is to assign an Azure AD role to the app’s service principal once it has been created. You’ll need to select what kind of role your app should have.

These are the legitimate supported roles for Exchange Online V2.

  • Company administrator
  • Compliance administrator
  • Security reader
  • Security administrator
  • Helpdesk administrator
  • Exchange Service Administrator
  • Global Reader

Only grant the least privileged role to your script that you believe is suitable. The code below assigns the Exchange Service administrator role to the app’s service principal in this case.

## The role to assign to your app $directoryRole = ‘Exchange Service Administrator’ ## Find the ObjectID of ‘Exchange Service Administrator’ $RoleId = (Get-AzureADDirectoryRole | Where-Object {$_.displayname -eq $directoryRole}).ObjectID ## Add the service principal to the directory role Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose

You should get a result similar to the one displayed in the example below if you execute the command above in PowerShell.

Giving the app an Azure Active Directory roleGiving the app an Azure Active Directory role

Making a self-signed certificate and attaching it to the application

The next step is to create a self-signed certificate and add it to your program. This step will need the Create-SelfSignedCertificate.ps1 script.

The script below will create a self-signed certificate with the subject name of your app, such as Exo V2 App. The certificate is only good for one year.

Update the $certYears value to the desired number of years if you wish to change the certificate’s validity. If you wish to use a different password for the generated certificate (PFX) file, you may alter the $certPassword value.

## Validity of the certificate in years 1 $certYears ## Password for the Certificate (PFX) ‘4mt4G*[email protected]’ is the certificate password. Create-SelfSignedCertificate. -CommonName ps1 $appName ‘ -BeginDate (Get-Date). AddDays(-1) ‘ -FinishDate (Get-Date). AddYears($certYears) ‘ -Force (ConvertTo-SecureString $certPassword -AsPlainText)’-Password (ConvertTo-SecureString $certPassword -AsPlainText

Two files will be produced when you execute the code above in PowerShell, as seen in the sample below.

Create a certificate that is self-signed.Create a certificate that is self-signed.

The next step is to submit your newly generated certificate to your Azure AD app. The code below will find and attach the certificate (.CER) file in your working directory to the Azure AD app. You don’t need to change the code; just copy and execute it in PowerShell.

## Download the certificate (.CER) (Resolve-Path “.$($appName).cer”) $CertificateFilePath Path ## Make a certificate object. $cer = System.Security.Cryptography.X509Certificates.X509Certificate2 New-Object $cer $cer.Import(“$($CertificateFilePath)”) $cer.GetRawCertData $bin () $bin = $cer.GetCertHash $base64Value = [System.Convert]::ToBase64String($bin) () $bin = [System.Convert]::ToBase64String($base64Thumbprint) ## In AzureAD, upload and assign the certificate to the application. -ObjectId $null = New-AzureADApplicationKeyCredential -CustomKeyIdentifier $myApp.ObjectID ‘ -Type AsymmetricX509Cert -Usage Verify’-Value $base64Thumbprint ‘ -StartDate ($cer.NotBefore)’-EndDate ($cer.NotAfter)’$base64Value

If the code above is executed in PowerShell, no output should be expected until an error occurs. When the code is successfully executed, the outcome is shown in the example below.

Adding the certificate to the Azure Active Directory appAdding the certificate to the Azure Active Directory app

Approval of the Application by the Admin

You’re almost finished with your setup. The next step is for a Global Admin to give your Azure AD app permission. This step may be carried out by you or another Global Admin in your company.

From the Azure Active Directory admin center, a Global admin may provide consent. However, PowerShell can also build a consent URL. You may either provide it to the Global admin or use it to grant consent yourself.

This is the format for the consent URL.

https://login.microsoftonline.com/{TenantID}/adminconsent?client id={ApplicationID}

The TenantID value is your Office 365 tenant’s directory ID or confirmed domain. The AppID of the Azure AD application that you previously generated is the value for ApplicationID.

Based on the variables supplied, the code below will construct the consent URL. The consent URL will then be shown on the screen and opened in the default browser on the machine.

## Obtain TenantID $tenantID = $tenantID (Get-AzureADTenantDetail). ObjectID ## Visit this link “https://login.microsoftonline.com/$tenantID/adminconsent?client id=$($myApp.AppId)” $consentURL = “https://login.microsoftonline.com/$tenantID/adminconsent ## Make the consent URL visible. $consentURL ## Use the default browser to access the consent URL. $consentURL -Start-Process

To see what occurs when you execute the code above in PowerShell, look at the example below.

Create a consent URL and provide permission.Create a consent URL and provide permission.

PowerShell Connection to Exchange Online

You must now upload and attach the certificate after establishing the app and giving permissions and roles. You may now use the app’s certificate credentials to login to Exchange Online PowerShell.

The local certificate file (.pfx) and the thumbprint of the certificate put in the current user’s personal certificate store are the two methods to use the certificate credentials.

Using a Local PFX Certificate for Authentication

You’ll need the following information to connect to Exchange Online PowerShell using a local certificate for authentication:

  • Your Azure AD tenant’s Directory ID or confirmed domain.
  • The AppID of the application you already registered.
  • The self-signed PFX certificate’s complete file path.
  • The seld-sign PFX certificate’s password.

Then, in the code below, alter the values of the $tenantID, $appID, $CertificateFilePath, and $pfxPassword variables. Copy the code and execute it in PowerShell after you’ve changed the values of the variables as appropriate.

## Create a tenant ID (directory ID or domain) ‘poshlab.ga’ as $tenantID $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450f (.pfx) ## Get the PFX password using $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’. ‘4mt4G*[email protected]’ as $pfxPassword Connect-ExchangeOnline -CertificateFilePath ## Connect to Exchange Online -CertificatePassword (ConvertTo-SecureString -String $pfxPassword -AsPlainText -Force)’-AppID $CertificateFilePath -Organization $appID $tenantID

The demo below shows that the PowerShell Connection to Exchange Online si successful using the local certificate file authentication.

Using a Local PFX Certificate for AuthenticationUsing a Local PFX Certificate for Authentication

When you examine the code again, you’ll see that the pfx certificate password is visible. For increased protection, you may consider storing the certificate credential in a secret management system.

Using the Certificate Thumbprint for Authentication

This way of authentication is more secure than using a password and a local certificate. You must import the certificate into the Personal certificate store using this approach. Only the thumbprint is required to determine which certificate to use for authentication.

The PFX certificate must first be imported into the Personal certificate repository. This step only has to be done once for the current user.

IMPORT THE PFX CERTIFICATE INTO THE CURRENT PERSONAL CERTIFICATE STORE WITH THIS CODE. ## Get the PFX password $mypwd = Get-Credential -UserName ‘Enter password below’ -Message ‘Enter password below’ ## Set the certificate file path (.pfx) $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’ ## Import the PFX certificate into the personal certificate store of the current user. -CertStoreLocation Cert:CurrentUserMy -Password Import-PfxCertificate -FilePath $CertificateFilePath $mypwd.Password

The demonstration below demonstrates how to import a PFX certificate into your own certificate store.

The PFX certificate is imported.The PFX certificate is imported.

The outcome of the PFX import procedure will be seen as shown above. Make a note of the value of the Thumbprint for future reference.

Your scripts may now use the thumbprint of the certificate to authenticate with Exchange Online PowerShell.

To match your right values, edit the $tenantID, $appID, and $CertificateThumbPrint in the code below. Then, in PowerShell, copy and execute the code.

## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID

If you run the code above in PowerShell, you’ll get something like the example below.

After executing the code in Powershell, this is the output.After executing the code in Powershell, this is the output.

Using App-Only Authentication to Connect and Run Exchange Online PowerShell Scripts

You’ve just been copying and pasting code into PowerShell so far in this tutorial. You should use app-only authentication to execute your PowerShell scripts now that you understand how it works.

The script below connects to Exchange Online PowerShell and authenticates using the certificate thumbprint. The script will then obtain all of the mailboxes accessible once connected. C:exo v2 demoListExoMailbox.ps1 is where the script is stored.

## Clean up Exchange Online Session Get-PSSession | Where-Object {$_.name -like “ExchangeOnline*”} | Remove-PSSession -ErrorAction SilentlyContinue ## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID ## Get All Mailbox Write-Output “Getting all mailboxes” Get-Mailbox -ResultSize Unlimited | Format-Table Name,DisplayName

Run the script in PowerShell once you’ve saved it. The script should automatically connect to Exchange Online and do its purpose. Refer to the findings in the demonstration below.

App-Only Authentication PowerShell ScriptApp-Only Authentication PowerShell Script

Summary

The EXO V2 PowerShell module’s release is a great development. Knowing that Microsoft has opted to remove basic authentication for connecting to Exchange Online through PowerShell, administrators may update their current scripts with this new app-only authentication option.

Implementing EXO V2 app-only authentication, on the other hand, is not without its difficulties.

  • A PFX password is still required when using a local certificate file. You should be able to avoid this password vulnerability problem if you use a credential or secret management approach.
  • In the personal shop, using a certificate gives you extra assurance. However, only the current user has access to the certificate. If you’ve set up a scheduled job to execute the script using UserA’s credentials, the certificate must be imported into UserA’s personal certificate store.
  • Certificates have a time limit. This would need certificate monitoring, renewal, and re-assignment to the Azure AD app. Otherwise, owing to an authentication failure, the script will cease operating.

These disadvantages are outweighed by the advantages of utilizing the new EXO V2 PowerShell module.

In this post, you learnt how to set up app-only authentication for the Exchange Online V2 PowerShell module step by step. You’ve also learned how to use a self-signed certificate to login to Exchange Online PowerShell.

You may now employ app-only certificate-based authentication in your scripts instead of dealing with Exchange Online PowerShell MFA prompts.

If you want to take things a step further, you might use Jenkins or Azure Automation to put everything you’ve learned in this article to the test. Alternatively, you may create your own PowerShell functions and modules.

Thank you for stopping by!

Additional Reading

.Value -eq ‘Exchange.ManageAsApp’ | $permission = $api.AppRoles ## Create the API authorization object (TYPE: Application, Scope: User) [Microsoft.Open.AzureAD.Model] $apiPermission .RequiredResourceAccess] @ ResourceAccess = [Microsoft.Open.AzureAD.Model]; ResourceAppId = $api.AppId .ResourceAccess] @ Type = “Role”; Id = $permission.Id ## Grant API Permissions to the new Azure AD App New-AzureADApplication -DisplayName $myApp ‘http://localhost’ -RequiredResourceAccess $appName -ReplyUrls $apiPermission ## Make the Service Principal active. New-AzureADServicePrincipal -AppID $mySP $myApp.AppID ## Format-List DisplayName,ObjectID,AppID to show the new app properties $myApp

The code is shown in the video below. The DisplayName, ObjectID, and AppID attributes of the new app will be presented at the end. These attributes are saved in the $myApp variable. The service principal’s property values are stored in the $mySP variable.

Create a new Azure Active Directory app.Create a new Azure Active Directory app.

TIP: Save the attributes of the application for future reference.

Use the command below to export the application’s property values.

“$($appName).csv” $myApp | Export-Csv -NoTypeInformation

Adding an Azure Active Directory Role to the Application

The next step is to assign an Azure AD role to the app’s service principal once it has been created. You’ll need to select what kind of role your app should have.

These are the legitimate supported roles for Exchange Online V2.

  • Company administrator
  • Compliance administrator
  • Security reader
  • Security administrator
  • Helpdesk administrator
  • Exchange Service Administrator
  • Global Reader

Only grant the least privileged role to your script that you believe is suitable. The code below assigns the Exchange Service administrator role to the app’s service principal in this case.

## The role to assign to your app $directoryRole = ‘Exchange Service Administrator’ ## Find the ObjectID of ‘Exchange Service Administrator’ $RoleId = (Get-AzureADDirectoryRole | Where-Object {$_.displayname -eq $directoryRole}).ObjectID ## Add the service principal to the directory role Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose

You should get a result similar to the one displayed in the example below if you execute the command above in PowerShell.

Giving the app an Azure Active Directory roleGiving the app an Azure Active Directory role

Making a self-signed certificate and attaching it to the application

The next step is to create a self-signed certificate and add it to your program. This step will need the Create-SelfSignedCertificate.ps1 script.

The script below will create a self-signed certificate with the subject name of your app, such as Exo V2 App. The certificate is only good for one year.

Update the $certYears value to the desired number of years if you wish to change the certificate’s validity. If you wish to use a different password for the generated certificate (PFX) file, you may alter the $certPassword value.

## Validity of the certificate in years 1 $certYears ## Password for the Certificate (PFX) ‘4mt4G*[email protected]’ is the certificate password. Create-SelfSignedCertificate. -CommonName ps1 $appName ‘ -BeginDate (Get-Date). AddDays(-1) ‘ -FinishDate (Get-Date). AddYears($certYears) ‘ -Force (ConvertTo-SecureString $certPassword -AsPlainText)’-Password (ConvertTo-SecureString $certPassword -AsPlainText

Two files will be produced when you execute the code above in PowerShell, as seen in the sample below.

Create a certificate that is self-signed.Create a certificate that is self-signed.

The next step is to submit your newly generated certificate to your Azure AD app. The code below will find and attach the certificate (.CER) file in your working directory to the Azure AD app. You don’t need to change the code; just copy and execute it in PowerShell.

## Download the certificate (.CER) (Resolve-Path “.$($appName).cer”) $CertificateFilePath Path ## Make a certificate object. $cer = System.Security.Cryptography.X509Certificates.X509Certificate2 New-Object $cer $cer.Import(“$($CertificateFilePath)”) $cer.GetRawCertData $bin () $bin = $cer.GetCertHash $base64Value = [System.Convert]::ToBase64String($bin) () $bin = [System.Convert]::ToBase64String($base64Thumbprint) ## In AzureAD, upload and assign the certificate to the application. -ObjectId $null = New-AzureADApplicationKeyCredential -CustomKeyIdentifier $myApp.ObjectID ‘ -Type AsymmetricX509Cert -Usage Verify’-Value $base64Thumbprint ‘ -StartDate ($cer.NotBefore)’-EndDate ($cer.NotAfter)’$base64Value

If the code above is executed in PowerShell, no output should be expected until an error occurs. When the code is successfully executed, the outcome is shown in the example below.

Adding the certificate to the Azure Active Directory appAdding the certificate to the Azure Active Directory app

Approval of the Application by the Admin

You’re almost finished with your setup. The next step is for a Global Admin to give your Azure AD app permission. This step may be carried out by you or another Global Admin in your company.

From the Azure Active Directory admin center, a Global admin may provide consent. However, PowerShell can also build a consent URL. You may either provide it to the Global admin or use it to grant consent yourself.

This is the format for the consent URL.

https://login.microsoftonline.com/{TenantID}/adminconsent?client id={ApplicationID}

The TenantID value is your Office 365 tenant’s directory ID or confirmed domain. The AppID of the Azure AD application that you previously generated is the value for ApplicationID.

Based on the variables supplied, the code below will construct the consent URL. The consent URL will then be shown on the screen and opened in the default browser on the machine.

## Obtain TenantID $tenantID = $tenantID (Get-AzureADTenantDetail). ObjectID ## Visit this link “https://login.microsoftonline.com/$tenantID/adminconsent?client id=$($myApp.AppId)” $consentURL = “https://login.microsoftonline.com/$tenantID/adminconsent ## Make the consent URL visible. $consentURL ## Use the default browser to access the consent URL. $consentURL -Start-Process

To see what occurs when you execute the code above in PowerShell, look at the example below.

Create a consent URL and provide permission.Create a consent URL and provide permission.

PowerShell Connection to Exchange Online

You must now upload and attach the certificate after establishing the app and giving permissions and roles. You may now use the app’s certificate credentials to login to Exchange Online PowerShell.

The local certificate file (.pfx) and the thumbprint of the certificate put in the current user’s personal certificate store are the two methods to use the certificate credentials.

Using a Local PFX Certificate for Authentication

You’ll need the following information to connect to Exchange Online PowerShell using a local certificate for authentication:

  • Your Azure AD tenant’s Directory ID or confirmed domain.
  • The AppID of the application you already registered.
  • The self-signed PFX certificate’s complete file path.
  • The seld-sign PFX certificate’s password.

Then, in the code below, alter the values of the $tenantID, $appID, $CertificateFilePath, and $pfxPassword variables. Copy the code and execute it in PowerShell after you’ve changed the values of the variables as appropriate.

## Create a tenant ID (directory ID or domain) ‘poshlab.ga’ as $tenantID $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450f (.pfx) ## Get the PFX password using $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’. ‘4mt4G*[email protected]’ as $pfxPassword Connect-ExchangeOnline -CertificateFilePath ## Connect to Exchange Online -CertificatePassword (ConvertTo-SecureString -String $pfxPassword -AsPlainText -Force)’-AppID $CertificateFilePath -Organization $appID $tenantID

The demo below shows that the PowerShell Connection to Exchange Online si successful using the local certificate file authentication.

Using a Local PFX Certificate for AuthenticationUsing a Local PFX Certificate for Authentication

When you examine the code again, you’ll see that the pfx certificate password is visible. For increased protection, you may consider storing the certificate credential in a secret management system.

Using the Certificate Thumbprint for Authentication

This way of authentication is more secure than using a password and a local certificate. You must import the certificate into the Personal certificate store using this approach. Only the thumbprint is required to determine which certificate to use for authentication.

The PFX certificate must first be imported into the Personal certificate repository. This step only has to be done once for the current user.

IMPORT THE PFX CERTIFICATE INTO THE CURRENT PERSONAL CERTIFICATE STORE WITH THIS CODE. ## Get the PFX password $mypwd = Get-Credential -UserName ‘Enter password below’ -Message ‘Enter password below’ ## Set the certificate file path (.pfx) $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’ ## Import the PFX certificate into the personal certificate store of the current user. -CertStoreLocation Cert:CurrentUserMy -Password Import-PfxCertificate -FilePath $CertificateFilePath $mypwd.Password

The demonstration below demonstrates how to import a PFX certificate into your own certificate store.

The PFX certificate is imported.The PFX certificate is imported.

The outcome of the PFX import procedure will be seen as shown above. Make a note of the value of the Thumbprint for future reference.

Your scripts may now use the thumbprint of the certificate to authenticate with Exchange Online PowerShell.

To match your right values, edit the $tenantID, $appID, and $CertificateThumbPrint in the code below. Then, in PowerShell, copy and execute the code.

## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID

If you run the code above in PowerShell, you’ll get something like the example below.

After executing the code in Powershell, this is the output.After executing the code in Powershell, this is the output.

Using App-Only Authentication to Connect and Run Exchange Online PowerShell Scripts

You’ve just been copying and pasting code into PowerShell so far in this tutorial. You should use app-only authentication to execute your PowerShell scripts now that you understand how it works.

The script below connects to Exchange Online PowerShell and authenticates using the certificate thumbprint. The script will then obtain all of the mailboxes accessible once connected. C:exo v2 demoListExoMailbox.ps1 is where the script is stored.

## Clean up Exchange Online Session Get-PSSession | Where-Object {$_.name -like “ExchangeOnline*”} | Remove-PSSession -ErrorAction SilentlyContinue ## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID ## Get All Mailbox Write-Output “Getting all mailboxes” Get-Mailbox -ResultSize Unlimited | Format-Table Name,DisplayName

Run the script in PowerShell once you’ve saved it. The script should automatically connect to Exchange Online and do its purpose. Refer to the findings in the demonstration below.

App-Only Authentication PowerShell ScriptApp-Only Authentication PowerShell Script

Summary

The EXO V2 PowerShell module’s release is a great development. Knowing that Microsoft has opted to remove basic authentication for connecting to Exchange Online through PowerShell, administrators may update their current scripts with this new app-only authentication option.

Implementing EXO V2 app-only authentication, on the other hand, is not without its difficulties.

  • A PFX password is still required when using a local certificate file. You should be able to avoid this password vulnerability problem if you use a credential or secret management approach.
  • In the personal shop, using a certificate gives you extra assurance. However, only the current user has access to the certificate. If you’ve set up a scheduled job to execute the script using UserA’s credentials, the certificate must be imported into UserA’s personal certificate store.
  • Certificates have a time limit. This would need certificate monitoring, renewal, and re-assignment to the Azure AD app. Otherwise, owing to an authentication failure, the script will cease operating.

These disadvantages are outweighed by the advantages of utilizing the new EXO V2 PowerShell module.

In this post, you learnt how to set up app-only authentication for the Exchange Online V2 PowerShell module step by step. You’ve also learned how to use a self-signed certificate to login to Exchange Online PowerShell.

You may now employ app-only certificate-based authentication in your scripts instead of dealing with Exchange Online PowerShell MFA prompts.

If you want to take things a step further, you might use Jenkins or Azure Automation to put everything you’ve learned in this article to the test. Alternatively, you may create your own PowerShell functions and modules.

Thank you for stopping by!

Additional Reading

.displayname ObjectID ## Assign the directory role to the service principal. ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose Add-AzureADDirectoryRoleMember

You should get a result similar to the one displayed in the example below if you execute the command above in PowerShell.

Giving the app an Azure Active Directory roleGiving the app an Azure Active Directory role

Making a self-signed certificate and attaching it to the application

The next step is to create a self-signed certificate and add it to your program. This step will need the Create-SelfSignedCertificate.ps1 script.

The script below will create a self-signed certificate with the subject name of your app, such as Exo V2 App. The certificate is only good for one year.

Update the $certYears value to the desired number of years if you wish to change the certificate’s validity. If you wish to use a different password for the generated certificate (PFX) file, you may alter the $certPassword value.

## Validity of the certificate in years 1 $certYears ## Password for the Certificate (PFX) ‘4mt4G*[email protected]’ is the certificate password. Create-SelfSignedCertificate. -CommonName ps1 $appName ‘ -BeginDate (Get-Date). AddDays(-1) ‘ -FinishDate (Get-Date). AddYears($certYears) ‘ -Force (ConvertTo-SecureString $certPassword -AsPlainText)’-Password (ConvertTo-SecureString $certPassword -AsPlainText

Two files will be produced when you execute the code above in PowerShell, as seen in the sample below.

Create a certificate that is self-signed.Create a certificate that is self-signed.

The next step is to submit your newly generated certificate to your Azure AD app. The code below will find and attach the certificate (.CER) file in your working directory to the Azure AD app. You don’t need to change the code; just copy and execute it in PowerShell.

## Download the certificate (.CER) (Resolve-Path “.$($appName).cer”) $CertificateFilePath Path ## Make a certificate object. $cer = System.Security.Cryptography.X509Certificates.X509Certificate2 New-Object $cer $cer.Import(“$($CertificateFilePath)”) $cer.GetRawCertData $bin () $bin = $cer.GetCertHash $base64Value = [System.Convert]::ToBase64String($bin) () $bin = [System.Convert]::ToBase64String($base64Thumbprint) ## In AzureAD, upload and assign the certificate to the application. -ObjectId $null = New-AzureADApplicationKeyCredential -CustomKeyIdentifier $myApp.ObjectID ‘ -Type AsymmetricX509Cert -Usage Verify’-Value $base64Thumbprint ‘ -StartDate ($cer.NotBefore)’-EndDate ($cer.NotAfter)’$base64Value

If the code above is executed in PowerShell, no output should be expected until an error occurs. When the code is successfully executed, the outcome is shown in the example below.

Adding the certificate to the Azure Active Directory appAdding the certificate to the Azure Active Directory app

Approval of the Application by the Admin

You’re almost finished with your setup. The next step is for a Global Admin to give your Azure AD app permission. This step may be carried out by you or another Global Admin in your company.

From the Azure Active Directory admin center, a Global admin may provide consent. However, PowerShell can also build a consent URL. You may either provide it to the Global admin or use it to grant consent yourself.

This is the format for the consent URL.

https://login.microsoftonline.com/{TenantID}/adminconsent?client id={ApplicationID}

The TenantID value is your Office 365 tenant’s directory ID or confirmed domain. The AppID of the Azure AD application that you previously generated is the value for ApplicationID.

Based on the variables supplied, the code below will construct the consent URL. The consent URL will then be shown on the screen and opened in the default browser on the machine.

## Obtain TenantID $tenantID = $tenantID (Get-AzureADTenantDetail). ObjectID ## Visit this link “https://login.microsoftonline.com/$tenantID/adminconsent?client id=$($myApp.AppId)” $consentURL = “https://login.microsoftonline.com/$tenantID/adminconsent ## Make the consent URL visible. $consentURL ## Use the default browser to access the consent URL. $consentURL -Start-Process

To see what occurs when you execute the code above in PowerShell, look at the example below.

Create a consent URL and provide permission.Create a consent URL and provide permission.

PowerShell Connection to Exchange Online

You must now upload and attach the certificate after establishing the app and giving permissions and roles. You may now use the app’s certificate credentials to login to Exchange Online PowerShell.

The local certificate file (.pfx) and the thumbprint of the certificate put in the current user’s personal certificate store are the two methods to use the certificate credentials.

Using a Local PFX Certificate for Authentication

You’ll need the following information to connect to Exchange Online PowerShell using a local certificate for authentication:

  • Your Azure AD tenant’s Directory ID or confirmed domain.
  • The AppID of the application you already registered.
  • The self-signed PFX certificate’s complete file path.
  • The seld-sign PFX certificate’s password.

Then, in the code below, alter the values of the $tenantID, $appID, $CertificateFilePath, and $pfxPassword variables. Copy the code and execute it in PowerShell after you’ve changed the values of the variables as appropriate.

## Create a tenant ID (directory ID or domain) ‘poshlab.ga’ as $tenantID $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450f (.pfx) ## Get the PFX password using $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’. ‘4mt4G*[email protected]’ as $pfxPassword Connect-ExchangeOnline -CertificateFilePath ## Connect to Exchange Online -CertificatePassword (ConvertTo-SecureString -String $pfxPassword -AsPlainText -Force)’-AppID $CertificateFilePath -Organization $appID $tenantID

The demo below shows that the PowerShell Connection to Exchange Online si successful using the local certificate file authentication.

Using a Local PFX Certificate for AuthenticationUsing a Local PFX Certificate for Authentication

When you examine the code again, you’ll see that the pfx certificate password is visible. For increased protection, you may consider storing the certificate credential in a secret management system.

Using the Certificate Thumbprint for Authentication

This way of authentication is more secure than using a password and a local certificate. You must import the certificate into the Personal certificate store using this approach. Only the thumbprint is required to determine which certificate to use for authentication.

The PFX certificate must first be imported into the Personal certificate repository. This step only has to be done once for the current user.

IMPORT THE PFX CERTIFICATE INTO THE CURRENT PERSONAL CERTIFICATE STORE WITH THIS CODE. ## Get the PFX password $mypwd = Get-Credential -UserName ‘Enter password below’ -Message ‘Enter password below’ ## Set the certificate file path (.pfx) $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’ ## Import the PFX certificate into the personal certificate store of the current user. -CertStoreLocation Cert:CurrentUserMy -Password Import-PfxCertificate -FilePath $CertificateFilePath $mypwd.Password

The demonstration below demonstrates how to import a PFX certificate into your own certificate store.

The PFX certificate is imported.The PFX certificate is imported.

The outcome of the PFX import procedure will be seen as shown above. Make a note of the value of the Thumbprint for future reference.

Your scripts may now use the thumbprint of the certificate to authenticate with Exchange Online PowerShell.

To match your right values, edit the $tenantID, $appID, and $CertificateThumbPrint in the code below. Then, in PowerShell, copy and execute the code.

## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID

If you run the code above in PowerShell, you’ll get something like the example below.

After executing the code in Powershell, this is the output.After executing the code in Powershell, this is the output.

Using App-Only Authentication to Connect and Run Exchange Online PowerShell Scripts

You’ve just been copying and pasting code into PowerShell so far in this tutorial. You should use app-only authentication to execute your PowerShell scripts now that you understand how it works.

The script below connects to Exchange Online PowerShell and authenticates using the certificate thumbprint. The script will then obtain all of the mailboxes accessible once connected. C:exo v2 demoListExoMailbox.ps1 is where the script is stored.

## Clean up Exchange Online Session Get-PSSession | Where-Object {$_.name -like “ExchangeOnline*”} | Remove-PSSession -ErrorAction SilentlyContinue ## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID ## Get All Mailbox Write-Output “Getting all mailboxes” Get-Mailbox -ResultSize Unlimited | Format-Table Name,DisplayName

Run the script in PowerShell once you’ve saved it. The script should automatically connect to Exchange Online and do its purpose. Refer to the findings in the demonstration below.

App-Only Authentication PowerShell ScriptApp-Only Authentication PowerShell Script

Summary

The EXO V2 PowerShell module’s release is a great development. Knowing that Microsoft has opted to remove basic authentication for connecting to Exchange Online through PowerShell, administrators may update their current scripts with this new app-only authentication option.

Implementing EXO V2 app-only authentication, on the other hand, is not without its difficulties.

  • A PFX password is still required when using a local certificate file. You should be able to avoid this password vulnerability problem if you use a credential or secret management approach.
  • In the personal shop, using a certificate gives you extra assurance. However, only the current user has access to the certificate. If you’ve set up a scheduled job to execute the script using UserA’s credentials, the certificate must be imported into UserA’s personal certificate store.
  • Certificates have a time limit. This would need certificate monitoring, renewal, and re-assignment to the Azure AD app. Otherwise, owing to an authentication failure, the script will cease operating.

These disadvantages are outweighed by the advantages of utilizing the new EXO V2 PowerShell module.

In this post, you learnt how to set up app-only authentication for the Exchange Online V2 PowerShell module step by step. You’ve also learned how to use a self-signed certificate to login to Exchange Online PowerShell.

You may now employ app-only certificate-based authentication in your scripts instead of dealing with Exchange Online PowerShell MFA prompts.

If you want to take things a step further, you might use Jenkins or Azure Automation to put everything you’ve learned in this article to the test. Alternatively, you may create your own PowerShell functions and modules.

Thank you for stopping by!

Additional Reading

.Value -eq ‘Exchange.ManageAsApp’ | $permission = $api.AppRoles ## Create the API authorization object (TYPE: Application, Scope: User) [Microsoft.Open.AzureAD.Model] $apiPermission .RequiredResourceAccess] @ ResourceAccess = [Microsoft.Open.AzureAD.Model]; ResourceAppId = $api.AppId .ResourceAccess] @ Type = “Role”; Id = $permission.Id ## Grant API Permissions to the new Azure AD App New-AzureADApplication -DisplayName $myApp ‘http://localhost’ -RequiredResourceAccess $appName -ReplyUrls $apiPermission ## Make the Service Principal active. New-AzureADServicePrincipal -AppID $mySP $myApp.AppID ## Format-List DisplayName,ObjectID,AppID to show the new app properties $myApp

The code is shown in the video below. The DisplayName, ObjectID, and AppID attributes of the new app will be presented at the end. These attributes are saved in the $myApp variable. The service principal’s property values are stored in the $mySP variable.

Create a new Azure Active Directory app.Create a new Azure Active Directory app.

TIP: Save the attributes of the application for future reference.

Use the command below to export the application’s property values.

“$($appName).csv” $myApp | Export-Csv -NoTypeInformation

Adding an Azure Active Directory Role to the Application

The next step is to assign an Azure AD role to the app’s service principal once it has been created. You’ll need to select what kind of role your app should have.

These are the legitimate supported roles for Exchange Online V2.

  • Company administrator
  • Compliance administrator
  • Security reader
  • Security administrator
  • Helpdesk administrator
  • Exchange Service Administrator
  • Global Reader

Only grant the least privileged role to your script that you believe is suitable. The code below assigns the Exchange Service administrator role to the app’s service principal in this case.

## The app’s role to be assigned ## Find the ObjectID of ‘Exchange Service Administrator’ using $directoryRole = ‘Exchange Service Administrator’. (Get-AzureADDirectoryRole | Where-Object

You’re definitely utilizing PowerShell scripts to automate numerous Office 365 processes if you’re an administrator. It’s improbable, though, that you’re utilizing MFA to connect to Exchange Online through PowerShell for unattended scripts. This indicates that your scripts continue to use basic authentication.

On October 13, 2020, Microsoft intended to eliminate basic authentication from Exchange Online. After then, the plan was pushed back until the second half of 2021.

Admins must redesign their scripts as soon as possible, taking into account the following:

  • Modern authentication must be used in PowerShell scripts while yet allowing them to operate unattended.
  • In Office 365, PowerShell scripts must authenticate securely without the need to exclude a service account from multi-factor authentication.

Previously, current systems could not meet those two requirements. Fortunately, Microsoft has published version 2.0.3-preview of the Exchange Online V2 PowerShell module. The option to employ certificate-based authentication with an Azure AD app was included in this new version.

In this article, you’ll discover how to get ready to utilize the EXO V2 module with app-only contemporary authentication to execute Exchange Online unattended scripts. You’ll discover how to:

  • Create a new app and activate its service principal in Azure Active Directory.
  • Assign API roles and permissions.
  • Make a self-signed certificate and submit it.
  • Authenticate and connect to Exchange Online PowerShell using the app and certificate.

As a result, don’t expect to see a lot of point-and-click instructions in this post. PowerShell will be used for the majority of the walkthrough instructions.

Prerequisites

Make sure you have the following needs in order to follow along correctly.

  • With Global Admin rights, access to an Office 365 tenant. For testing, use a non-production/dev tenant. Consider up for a free Office 365 trial tenancy.
  • Windows PowerShell 5.1 on a Windows PC. This post will be written on a machine running Windows 10 version 1909.
  • The newest AzureAD PowerShell Module should be installed. This article was written using version 2.0.2.106.
  • Notepad++, Atom, Windows PowerShell ISE, or Visual Studio Code are examples of code editors. Use whatever one seems most natural to you.
  • For your test, create a functioning directory. The working directory in this article is C:exo v2 demo.
  • Save the Create-SelfSignedCertificate.ps1 script to your working directory after downloading it. The script will be saved in the working directory C:exo v2 demo in this article.

Using PowerShell to Set Up App-Only Authentication

You may be accustomed to running your PowerShell scripts using a generic account, sometimes known as a service account. In nature, such sort of account is a “shared” account. Anyone with access to that account’s credentials may log in and execute various administrative tasks on your business, which is a security risk.

App-only authentication aims to address this security issue. App-only authentication necessitates the creation of an Azure AD app with a service principal and certain permissions and roles. To authenticate, use a token or a certificate.

Adding API Permissions to an Azure AD Application

To begin, establish a new Azure AD app with the appropriate API access. To begin, launch an elevated Windows PowerShell session (run as administrator) and Connect to Azure Active Directory.

Connect to Azure Active DirectoryConnect to Azure Active Directory

The code below will create a new Exo V2 App app in Azure AD and attach it to the Exchange. The Office 365 Exchange Online API has the ManageAsApp permission.

If you want to give your app a different name, change the value of the $appName variable in the code below. Copy and execute the code in PowerShell.

# APP REGISTRATION, API PERMISSIONS, AND SERVICE PRINCIPAL ENABLEMENT CODE ## Name the client application $appName = ‘Exo V2 App’ ## Get information about the Office 365 Exchange Online API. (Get-AzureADServicePrincipal -Filter “AppID eq ‘00000002-0000-0ff1-ce00-000000000000’) $api = (Get-AzureADServicePrincipal -Filter “AppID ## Determine the API permission ID. Where-Object

You’re definitely utilizing PowerShell scripts to automate numerous Office 365 processes if you’re an administrator. It’s improbable, though, that you’re utilizing MFA to connect to Exchange Online through PowerShell for unattended scripts. This indicates that your scripts continue to use basic authentication.

On October 13, 2020, Microsoft intended to eliminate basic authentication from Exchange Online. After then, the plan was pushed back until the second half of 2021.

Admins must redesign their scripts as soon as possible, taking into account the following:

  • Modern authentication must be used in PowerShell scripts while yet allowing them to operate unattended.
  • In Office 365, PowerShell scripts must authenticate securely without the need to exclude a service account from multi-factor authentication.

Previously, current systems could not meet those two requirements. Fortunately, Microsoft has published version 2.0.3-preview of the Exchange Online V2 PowerShell module. The option to employ certificate-based authentication with an Azure AD app was included in this new version.

In this article, you’ll discover how to get ready to utilize the EXO V2 module with app-only contemporary authentication to execute Exchange Online unattended scripts. You’ll discover how to:

  • Create a new app and activate its service principal in Azure Active Directory.
  • Assign API roles and permissions.
  • Make a self-signed certificate and submit it.
  • Authenticate and connect to Exchange Online PowerShell using the app and certificate.

As a result, don’t expect to see a lot of point-and-click instructions in this post. PowerShell will be used for the majority of the walkthrough instructions.

Prerequisites

Make sure you have the following needs in order to follow along correctly.

  • With Global Admin rights, access to an Office 365 tenant. For testing, use a non-production/dev tenant. Consider up for a free Office 365 trial tenancy.
  • Windows PowerShell 5.1 on a Windows PC. This post will be written on a machine running Windows 10 version 1909.
  • The newest AzureAD PowerShell Module should be installed. This article was written using version 2.0.2.106.
  • Notepad++, Atom, Windows PowerShell ISE, or Visual Studio Code are examples of code editors. Use whatever one seems most natural to you.
  • For your test, create a functioning directory. The working directory in this article is C:exo v2 demo.
  • Save the Create-SelfSignedCertificate.ps1 script to your working directory after downloading it. The script will be saved in the working directory C:exo v2 demo in this article.

Using PowerShell to Set Up App-Only Authentication

You may be accustomed to running your PowerShell scripts using a generic account, sometimes known as a service account. In nature, such sort of account is a “shared” account. Anyone with access to that account’s credentials may log in and execute various administrative tasks on your business, which is a security risk.

App-only authentication aims to address this security issue. App-only authentication necessitates the creation of an Azure AD app with a service principal and certain permissions and roles. To authenticate, use a token or a certificate.

Adding API Permissions to an Azure AD Application

To begin, establish a new Azure AD app with the appropriate API access. To begin, launch an elevated Windows PowerShell session (run as administrator) and Connect to Azure Active Directory.

Connect to Azure Active DirectoryConnect to Azure Active Directory

The code below will create a new Exo V2 App app in Azure AD and attach it to the Exchange. The Office 365 Exchange Online API has the ManageAsApp permission.

If you want to give your app a different name, change the value of the $appName variable in the code below. Copy and execute the code in PowerShell.

# CODE TO REGISTER APP, ASSIGN API PERMISSIONS, AND ENABLE SERVICE PRINCIPAL ## Define the client app name $appName = ‘Exo_V2_App’ ## Get the Office 365 Exchange Online API details. $api = (Get-AzureADServicePrincipal -Filter “AppID eq ‘00000002-0000-0ff1-ce00-000000000000′”) ## Get the API permission ID $permission = $api.AppRoles | Where-Object { $_.Value -eq ‘Exchange.ManageAsApp’ } ## Build the API permission object (TYPE: Role = Application, Scope = User) $apiPermission = [Microsoft.Open.AzureAD.Model.RequiredResourceAccess]@{ ResourceAppId = $api.AppId ; ResourceAccess = [Microsoft.Open.AzureAD.Model.ResourceAccess]@{ Id = $permission.Id ; Type = “Role” } } ## Register the new Azure AD App with API Permissions $myApp = New-AzureADApplication -DisplayName $appName -ReplyUrls ‘http://localhost’ -RequiredResourceAccess $apiPermission ## Enable the Service Principal $mySP = New-AzureADServicePrincipal -AppID $myApp.AppID ## Display the new app properties $myApp | Format-List DisplayName,ObjectID,AppID

The code is shown in the video below. The DisplayName, ObjectID, and AppID attributes of the new app will be presented at the end. These attributes are saved in the $myApp variable. The service principal’s property values are stored in the $mySP variable.

Create a new Azure Active Directory app.Create a new Azure Active Directory app.

TIP: Save the attributes of the application for future reference.

Use the command below to export the application’s property values.

“$($appName).csv” $myApp | Export-Csv -NoTypeInformation

Adding an Azure Active Directory Role to the Application

The next step is to assign an Azure AD role to the app’s service principal once it has been created. You’ll need to select what kind of role your app should have.

These are the legitimate supported roles for Exchange Online V2.

  • Company administrator
  • Compliance administrator
  • Security reader
  • Security administrator
  • Helpdesk administrator
  • Exchange Service Administrator
  • Global Reader

Only grant the least privileged role to your script that you believe is suitable. The code below assigns the Exchange Service administrator role to the app’s service principal in this case.

## The role to assign to your app $directoryRole = ‘Exchange Service Administrator’ ## Find the ObjectID of ‘Exchange Service Administrator’ $RoleId = (Get-AzureADDirectoryRole | Where-Object {$_.displayname -eq $directoryRole}).ObjectID ## Add the service principal to the directory role Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose

You should get a result similar to the one displayed in the example below if you execute the command above in PowerShell.

Giving the app an Azure Active Directory roleGiving the app an Azure Active Directory role

Making a self-signed certificate and attaching it to the application

The next step is to create a self-signed certificate and add it to your program. This step will need the Create-SelfSignedCertificate.ps1 script.

The script below will create a self-signed certificate with the subject name of your app, such as Exo V2 App. The certificate is only good for one year.

Update the $certYears value to the desired number of years if you wish to change the certificate’s validity. If you wish to use a different password for the generated certificate (PFX) file, you may alter the $certPassword value.

## Validity of the certificate in years 1 $certYears ## Password for the Certificate (PFX) ‘4mt4G*[email protected]’ is the certificate password. Create-SelfSignedCertificate. -CommonName ps1 $appName ‘ -BeginDate (Get-Date). AddDays(-1) ‘ -FinishDate (Get-Date). AddYears($certYears) ‘ -Force (ConvertTo-SecureString $certPassword -AsPlainText)’-Password (ConvertTo-SecureString $certPassword -AsPlainText

Two files will be produced when you execute the code above in PowerShell, as seen in the sample below.

Create a certificate that is self-signed.Create a certificate that is self-signed.

The next step is to submit your newly generated certificate to your Azure AD app. The code below will find and attach the certificate (.CER) file in your working directory to the Azure AD app. You don’t need to change the code; just copy and execute it in PowerShell.

## Download the certificate (.CER) (Resolve-Path “.$($appName).cer”) $CertificateFilePath Path ## Make a certificate object. $cer = System.Security.Cryptography.X509Certificates.X509Certificate2 New-Object $cer $cer.Import(“$($CertificateFilePath)”) $cer.GetRawCertData $bin () $bin = $cer.GetCertHash $base64Value = [System.Convert]::ToBase64String($bin) () $bin = [System.Convert]::ToBase64String($base64Thumbprint) ## In AzureAD, upload and assign the certificate to the application. -ObjectId $null = New-AzureADApplicationKeyCredential -CustomKeyIdentifier $myApp.ObjectID ‘ -Type AsymmetricX509Cert -Usage Verify’-Value $base64Thumbprint ‘ -StartDate ($cer.NotBefore)’-EndDate ($cer.NotAfter)’$base64Value

If the code above is executed in PowerShell, no output should be expected until an error occurs. When the code is successfully executed, the outcome is shown in the example below.

Adding the certificate to the Azure Active Directory appAdding the certificate to the Azure Active Directory app

Approval of the Application by the Admin

You’re almost finished with your setup. The next step is for a Global Admin to give your Azure AD app permission. This step may be carried out by you or another Global Admin in your company.

From the Azure Active Directory admin center, a Global admin may provide consent. However, PowerShell can also build a consent URL. You may either provide it to the Global admin or use it to grant consent yourself.

This is the format for the consent URL.

https://login.microsoftonline.com/{TenantID}/adminconsent?client id={ApplicationID}

The TenantID value is your Office 365 tenant’s directory ID or confirmed domain. The AppID of the Azure AD application that you previously generated is the value for ApplicationID.

Based on the variables supplied, the code below will construct the consent URL. The consent URL will then be shown on the screen and opened in the default browser on the machine.

## Obtain TenantID $tenantID = $tenantID (Get-AzureADTenantDetail). ObjectID ## Visit this link “https://login.microsoftonline.com/$tenantID/adminconsent?client id=$($myApp.AppId)” $consentURL = “https://login.microsoftonline.com/$tenantID/adminconsent ## Make the consent URL visible. $consentURL ## Use the default browser to access the consent URL. $consentURL -Start-Process

To see what occurs when you execute the code above in PowerShell, look at the example below.

Create a consent URL and provide permission.Create a consent URL and provide permission.

PowerShell Connection to Exchange Online

You must now upload and attach the certificate after establishing the app and giving permissions and roles. You may now use the app’s certificate credentials to login to Exchange Online PowerShell.

The local certificate file (.pfx) and the thumbprint of the certificate put in the current user’s personal certificate store are the two methods to use the certificate credentials.

Using a Local PFX Certificate for Authentication

You’ll need the following information to connect to Exchange Online PowerShell using a local certificate for authentication:

  • Your Azure AD tenant’s Directory ID or confirmed domain.
  • The AppID of the application you already registered.
  • The self-signed PFX certificate’s complete file path.
  • The seld-sign PFX certificate’s password.

Then, in the code below, alter the values of the $tenantID, $appID, $CertificateFilePath, and $pfxPassword variables. Copy the code and execute it in PowerShell after you’ve changed the values of the variables as appropriate.

## Create a tenant ID (directory ID or domain) ‘poshlab.ga’ as $tenantID $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450f (.pfx) ## Get the PFX password using $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’. ‘4mt4G*[email protected]’ as $pfxPassword Connect-ExchangeOnline -CertificateFilePath ## Connect to Exchange Online -CertificatePassword (ConvertTo-SecureString -String $pfxPassword -AsPlainText -Force)’-AppID $CertificateFilePath -Organization $appID $tenantID

The demo below shows that the PowerShell Connection to Exchange Online si successful using the local certificate file authentication.

Using a Local PFX Certificate for AuthenticationUsing a Local PFX Certificate for Authentication

When you examine the code again, you’ll see that the pfx certificate password is visible. For increased protection, you may consider storing the certificate credential in a secret management system.

Using the Certificate Thumbprint for Authentication

This way of authentication is more secure than using a password and a local certificate. You must import the certificate into the Personal certificate store using this approach. Only the thumbprint is required to determine which certificate to use for authentication.

The PFX certificate must first be imported into the Personal certificate repository. This step only has to be done once for the current user.

IMPORT THE PFX CERTIFICATE INTO THE CURRENT PERSONAL CERTIFICATE STORE WITH THIS CODE. ## Get the PFX password $mypwd = Get-Credential -UserName ‘Enter password below’ -Message ‘Enter password below’ ## Set the certificate file path (.pfx) $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’ ## Import the PFX certificate into the personal certificate store of the current user. -CertStoreLocation Cert:CurrentUserMy -Password Import-PfxCertificate -FilePath $CertificateFilePath $mypwd.Password

The demonstration below demonstrates how to import a PFX certificate into your own certificate store.

The PFX certificate is imported.The PFX certificate is imported.

The outcome of the PFX import procedure will be seen as shown above. Make a note of the value of the Thumbprint for future reference.

Your scripts may now use the thumbprint of the certificate to authenticate with Exchange Online PowerShell.

To match your right values, edit the $tenantID, $appID, and $CertificateThumbPrint in the code below. Then, in PowerShell, copy and execute the code.

## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID

If you run the code above in PowerShell, you’ll get something like the example below.

After executing the code in Powershell, this is the output.After executing the code in Powershell, this is the output.

Using App-Only Authentication to Connect and Run Exchange Online PowerShell Scripts

You’ve just been copying and pasting code into PowerShell so far in this tutorial. You should use app-only authentication to execute your PowerShell scripts now that you understand how it works.

The script below connects to Exchange Online PowerShell and authenticates using the certificate thumbprint. The script will then obtain all of the mailboxes accessible once connected. C:exo v2 demoListExoMailbox.ps1 is where the script is stored.

## Clean up Exchange Online Session Get-PSSession | Where-Object {$_.name -like “ExchangeOnline*”} | Remove-PSSession -ErrorAction SilentlyContinue ## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID ## Get All Mailbox Write-Output “Getting all mailboxes” Get-Mailbox -ResultSize Unlimited | Format-Table Name,DisplayName

Run the script in PowerShell once you’ve saved it. The script should automatically connect to Exchange Online and do its purpose. Refer to the findings in the demonstration below.

App-Only Authentication PowerShell ScriptApp-Only Authentication PowerShell Script

Summary

The EXO V2 PowerShell module’s release is a great development. Knowing that Microsoft has opted to remove basic authentication for connecting to Exchange Online through PowerShell, administrators may update their current scripts with this new app-only authentication option.

Implementing EXO V2 app-only authentication, on the other hand, is not without its difficulties.

  • A PFX password is still required when using a local certificate file. You should be able to avoid this password vulnerability problem if you use a credential or secret management approach.
  • In the personal shop, using a certificate gives you extra assurance. However, only the current user has access to the certificate. If you’ve set up a scheduled job to execute the script using UserA’s credentials, the certificate must be imported into UserA’s personal certificate store.
  • Certificates have a time limit. This would need certificate monitoring, renewal, and re-assignment to the Azure AD app. Otherwise, owing to an authentication failure, the script will cease operating.

These disadvantages are outweighed by the advantages of utilizing the new EXO V2 PowerShell module.

In this post, you learnt how to set up app-only authentication for the Exchange Online V2 PowerShell module step by step. You’ve also learned how to use a self-signed certificate to login to Exchange Online PowerShell.

You may now employ app-only certificate-based authentication in your scripts instead of dealing with Exchange Online PowerShell MFA prompts.

If you want to take things a step further, you might use Jenkins or Azure Automation to put everything you’ve learned in this article to the test. Alternatively, you may create your own PowerShell functions and modules.

Thank you for stopping by!

Additional Reading

.Value -eq ‘Exchange.ManageAsApp’ | $permission = $api.AppRoles ## Create the API authorization object (TYPE: Application, Scope: User) [Microsoft.Open.AzureAD.Model] $apiPermission .RequiredResourceAccess] @ ResourceAccess = [Microsoft.Open.AzureAD.Model]; ResourceAppId = $api.AppId .ResourceAccess] @ Type = “Role”; Id = $permission.Id ## Grant API Permissions to the new Azure AD App New-AzureADApplication -DisplayName $myApp ‘http://localhost’ -RequiredResourceAccess $appName -ReplyUrls $apiPermission ## Make the Service Principal active. New-AzureADServicePrincipal -AppID $mySP $myApp.AppID ## Format-List DisplayName,ObjectID,AppID to show the new app properties $myApp

The code is shown in the video below. The DisplayName, ObjectID, and AppID attributes of the new app will be presented at the end. These attributes are saved in the $myApp variable. The service principal’s property values are stored in the $mySP variable.

Create a new Azure Active Directory app.Create a new Azure Active Directory app.

TIP: Save the attributes of the application for future reference.

Use the command below to export the application’s property values.

“$($appName).csv” $myApp | Export-Csv -NoTypeInformation

Adding an Azure Active Directory Role to the Application

The next step is to assign an Azure AD role to the app’s service principal once it has been created. You’ll need to select what kind of role your app should have.

These are the legitimate supported roles for Exchange Online V2.

  • Company administrator
  • Compliance administrator
  • Security reader
  • Security administrator
  • Helpdesk administrator
  • Exchange Service Administrator
  • Global Reader

Only grant the least privileged role to your script that you believe is suitable. The code below assigns the Exchange Service administrator role to the app’s service principal in this case.

## The role to assign to your app $directoryRole = ‘Exchange Service Administrator’ ## Find the ObjectID of ‘Exchange Service Administrator’ $RoleId = (Get-AzureADDirectoryRole | Where-Object {$_.displayname -eq $directoryRole}).ObjectID ## Add the service principal to the directory role Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose

You should get a result similar to the one displayed in the example below if you execute the command above in PowerShell.

Giving the app an Azure Active Directory roleGiving the app an Azure Active Directory role

Making a self-signed certificate and attaching it to the application

The next step is to create a self-signed certificate and add it to your program. This step will need the Create-SelfSignedCertificate.ps1 script.

The script below will create a self-signed certificate with the subject name of your app, such as Exo V2 App. The certificate is only good for one year.

Update the $certYears value to the desired number of years if you wish to change the certificate’s validity. If you wish to use a different password for the generated certificate (PFX) file, you may alter the $certPassword value.

## Validity of the certificate in years 1 $certYears ## Password for the Certificate (PFX) ‘4mt4G*[email protected]’ is the certificate password. Create-SelfSignedCertificate. -CommonName ps1 $appName ‘ -BeginDate (Get-Date). AddDays(-1) ‘ -FinishDate (Get-Date). AddYears($certYears) ‘ -Force (ConvertTo-SecureString $certPassword -AsPlainText)’-Password (ConvertTo-SecureString $certPassword -AsPlainText

Two files will be produced when you execute the code above in PowerShell, as seen in the sample below.

Create a certificate that is self-signed.Create a certificate that is self-signed.

The next step is to submit your newly generated certificate to your Azure AD app. The code below will find and attach the certificate (.CER) file in your working directory to the Azure AD app. You don’t need to change the code; just copy and execute it in PowerShell.

## Download the certificate (.CER) (Resolve-Path “.$($appName).cer”) $CertificateFilePath Path ## Make a certificate object. $cer = System.Security.Cryptography.X509Certificates.X509Certificate2 New-Object $cer $cer.Import(“$($CertificateFilePath)”) $cer.GetRawCertData $bin () $bin = $cer.GetCertHash $base64Value = [System.Convert]::ToBase64String($bin) () $bin = [System.Convert]::ToBase64String($base64Thumbprint) ## In AzureAD, upload and assign the certificate to the application. -ObjectId $null = New-AzureADApplicationKeyCredential -CustomKeyIdentifier $myApp.ObjectID ‘ -Type AsymmetricX509Cert -Usage Verify’-Value $base64Thumbprint ‘ -StartDate ($cer.NotBefore)’-EndDate ($cer.NotAfter)’$base64Value

If the code above is executed in PowerShell, no output should be expected until an error occurs. When the code is successfully executed, the outcome is shown in the example below.

Adding the certificate to the Azure Active Directory appAdding the certificate to the Azure Active Directory app

Approval of the Application by the Admin

You’re almost finished with your setup. The next step is for a Global Admin to give your Azure AD app permission. This step may be carried out by you or another Global Admin in your company.

From the Azure Active Directory admin center, a Global admin may provide consent. However, PowerShell can also build a consent URL. You may either provide it to the Global admin or use it to grant consent yourself.

This is the format for the consent URL.

https://login.microsoftonline.com/{TenantID}/adminconsent?client id={ApplicationID}

The TenantID value is your Office 365 tenant’s directory ID or confirmed domain. The AppID of the Azure AD application that you previously generated is the value for ApplicationID.

Based on the variables supplied, the code below will construct the consent URL. The consent URL will then be shown on the screen and opened in the default browser on the machine.

## Obtain TenantID $tenantID = $tenantID (Get-AzureADTenantDetail). ObjectID ## Visit this link “https://login.microsoftonline.com/$tenantID/adminconsent?client id=$($myApp.AppId)” $consentURL = “https://login.microsoftonline.com/$tenantID/adminconsent ## Make the consent URL visible. $consentURL ## Use the default browser to access the consent URL. $consentURL -Start-Process

To see what occurs when you execute the code above in PowerShell, look at the example below.

Create a consent URL and provide permission.Create a consent URL and provide permission.

PowerShell Connection to Exchange Online

You must now upload and attach the certificate after establishing the app and giving permissions and roles. You may now use the app’s certificate credentials to login to Exchange Online PowerShell.

The local certificate file (.pfx) and the thumbprint of the certificate put in the current user’s personal certificate store are the two methods to use the certificate credentials.

Using a Local PFX Certificate for Authentication

You’ll need the following information to connect to Exchange Online PowerShell using a local certificate for authentication:

  • Your Azure AD tenant’s Directory ID or confirmed domain.
  • The AppID of the application you already registered.
  • The self-signed PFX certificate’s complete file path.
  • The seld-sign PFX certificate’s password.

Then, in the code below, alter the values of the $tenantID, $appID, $CertificateFilePath, and $pfxPassword variables. Copy the code and execute it in PowerShell after you’ve changed the values of the variables as appropriate.

## Create a tenant ID (directory ID or domain) ‘poshlab.ga’ as $tenantID $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450f (.pfx) ## Get the PFX password using $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’. ‘4mt4G*[email protected]’ as $pfxPassword Connect-ExchangeOnline -CertificateFilePath ## Connect to Exchange Online -CertificatePassword (ConvertTo-SecureString -String $pfxPassword -AsPlainText -Force)’-AppID $CertificateFilePath -Organization $appID $tenantID

The demo below shows that the PowerShell Connection to Exchange Online si successful using the local certificate file authentication.

Using a Local PFX Certificate for AuthenticationUsing a Local PFX Certificate for Authentication

When you examine the code again, you’ll see that the pfx certificate password is visible. For increased protection, you may consider storing the certificate credential in a secret management system.

Using the Certificate Thumbprint for Authentication

This way of authentication is more secure than using a password and a local certificate. You must import the certificate into the Personal certificate store using this approach. Only the thumbprint is required to determine which certificate to use for authentication.

The PFX certificate must first be imported into the Personal certificate repository. This step only has to be done once for the current user.

IMPORT THE PFX CERTIFICATE INTO THE CURRENT PERSONAL CERTIFICATE STORE WITH THIS CODE. ## Get the PFX password $mypwd = Get-Credential -UserName ‘Enter password below’ -Message ‘Enter password below’ ## Set the certificate file path (.pfx) $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’ ## Import the PFX certificate into the personal certificate store of the current user. -CertStoreLocation Cert:CurrentUserMy -Password Import-PfxCertificate -FilePath $CertificateFilePath $mypwd.Password

The demonstration below demonstrates how to import a PFX certificate into your own certificate store.

The PFX certificate is imported.The PFX certificate is imported.

The outcome of the PFX import procedure will be seen as shown above. Make a note of the value of the Thumbprint for future reference.

Your scripts may now use the thumbprint of the certificate to authenticate with Exchange Online PowerShell.

To match your right values, edit the $tenantID, $appID, and $CertificateThumbPrint in the code below. Then, in PowerShell, copy and execute the code.

## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID

If you run the code above in PowerShell, you’ll get something like the example below.

After executing the code in Powershell, this is the output.After executing the code in Powershell, this is the output.

Using App-Only Authentication to Connect and Run Exchange Online PowerShell Scripts

You’ve just been copying and pasting code into PowerShell so far in this tutorial. You should use app-only authentication to execute your PowerShell scripts now that you understand how it works.

The script below connects to Exchange Online PowerShell and authenticates using the certificate thumbprint. The script will then obtain all of the mailboxes accessible once connected. C:exo v2 demoListExoMailbox.ps1 is where the script is stored.

## Clean up Exchange Online Session Get-PSSession | Where-Object {$_.name -like “ExchangeOnline*”} | Remove-PSSession -ErrorAction SilentlyContinue ## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID ## Get All Mailbox Write-Output “Getting all mailboxes” Get-Mailbox -ResultSize Unlimited | Format-Table Name,DisplayName

Run the script in PowerShell once you’ve saved it. The script should automatically connect to Exchange Online and do its purpose. Refer to the findings in the demonstration below.

App-Only Authentication PowerShell ScriptApp-Only Authentication PowerShell Script

Summary

The EXO V2 PowerShell module’s release is a great development. Knowing that Microsoft has opted to remove basic authentication for connecting to Exchange Online through PowerShell, administrators may update their current scripts with this new app-only authentication option.

Implementing EXO V2 app-only authentication, on the other hand, is not without its difficulties.

  • A PFX password is still required when using a local certificate file. You should be able to avoid this password vulnerability problem if you use a credential or secret management approach.
  • In the personal shop, using a certificate gives you extra assurance. However, only the current user has access to the certificate. If you’ve set up a scheduled job to execute the script using UserA’s credentials, the certificate must be imported into UserA’s personal certificate store.
  • Certificates have a time limit. This would need certificate monitoring, renewal, and re-assignment to the Azure AD app. Otherwise, owing to an authentication failure, the script will cease operating.

These disadvantages are outweighed by the advantages of utilizing the new EXO V2 PowerShell module.

In this post, you learnt how to set up app-only authentication for the Exchange Online V2 PowerShell module step by step. You’ve also learned how to use a self-signed certificate to login to Exchange Online PowerShell.

You may now employ app-only certificate-based authentication in your scripts instead of dealing with Exchange Online PowerShell MFA prompts.

If you want to take things a step further, you might use Jenkins or Azure Automation to put everything you’ve learned in this article to the test. Alternatively, you may create your own PowerShell functions and modules.

Thank you for stopping by!

Additional Reading

.displayname -eq $directoryRole) $RoleId = (Get-AzureADDirectoryRole | Where-Object

You’re definitely utilizing PowerShell scripts to automate numerous Office 365 processes if you’re an administrator. It’s improbable, though, that you’re utilizing MFA to connect to Exchange Online through PowerShell for unattended scripts. This indicates that your scripts continue to use basic authentication.

On October 13, 2020, Microsoft intended to eliminate basic authentication from Exchange Online. After then, the plan was pushed back until the second half of 2021.

Admins must redesign their scripts as soon as possible, taking into account the following:

  • Modern authentication must be used in PowerShell scripts while yet allowing them to operate unattended.
  • In Office 365, PowerShell scripts must authenticate securely without the need to exclude a service account from multi-factor authentication.

Previously, current systems could not meet those two requirements. Fortunately, Microsoft has published version 2.0.3-preview of the Exchange Online V2 PowerShell module. The option to employ certificate-based authentication with an Azure AD app was included in this new version.

In this article, you’ll discover how to get ready to utilize the EXO V2 module with app-only contemporary authentication to execute Exchange Online unattended scripts. You’ll discover how to:

  • Create a new app and activate its service principal in Azure Active Directory.
  • Assign API roles and permissions.
  • Make a self-signed certificate and submit it.
  • Authenticate and connect to Exchange Online PowerShell using the app and certificate.

As a result, don’t expect to see a lot of point-and-click instructions in this post. PowerShell will be used for the majority of the walkthrough instructions.

Prerequisites

Make sure you have the following needs in order to follow along correctly.

  • With Global Admin rights, access to an Office 365 tenant. For testing, use a non-production/dev tenant. Consider up for a free Office 365 trial tenancy.
  • Windows PowerShell 5.1 on a Windows PC. This post will be written on a machine running Windows 10 version 1909.
  • The newest AzureAD PowerShell Module should be installed. This article was written using version 2.0.2.106.
  • Notepad++, Atom, Windows PowerShell ISE, or Visual Studio Code are examples of code editors. Use whatever one seems most natural to you.
  • For your test, create a functioning directory. The working directory in this article is C:exo v2 demo.
  • Save the Create-SelfSignedCertificate.ps1 script to your working directory after downloading it. The script will be saved in the working directory C:exo v2 demo in this article.

Using PowerShell to Set Up App-Only Authentication

You may be accustomed to running your PowerShell scripts using a generic account, sometimes known as a service account. In nature, such sort of account is a “shared” account. Anyone with access to that account’s credentials may log in and execute various administrative tasks on your business, which is a security risk.

App-only authentication aims to address this security issue. App-only authentication necessitates the creation of an Azure AD app with a service principal and certain permissions and roles. To authenticate, use a token or a certificate.

Adding API Permissions to an Azure AD Application

To begin, establish a new Azure AD app with the appropriate API access. To begin, launch an elevated Windows PowerShell session (run as administrator) and Connect to Azure Active Directory.

Connect to Azure Active DirectoryConnect to Azure Active Directory

The code below will create a new Exo V2 App app in Azure AD and attach it to the Exchange. The Office 365 Exchange Online API has the ManageAsApp permission.

If you want to give your app a different name, change the value of the $appName variable in the code below. Copy and execute the code in PowerShell.

# APP REGISTRATION, API PERMISSIONS, AND SERVICE PRINCIPAL ENABLEMENT CODE ## Name the client application $appName = ‘Exo V2 App’ ## Get information about the Office 365 Exchange Online API. (Get-AzureADServicePrincipal -Filter “AppID eq ‘00000002-0000-0ff1-ce00-000000000000’) $api = (Get-AzureADServicePrincipal -Filter “AppID ## Determine the API permission ID. Where-Object

You’re definitely utilizing PowerShell scripts to automate numerous Office 365 processes if you’re an administrator. It’s improbable, though, that you’re utilizing MFA to connect to Exchange Online through PowerShell for unattended scripts. This indicates that your scripts continue to use basic authentication.

On October 13, 2020, Microsoft intended to eliminate basic authentication from Exchange Online. After then, the plan was pushed back until the second half of 2021.

Admins must redesign their scripts as soon as possible, taking into account the following:

  • Modern authentication must be used in PowerShell scripts while yet allowing them to operate unattended.
  • In Office 365, PowerShell scripts must authenticate securely without the need to exclude a service account from multi-factor authentication.

Previously, current systems could not meet those two requirements. Fortunately, Microsoft has published version 2.0.3-preview of the Exchange Online V2 PowerShell module. The option to employ certificate-based authentication with an Azure AD app was included in this new version.

In this article, you’ll discover how to get ready to utilize the EXO V2 module with app-only contemporary authentication to execute Exchange Online unattended scripts. You’ll discover how to:

  • Create a new app and activate its service principal in Azure Active Directory.
  • Assign API roles and permissions.
  • Make a self-signed certificate and submit it.
  • Authenticate and connect to Exchange Online PowerShell using the app and certificate.

As a result, don’t expect to see a lot of point-and-click instructions in this post. PowerShell will be used for the majority of the walkthrough instructions.

Prerequisites

Make sure you have the following needs in order to follow along correctly.

  • With Global Admin rights, access to an Office 365 tenant. For testing, use a non-production/dev tenant. Consider up for a free Office 365 trial tenancy.
  • Windows PowerShell 5.1 on a Windows PC. This post will be written on a machine running Windows 10 version 1909.
  • The newest AzureAD PowerShell Module should be installed. This article was written using version 2.0.2.106.
  • Notepad++, Atom, Windows PowerShell ISE, or Visual Studio Code are examples of code editors. Use whatever one seems most natural to you.
  • For your test, create a functioning directory. The working directory in this article is C:exo v2 demo.
  • Save the Create-SelfSignedCertificate.ps1 script to your working directory after downloading it. The script will be saved in the working directory C:exo v2 demo in this article.

Using PowerShell to Set Up App-Only Authentication

You may be accustomed to running your PowerShell scripts using a generic account, sometimes known as a service account. In nature, such sort of account is a “shared” account. Anyone with access to that account’s credentials may log in and execute various administrative tasks on your business, which is a security risk.

App-only authentication aims to address this security issue. App-only authentication necessitates the creation of an Azure AD app with a service principal and certain permissions and roles. To authenticate, use a token or a certificate.

Adding API Permissions to an Azure AD Application

To begin, establish a new Azure AD app with the appropriate API access. To begin, launch an elevated Windows PowerShell session (run as administrator) and Connect to Azure Active Directory.

Connect to Azure Active DirectoryConnect to Azure Active Directory

The code below will create a new Exo V2 App app in Azure AD and attach it to the Exchange. The Office 365 Exchange Online API has the ManageAsApp permission.

If you want to give your app a different name, change the value of the $appName variable in the code below. Copy and execute the code in PowerShell.

# CODE TO REGISTER APP, ASSIGN API PERMISSIONS, AND ENABLE SERVICE PRINCIPAL ## Define the client app name $appName = ‘Exo_V2_App’ ## Get the Office 365 Exchange Online API details. $api = (Get-AzureADServicePrincipal -Filter “AppID eq ‘00000002-0000-0ff1-ce00-000000000000′”) ## Get the API permission ID $permission = $api.AppRoles | Where-Object { $_.Value -eq ‘Exchange.ManageAsApp’ } ## Build the API permission object (TYPE: Role = Application, Scope = User) $apiPermission = [Microsoft.Open.AzureAD.Model.RequiredResourceAccess]@{ ResourceAppId = $api.AppId ; ResourceAccess = [Microsoft.Open.AzureAD.Model.ResourceAccess]@{ Id = $permission.Id ; Type = “Role” } } ## Register the new Azure AD App with API Permissions $myApp = New-AzureADApplication -DisplayName $appName -ReplyUrls ‘http://localhost’ -RequiredResourceAccess $apiPermission ## Enable the Service Principal $mySP = New-AzureADServicePrincipal -AppID $myApp.AppID ## Display the new app properties $myApp | Format-List DisplayName,ObjectID,AppID

The code is shown in the video below. The DisplayName, ObjectID, and AppID attributes of the new app will be presented at the end. These attributes are saved in the $myApp variable. The service principal’s property values are stored in the $mySP variable.

Create a new Azure Active Directory app.Create a new Azure Active Directory app.

TIP: Save the attributes of the application for future reference.

Use the command below to export the application’s property values.

“$($appName).csv” $myApp | Export-Csv -NoTypeInformation

Adding an Azure Active Directory Role to the Application

The next step is to assign an Azure AD role to the app’s service principal once it has been created. You’ll need to select what kind of role your app should have.

These are the legitimate supported roles for Exchange Online V2.

  • Company administrator
  • Compliance administrator
  • Security reader
  • Security administrator
  • Helpdesk administrator
  • Exchange Service Administrator
  • Global Reader

Only grant the least privileged role to your script that you believe is suitable. The code below assigns the Exchange Service administrator role to the app’s service principal in this case.

## The role to assign to your app $directoryRole = ‘Exchange Service Administrator’ ## Find the ObjectID of ‘Exchange Service Administrator’ $RoleId = (Get-AzureADDirectoryRole | Where-Object {$_.displayname -eq $directoryRole}).ObjectID ## Add the service principal to the directory role Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose

You should get a result similar to the one displayed in the example below if you execute the command above in PowerShell.

Giving the app an Azure Active Directory roleGiving the app an Azure Active Directory role

Making a self-signed certificate and attaching it to the application

The next step is to create a self-signed certificate and add it to your program. This step will need the Create-SelfSignedCertificate.ps1 script.

The script below will create a self-signed certificate with the subject name of your app, such as Exo V2 App. The certificate is only good for one year.

Update the $certYears value to the desired number of years if you wish to change the certificate’s validity. If you wish to use a different password for the generated certificate (PFX) file, you may alter the $certPassword value.

## Validity of the certificate in years 1 $certYears ## Password for the Certificate (PFX) ‘4mt4G*[email protected]’ is the certificate password. Create-SelfSignedCertificate. -CommonName ps1 $appName ‘ -BeginDate (Get-Date). AddDays(-1) ‘ -FinishDate (Get-Date). AddYears($certYears) ‘ -Force (ConvertTo-SecureString $certPassword -AsPlainText)’-Password (ConvertTo-SecureString $certPassword -AsPlainText

Two files will be produced when you execute the code above in PowerShell, as seen in the sample below.

Create a certificate that is self-signed.Create a certificate that is self-signed.

The next step is to submit your newly generated certificate to your Azure AD app. The code below will find and attach the certificate (.CER) file in your working directory to the Azure AD app. You don’t need to change the code; just copy and execute it in PowerShell.

## Download the certificate (.CER) (Resolve-Path “.$($appName).cer”) $CertificateFilePath Path ## Make a certificate object. $cer = System.Security.Cryptography.X509Certificates.X509Certificate2 New-Object $cer $cer.Import(“$($CertificateFilePath)”) $cer.GetRawCertData $bin () $bin = $cer.GetCertHash $base64Value = [System.Convert]::ToBase64String($bin) () $bin = [System.Convert]::ToBase64String($base64Thumbprint) ## In AzureAD, upload and assign the certificate to the application. -ObjectId $null = New-AzureADApplicationKeyCredential -CustomKeyIdentifier $myApp.ObjectID ‘ -Type AsymmetricX509Cert -Usage Verify’-Value $base64Thumbprint ‘ -StartDate ($cer.NotBefore)’-EndDate ($cer.NotAfter)’$base64Value

If the code above is executed in PowerShell, no output should be expected until an error occurs. When the code is successfully executed, the outcome is shown in the example below.

Adding the certificate to the Azure Active Directory appAdding the certificate to the Azure Active Directory app

Approval of the Application by the Admin

You’re almost finished with your setup. The next step is for a Global Admin to give your Azure AD app permission. This step may be carried out by you or another Global Admin in your company.

From the Azure Active Directory admin center, a Global admin may provide consent. However, PowerShell can also build a consent URL. You may either provide it to the Global admin or use it to grant consent yourself.

This is the format for the consent URL.

https://login.microsoftonline.com/{TenantID}/adminconsent?client id={ApplicationID}

The TenantID value is your Office 365 tenant’s directory ID or confirmed domain. The AppID of the Azure AD application that you previously generated is the value for ApplicationID.

Based on the variables supplied, the code below will construct the consent URL. The consent URL will then be shown on the screen and opened in the default browser on the machine.

## Obtain TenantID $tenantID = $tenantID (Get-AzureADTenantDetail). ObjectID ## Visit this link “https://login.microsoftonline.com/$tenantID/adminconsent?client id=$($myApp.AppId)” $consentURL = “https://login.microsoftonline.com/$tenantID/adminconsent ## Make the consent URL visible. $consentURL ## Use the default browser to access the consent URL. $consentURL -Start-Process

To see what occurs when you execute the code above in PowerShell, look at the example below.

Create a consent URL and provide permission.Create a consent URL and provide permission.

PowerShell Connection to Exchange Online

You must now upload and attach the certificate after establishing the app and giving permissions and roles. You may now use the app’s certificate credentials to login to Exchange Online PowerShell.

The local certificate file (.pfx) and the thumbprint of the certificate put in the current user’s personal certificate store are the two methods to use the certificate credentials.

Using a Local PFX Certificate for Authentication

You’ll need the following information to connect to Exchange Online PowerShell using a local certificate for authentication:

  • Your Azure AD tenant’s Directory ID or confirmed domain.
  • The AppID of the application you already registered.
  • The self-signed PFX certificate’s complete file path.
  • The seld-sign PFX certificate’s password.

Then, in the code below, alter the values of the $tenantID, $appID, $CertificateFilePath, and $pfxPassword variables. Copy the code and execute it in PowerShell after you’ve changed the values of the variables as appropriate.

## Create a tenant ID (directory ID or domain) ‘poshlab.ga’ as $tenantID $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450f (.pfx) ## Get the PFX password using $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’. ‘4mt4G*[email protected]’ as $pfxPassword Connect-ExchangeOnline -CertificateFilePath ## Connect to Exchange Online -CertificatePassword (ConvertTo-SecureString -String $pfxPassword -AsPlainText -Force)’-AppID $CertificateFilePath -Organization $appID $tenantID

The demo below shows that the PowerShell Connection to Exchange Online si successful using the local certificate file authentication.

Using a Local PFX Certificate for AuthenticationUsing a Local PFX Certificate for Authentication

When you examine the code again, you’ll see that the pfx certificate password is visible. For increased protection, you may consider storing the certificate credential in a secret management system.

Using the Certificate Thumbprint for Authentication

This way of authentication is more secure than using a password and a local certificate. You must import the certificate into the Personal certificate store using this approach. Only the thumbprint is required to determine which certificate to use for authentication.

The PFX certificate must first be imported into the Personal certificate repository. This step only has to be done once for the current user.

IMPORT THE PFX CERTIFICATE INTO THE CURRENT PERSONAL CERTIFICATE STORE WITH THIS CODE. ## Get the PFX password $mypwd = Get-Credential -UserName ‘Enter password below’ -Message ‘Enter password below’ ## Set the certificate file path (.pfx) $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’ ## Import the PFX certificate into the personal certificate store of the current user. -CertStoreLocation Cert:CurrentUserMy -Password Import-PfxCertificate -FilePath $CertificateFilePath $mypwd.Password

The demonstration below demonstrates how to import a PFX certificate into your own certificate store.

The PFX certificate is imported.The PFX certificate is imported.

The outcome of the PFX import procedure will be seen as shown above. Make a note of the value of the Thumbprint for future reference.

Your scripts may now use the thumbprint of the certificate to authenticate with Exchange Online PowerShell.

To match your right values, edit the $tenantID, $appID, and $CertificateThumbPrint in the code below. Then, in PowerShell, copy and execute the code.

## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID

If you run the code above in PowerShell, you’ll get something like the example below.

After executing the code in Powershell, this is the output.After executing the code in Powershell, this is the output.

Using App-Only Authentication to Connect and Run Exchange Online PowerShell Scripts

You’ve just been copying and pasting code into PowerShell so far in this tutorial. You should use app-only authentication to execute your PowerShell scripts now that you understand how it works.

The script below connects to Exchange Online PowerShell and authenticates using the certificate thumbprint. The script will then obtain all of the mailboxes accessible once connected. C:exo v2 demoListExoMailbox.ps1 is where the script is stored.

## Clean up Exchange Online Session Get-PSSession | Where-Object {$_.name -like “ExchangeOnline*”} | Remove-PSSession -ErrorAction SilentlyContinue ## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID ## Get All Mailbox Write-Output “Getting all mailboxes” Get-Mailbox -ResultSize Unlimited | Format-Table Name,DisplayName

Run the script in PowerShell once you’ve saved it. The script should automatically connect to Exchange Online and do its purpose. Refer to the findings in the demonstration below.

App-Only Authentication PowerShell ScriptApp-Only Authentication PowerShell Script

Summary

The EXO V2 PowerShell module’s release is a great development. Knowing that Microsoft has opted to remove basic authentication for connecting to Exchange Online through PowerShell, administrators may update their current scripts with this new app-only authentication option.

Implementing EXO V2 app-only authentication, on the other hand, is not without its difficulties.

  • A PFX password is still required when using a local certificate file. You should be able to avoid this password vulnerability problem if you use a credential or secret management approach.
  • In the personal shop, using a certificate gives you extra assurance. However, only the current user has access to the certificate. If you’ve set up a scheduled job to execute the script using UserA’s credentials, the certificate must be imported into UserA’s personal certificate store.
  • Certificates have a time limit. This would need certificate monitoring, renewal, and re-assignment to the Azure AD app. Otherwise, owing to an authentication failure, the script will cease operating.

These disadvantages are outweighed by the advantages of utilizing the new EXO V2 PowerShell module.

In this post, you learnt how to set up app-only authentication for the Exchange Online V2 PowerShell module step by step. You’ve also learned how to use a self-signed certificate to login to Exchange Online PowerShell.

You may now employ app-only certificate-based authentication in your scripts instead of dealing with Exchange Online PowerShell MFA prompts.

If you want to take things a step further, you might use Jenkins or Azure Automation to put everything you’ve learned in this article to the test. Alternatively, you may create your own PowerShell functions and modules.

Thank you for stopping by!

Additional Reading

.Value -eq ‘Exchange.ManageAsApp’ | $permission = $api.AppRoles ## Create the API authorization object (TYPE: Application, Scope: User) [Microsoft.Open.AzureAD.Model] $apiPermission .RequiredResourceAccess] @ ResourceAccess = [Microsoft.Open.AzureAD.Model]; ResourceAppId = $api.AppId .ResourceAccess] @ Type = “Role”; Id = $permission.Id ## Grant API Permissions to the new Azure AD App New-AzureADApplication -DisplayName $myApp ‘http://localhost’ -RequiredResourceAccess $appName -ReplyUrls $apiPermission ## Make the Service Principal active. New-AzureADServicePrincipal -AppID $mySP $myApp.AppID ## Format-List DisplayName,ObjectID,AppID to show the new app properties $myApp

The code is shown in the video below. The DisplayName, ObjectID, and AppID attributes of the new app will be presented at the end. These attributes are saved in the $myApp variable. The service principal’s property values are stored in the $mySP variable.

Create a new Azure Active Directory app.Create a new Azure Active Directory app.

TIP: Save the attributes of the application for future reference.

Use the command below to export the application’s property values.

“$($appName).csv” $myApp | Export-Csv -NoTypeInformation

Adding an Azure Active Directory Role to the Application

The next step is to assign an Azure AD role to the app’s service principal once it has been created. You’ll need to select what kind of role your app should have.

These are the legitimate supported roles for Exchange Online V2.

  • Company administrator
  • Compliance administrator
  • Security reader
  • Security administrator
  • Helpdesk administrator
  • Exchange Service Administrator
  • Global Reader

Only grant the least privileged role to your script that you believe is suitable. The code below assigns the Exchange Service administrator role to the app’s service principal in this case.

## The role to assign to your app $directoryRole = ‘Exchange Service Administrator’ ## Find the ObjectID of ‘Exchange Service Administrator’ $RoleId = (Get-AzureADDirectoryRole | Where-Object {$_.displayname -eq $directoryRole}).ObjectID ## Add the service principal to the directory role Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose

You should get a result similar to the one displayed in the example below if you execute the command above in PowerShell.

Giving the app an Azure Active Directory roleGiving the app an Azure Active Directory role

Making a self-signed certificate and attaching it to the application

The next step is to create a self-signed certificate and add it to your program. This step will need the Create-SelfSignedCertificate.ps1 script.

The script below will create a self-signed certificate with the subject name of your app, such as Exo V2 App. The certificate is only good for one year.

Update the $certYears value to the desired number of years if you wish to change the certificate’s validity. If you wish to use a different password for the generated certificate (PFX) file, you may alter the $certPassword value.

## Validity of the certificate in years 1 $certYears ## Password for the Certificate (PFX) ‘4mt4G*[email protected]’ is the certificate password. Create-SelfSignedCertificate. -CommonName ps1 $appName ‘ -BeginDate (Get-Date). AddDays(-1) ‘ -FinishDate (Get-Date). AddYears($certYears) ‘ -Force (ConvertTo-SecureString $certPassword -AsPlainText)’-Password (ConvertTo-SecureString $certPassword -AsPlainText

Two files will be produced when you execute the code above in PowerShell, as seen in the sample below.

Create a certificate that is self-signed.Create a certificate that is self-signed.

The next step is to submit your newly generated certificate to your Azure AD app. The code below will find and attach the certificate (.CER) file in your working directory to the Azure AD app. You don’t need to change the code; just copy and execute it in PowerShell.

## Download the certificate (.CER) (Resolve-Path “.$($appName).cer”) $CertificateFilePath Path ## Make a certificate object. $cer = System.Security.Cryptography.X509Certificates.X509Certificate2 New-Object $cer $cer.Import(“$($CertificateFilePath)”) $cer.GetRawCertData $bin () $bin = $cer.GetCertHash $base64Value = [System.Convert]::ToBase64String($bin) () $bin = [System.Convert]::ToBase64String($base64Thumbprint) ## In AzureAD, upload and assign the certificate to the application. -ObjectId $null = New-AzureADApplicationKeyCredential -CustomKeyIdentifier $myApp.ObjectID ‘ -Type AsymmetricX509Cert -Usage Verify’-Value $base64Thumbprint ‘ -StartDate ($cer.NotBefore)’-EndDate ($cer.NotAfter)’$base64Value

If the code above is executed in PowerShell, no output should be expected until an error occurs. When the code is successfully executed, the outcome is shown in the example below.

Adding the certificate to the Azure Active Directory appAdding the certificate to the Azure Active Directory app

Approval of the Application by the Admin

You’re almost finished with your setup. The next step is for a Global Admin to give your Azure AD app permission. This step may be carried out by you or another Global Admin in your company.

From the Azure Active Directory admin center, a Global admin may provide consent. However, PowerShell can also build a consent URL. You may either provide it to the Global admin or use it to grant consent yourself.

This is the format for the consent URL.

https://login.microsoftonline.com/{TenantID}/adminconsent?client id={ApplicationID}

The TenantID value is your Office 365 tenant’s directory ID or confirmed domain. The AppID of the Azure AD application that you previously generated is the value for ApplicationID.

Based on the variables supplied, the code below will construct the consent URL. The consent URL will then be shown on the screen and opened in the default browser on the machine.

## Obtain TenantID $tenantID = $tenantID (Get-AzureADTenantDetail). ObjectID ## Visit this link “https://login.microsoftonline.com/$tenantID/adminconsent?client id=$($myApp.AppId)” $consentURL = “https://login.microsoftonline.com/$tenantID/adminconsent ## Make the consent URL visible. $consentURL ## Use the default browser to access the consent URL. $consentURL -Start-Process

To see what occurs when you execute the code above in PowerShell, look at the example below.

Create a consent URL and provide permission.Create a consent URL and provide permission.

PowerShell Connection to Exchange Online

You must now upload and attach the certificate after establishing the app and giving permissions and roles. You may now use the app’s certificate credentials to login to Exchange Online PowerShell.

The local certificate file (.pfx) and the thumbprint of the certificate put in the current user’s personal certificate store are the two methods to use the certificate credentials.

Using a Local PFX Certificate for Authentication

You’ll need the following information to connect to Exchange Online PowerShell using a local certificate for authentication:

  • Your Azure AD tenant’s Directory ID or confirmed domain.
  • The AppID of the application you already registered.
  • The self-signed PFX certificate’s complete file path.
  • The seld-sign PFX certificate’s password.

Then, in the code below, alter the values of the $tenantID, $appID, $CertificateFilePath, and $pfxPassword variables. Copy the code and execute it in PowerShell after you’ve changed the values of the variables as appropriate.

## Create a tenant ID (directory ID or domain) ‘poshlab.ga’ as $tenantID $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450f (.pfx) ## Get the PFX password using $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’. ‘4mt4G*[email protected]’ as $pfxPassword Connect-ExchangeOnline -CertificateFilePath ## Connect to Exchange Online -CertificatePassword (ConvertTo-SecureString -String $pfxPassword -AsPlainText -Force)’-AppID $CertificateFilePath -Organization $appID $tenantID

The demo below shows that the PowerShell Connection to Exchange Online si successful using the local certificate file authentication.

Using a Local PFX Certificate for AuthenticationUsing a Local PFX Certificate for Authentication

When you examine the code again, you’ll see that the pfx certificate password is visible. For increased protection, you may consider storing the certificate credential in a secret management system.

Using the Certificate Thumbprint for Authentication

This way of authentication is more secure than using a password and a local certificate. You must import the certificate into the Personal certificate store using this approach. Only the thumbprint is required to determine which certificate to use for authentication.

The PFX certificate must first be imported into the Personal certificate repository. This step only has to be done once for the current user.

IMPORT THE PFX CERTIFICATE INTO THE CURRENT PERSONAL CERTIFICATE STORE WITH THIS CODE. ## Get the PFX password $mypwd = Get-Credential -UserName ‘Enter password below’ -Message ‘Enter password below’ ## Set the certificate file path (.pfx) $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’ ## Import the PFX certificate into the personal certificate store of the current user. -CertStoreLocation Cert:CurrentUserMy -Password Import-PfxCertificate -FilePath $CertificateFilePath $mypwd.Password

The demonstration below demonstrates how to import a PFX certificate into your own certificate store.

The PFX certificate is imported.The PFX certificate is imported.

The outcome of the PFX import procedure will be seen as shown above. Make a note of the value of the Thumbprint for future reference.

Your scripts may now use the thumbprint of the certificate to authenticate with Exchange Online PowerShell.

To match your right values, edit the $tenantID, $appID, and $CertificateThumbPrint in the code below. Then, in PowerShell, copy and execute the code.

## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID

If you run the code above in PowerShell, you’ll get something like the example below.

After executing the code in Powershell, this is the output.After executing the code in Powershell, this is the output.

Using App-Only Authentication to Connect and Run Exchange Online PowerShell Scripts

You’ve just been copying and pasting code into PowerShell so far in this tutorial. You should use app-only authentication to execute your PowerShell scripts now that you understand how it works.

The script below connects to Exchange Online PowerShell and authenticates using the certificate thumbprint. The script will then obtain all of the mailboxes accessible once connected. C:exo v2 demoListExoMailbox.ps1 is where the script is stored.

## Clean up Exchange Online Session Get-PSSession | Where-Object {$_.name -like “ExchangeOnline*”} | Remove-PSSession -ErrorAction SilentlyContinue ## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID ## Get All Mailbox Write-Output “Getting all mailboxes” Get-Mailbox -ResultSize Unlimited | Format-Table Name,DisplayName

Run the script in PowerShell once you’ve saved it. The script should automatically connect to Exchange Online and do its purpose. Refer to the findings in the demonstration below.

App-Only Authentication PowerShell ScriptApp-Only Authentication PowerShell Script

Summary

The EXO V2 PowerShell module’s release is a great development. Knowing that Microsoft has opted to remove basic authentication for connecting to Exchange Online through PowerShell, administrators may update their current scripts with this new app-only authentication option.

Implementing EXO V2 app-only authentication, on the other hand, is not without its difficulties.

  • A PFX password is still required when using a local certificate file. You should be able to avoid this password vulnerability problem if you use a credential or secret management approach.
  • In the personal shop, using a certificate gives you extra assurance. However, only the current user has access to the certificate. If you’ve set up a scheduled job to execute the script using UserA’s credentials, the certificate must be imported into UserA’s personal certificate store.
  • Certificates have a time limit. This would need certificate monitoring, renewal, and re-assignment to the Azure AD app. Otherwise, owing to an authentication failure, the script will cease operating.

These disadvantages are outweighed by the advantages of utilizing the new EXO V2 PowerShell module.

In this post, you learnt how to set up app-only authentication for the Exchange Online V2 PowerShell module step by step. You’ve also learned how to use a self-signed certificate to login to Exchange Online PowerShell.

You may now employ app-only certificate-based authentication in your scripts instead of dealing with Exchange Online PowerShell MFA prompts.

If you want to take things a step further, you might use Jenkins or Azure Automation to put everything you’ve learned in this article to the test. Alternatively, you may create your own PowerShell functions and modules.

Thank you for stopping by!

Additional Reading

.displayname ObjectID ## Assign the directory role to the service principal. ObjectId $RoleId -RefObjectId $mySP.ObjectID -Verbose Add-AzureADDirectoryRoleMember

You should get a result similar to the one displayed in the example below if you execute the command above in PowerShell.

Giving the app an Azure Active Directory roleGiving the app an Azure Active Directory role

Making a self-signed certificate and attaching it to the application

The next step is to create a self-signed certificate and add it to your program. This step will need the Create-SelfSignedCertificate.ps1 script.

The script below will create a self-signed certificate with the subject name of your app, such as Exo V2 App. The certificate is only good for one year.

Update the $certYears value to the desired number of years if you wish to change the certificate’s validity. If you wish to use a different password for the generated certificate (PFX) file, you may alter the $certPassword value.

## Validity of the certificate in years 1 $certYears ## Password for the Certificate (PFX) ‘4mt4G*[email protected]’ is the certificate password. Create-SelfSignedCertificate. -CommonName ps1 $appName ‘ -BeginDate (Get-Date). AddDays(-1) ‘ -FinishDate (Get-Date). AddYears($certYears) ‘ -Force (ConvertTo-SecureString $certPassword -AsPlainText)’-Password (ConvertTo-SecureString $certPassword -AsPlainText

Two files will be produced when you execute the code above in PowerShell, as seen in the sample below.

Create a certificate that is self-signed.Create a certificate that is self-signed.

The next step is to submit your newly generated certificate to your Azure AD app. The code below will find and attach the certificate (.CER) file in your working directory to the Azure AD app. You don’t need to change the code; just copy and execute it in PowerShell.

## Download the certificate (.CER) (Resolve-Path “.$($appName).cer”) $CertificateFilePath Path ## Make a certificate object. $cer = System.Security.Cryptography.X509Certificates.X509Certificate2 New-Object $cer $cer.Import(“$($CertificateFilePath)”) $cer.GetRawCertData $bin () $bin = $cer.GetCertHash $base64Value = [System.Convert]::ToBase64String($bin) () $bin = [System.Convert]::ToBase64String($base64Thumbprint) ## In AzureAD, upload and assign the certificate to the application. -ObjectId $null = New-AzureADApplicationKeyCredential -CustomKeyIdentifier $myApp.ObjectID ‘ -Type AsymmetricX509Cert -Usage Verify’-Value $base64Thumbprint ‘ -StartDate ($cer.NotBefore)’-EndDate ($cer.NotAfter)’$base64Value

If the code above is executed in PowerShell, no output should be expected until an error occurs. When the code is successfully executed, the outcome is shown in the example below.

Adding the certificate to the Azure Active Directory appAdding the certificate to the Azure Active Directory app

Approval of the Application by the Admin

You’re almost finished with your setup. The next step is for a Global Admin to give your Azure AD app permission. This step may be carried out by you or another Global Admin in your company.

From the Azure Active Directory admin center, a Global admin may provide consent. However, PowerShell can also build a consent URL. You may either provide it to the Global admin or use it to grant consent yourself.

This is the format for the consent URL.

https://login.microsoftonline.com/{TenantID}/adminconsent?client id={ApplicationID}

The TenantID value is your Office 365 tenant’s directory ID or confirmed domain. The AppID of the Azure AD application that you previously generated is the value for ApplicationID.

Based on the variables supplied, the code below will construct the consent URL. The consent URL will then be shown on the screen and opened in the default browser on the machine.

## Obtain TenantID $tenantID = $tenantID (Get-AzureADTenantDetail). ObjectID ## Visit this link “https://login.microsoftonline.com/$tenantID/adminconsent?client id=$($myApp.AppId)” $consentURL = “https://login.microsoftonline.com/$tenantID/adminconsent ## Make the consent URL visible. $consentURL ## Use the default browser to access the consent URL. $consentURL -Start-Process

To see what occurs when you execute the code above in PowerShell, look at the example below.

Create a consent URL and provide permission.Create a consent URL and provide permission.

PowerShell Connection to Exchange Online

You must now upload and attach the certificate after establishing the app and giving permissions and roles. You may now use the app’s certificate credentials to login to Exchange Online PowerShell.

The local certificate file (.pfx) and the thumbprint of the certificate put in the current user’s personal certificate store are the two methods to use the certificate credentials.

Using a Local PFX Certificate for Authentication

You’ll need the following information to connect to Exchange Online PowerShell using a local certificate for authentication:

  • Your Azure AD tenant’s Directory ID or confirmed domain.
  • The AppID of the application you already registered.
  • The self-signed PFX certificate’s complete file path.
  • The seld-sign PFX certificate’s password.

Then, in the code below, alter the values of the $tenantID, $appID, $CertificateFilePath, and $pfxPassword variables. Copy the code and execute it in PowerShell after you’ve changed the values of the variables as appropriate.

## Create a tenant ID (directory ID or domain) ‘poshlab.ga’ as $tenantID $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450f (.pfx) ## Get the PFX password using $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’. ‘4mt4G*[email protected]’ as $pfxPassword Connect-ExchangeOnline -CertificateFilePath ## Connect to Exchange Online -CertificatePassword (ConvertTo-SecureString -String $pfxPassword -AsPlainText -Force)’-AppID $CertificateFilePath -Organization $appID $tenantID

The demo below shows that the PowerShell Connection to Exchange Online si successful using the local certificate file authentication.

Using a Local PFX Certificate for AuthenticationUsing a Local PFX Certificate for Authentication

When you examine the code again, you’ll see that the pfx certificate password is visible. For increased protection, you may consider storing the certificate credential in a secret management system.

Using the Certificate Thumbprint for Authentication

This way of authentication is more secure than using a password and a local certificate. You must import the certificate into the Personal certificate store using this approach. Only the thumbprint is required to determine which certificate to use for authentication.

The PFX certificate must first be imported into the Personal certificate repository. This step only has to be done once for the current user.

IMPORT THE PFX CERTIFICATE INTO THE CURRENT PERSONAL CERTIFICATE STORE WITH THIS CODE. ## Get the PFX password $mypwd = Get-Credential -UserName ‘Enter password below’ -Message ‘Enter password below’ ## Set the certificate file path (.pfx) $CertificateFilePath = ‘C:exo v2 demoExo V2 App.pfx’ ## Import the PFX certificate into the personal certificate store of the current user. -CertStoreLocation Cert:CurrentUserMy -Password Import-PfxCertificate -FilePath $CertificateFilePath $mypwd.Password

The demonstration below demonstrates how to import a PFX certificate into your own certificate store.

The PFX certificate is imported.The PFX certificate is imported.

The outcome of the PFX import procedure will be seen as shown above. Make a note of the value of the Thumbprint for future reference.

Your scripts may now use the thumbprint of the certificate to authenticate with Exchange Online PowerShell.

To match your right values, edit the $tenantID, $appID, and $CertificateThumbPrint in the code below. Then, in PowerShell, copy and execute the code.

## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID

If you run the code above in PowerShell, you’ll get something like the example below.

After executing the code in Powershell, this is the output.After executing the code in Powershell, this is the output.

Using App-Only Authentication to Connect and Run Exchange Online PowerShell Scripts

You’ve just been copying and pasting code into PowerShell so far in this tutorial. You should use app-only authentication to execute your PowerShell scripts now that you understand how it works.

The script below connects to Exchange Online PowerShell and authenticates using the certificate thumbprint. The script will then obtain all of the mailboxes accessible once connected. C:exo v2 demoListExoMailbox.ps1 is where the script is stored.

## Clean up Exchange Online Session Get-PSSession | Where-Object {$_.name -like “ExchangeOnline*”} | Remove-PSSession -ErrorAction SilentlyContinue ## Create a tenant ID (directory ID or domain) $appID = ‘3f76be04-5cf0-47f1-9df6-d05981a450fc’ ## Set the Exo V2 App app id $tenantID = ‘poshlab.ga’ ## Set the certificate thumbprint ## Connect to Exchange Online using Connect-ExchangeOnline -CertificateThumbPrint $CertificateThumbPrint = ‘DED486B87C38CEA966EC71F8EE90BB3AAE694A74’ -AppID $CertificateThumbPrint -Organization $appID $tenantID ## Get All Mailbox Write-Output “Getting all mailboxes” Get-Mailbox -ResultSize Unlimited | Format-Table Name,DisplayName

Run the script in PowerShell once you’ve saved it. The script should automatically connect to Exchange Online and do its purpose. Refer to the findings in the demonstration below.

App-Only Authentication PowerShell ScriptApp-Only Authentication PowerShell Script

Summary

The EXO V2 PowerShell module’s release is a great development. Knowing that Microsoft has opted to remove basic authentication for connecting to Exchange Online through PowerShell, administrators may update their current scripts with this new app-only authentication option.

Implementing EXO V2 app-only authentication, on the other hand, is not without its difficulties.

  • A PFX password is still required when using a local certificate file. You should be able to avoid this password vulnerability problem if you use a credential or secret management approach.
  • In the personal shop, using a certificate gives you extra assurance. However, only the current user has access to the certificate. If you’ve set up a scheduled job to execute the script using UserA’s credentials, the certificate must be imported into UserA’s personal certificate store.
  • Certificates have a time limit. This would need certificate monitoring, renewal, and re-assignment to the Azure AD app. Otherwise, owing to an authentication failure, the script will cease operating.

These disadvantages are outweighed by the advantages of utilizing the new EXO V2 PowerShell module.

In this post, you learnt how to set up app-only authentication for the Exchange Online V2 PowerShell module step by step. You’ve also learned how to use a self-signed certificate to login to Exchange Online PowerShell.

You may now employ app-only certificate-based authentication in your scripts instead of dealing with Exchange Online PowerShell MFA prompts.

If you want to take things a step further, you might use Jenkins or Azure Automation to put everything you’ve learned in this article to the test. Alternatively, you may create your own PowerShell functions and modules.

Thank you for stopping by!

Additional Reading

The “exchange online powershell v2 module download” is a PowerShell module that allows users to connect to the Microsoft Exchange Online. This can be done via the “Connect-ExchangeOnline” cmdlet.

Related Tags

  • download exchange online powershell
  • install exchange online powershell module
  • install exchange online powershell v2 module
  • install-module exchange online
  • connect-exchangeonline

Table of Content