PowerShell

How to: Securely Connect to Microsoft 365 and Azure Using PowerShell with MFA

April 30, 2025
7 min read
#Administrative Access#API Permissions#Azure#Certificate-Based Authentication#Cloud Security#Exchange Online PowerShell#Microsoft 365#Microsoft Entra ID#Microsoft Graph PowerShell SDK#Microsoft Teams PowerShell#Multi-Factor Authentication#PnP PowerShell#PowerShell#Script Automation#Security#Security Compliance#SharePoint Online#Unattended Scripts

Microsoft 365 and Azure administrators rely heavily on PowerShell for managing, automating, and reporting on their cloud environments. However, the landscape of PowerShell connectivity to these services has evolved significantly over the past few years, with Microsoft placing a stronger emphasis on security, modern authentication, and consolidation of management tools.

This article provides an updated guide on how to securely connect to Microsoft 365 and Azure using PowerShell with Multi-Factor Authentication (MFA) support. Microsoft is implementing mandatory MFA enforcement in phases, with MFA becoming required for the Microsoft 365 admin center beginning in February 2025, and for Azure CLI, PowerShell, and REST API endpoints starting July 1, 2025. Understanding these changes and implementing secure connection methods is critical for all administrators.

Problem Definition

Administrators face several challenges when connecting to Microsoft 365 and Azure services through :

  1. Module Deprecation: As of March 30, 2024, the Azure AD and MSOnline PowerShell modules are officially deprecated, with limited support only for migration assistance to Microsoft Graph PowerShell SDK and security fixes until March 30, 2025.  This means many organizations need to migrate their scripts and processes to newer modules.
  2. Multi-Factor Authentication Requirements: Implementing MFA for administrative accounts is no longer optional but a mandatory security practice. Many legacy connection methods don't support MFA natively.
  3. Authentication Method Changes: Remote PowerShell Protocol (RPS) has been blocked for Exchange Online, requiring administrators to use the Exchange Online PowerShell V3 module which uses REST API connections rather than Basic authentication.
  4. Script Automation Challenges: Running automated scripts becomes challenging when interactive MFA prompts are required. Organizations need secure, non-interactive authentication methods that still comply with strong security practices.
  5. Permission Management: Ensuring scripts use the least permissions necessary can be difficult, especially with the Microsoft Graph PowerShell SDK where permissions can accumulate over time in the service principal.

Solution Options

1. Microsoft Graph PowerShell SDK

The Microsoft Graph PowerShell SDK is now the primary tool for managing Microsoft 365 and Azure resources, providing a unified interface to interact with all Microsoft cloud services.

Installation and Basic Connection

Install-Module Microsoft.Graph -Scope CurrentUser

# Connect with MFA (interactive)
Connect-MgGraph -Scopes "User.Read.All","Group.ReadWrite.All"

When connecting with the Microsoft Graph PowerShell SDK, you need to specify the permission scopes required for the operations you'll perform. Each API in Microsoft Graph is protected by one or more permission scopes, and the user must consent to these scopes during authentication.

For finding required permissions:

Find-MgGraphCommand -Command Get-MgUser | Select-Object -ExpandProperty Permissions

2. Exchange Online PowerShell V3 Module

The Exchange Online V3 module uses modern authentication and REST APIs instead of the deprecated Remote connections. This module is required for managing Exchange Online.

Installation and Connection

Install-Module -Name ExchangeOnlineManagement

# Connect with MFA
Connect-ExchangeOnline -UserPrincipalName admin@yourdomain.com

3. Microsoft Teams PowerShell Module

The Microsoft Teams PowerShell module requires Windows PowerShell 5.1 or PowerShell 7.2 or later, and can be installed from the Gallery.

Installation and Connection

Install-Module -Name MicrosoftTeams -Force -AllowClobber

# Connect with MFA
Connect-MicrosoftTeams

4. SharePoint Online and PnP PowerShell

For SharePoint Online management, administrators can use either the SharePoint Online Management Shell or the more comprehensive PnP PowerShell module.

PnP PowerShell is a cross-platform Module providing over 750 cmdlets for working with Microsoft 365 environments including SharePoint Online, Microsoft Teams, Microsoft Project, Security & Compliance, and more.

Installation and Connection

Install-Module -Name Microsoft.Online.SharePoint.# Connect with MFA
Connect-SPOService -Url https://contoso-admin.sharepoint.com

# Install PnP (cross-platform)
Install-Module -Name PnP.# Connect with MFA
Connect-PnPOnline -Url https://contoso.sharepoint.com -Interactive

5. Security & Compliance PowerShell

The Exchange Online PowerShell module is also used to connect to Security & Compliance PowerShell using modern authentication and MFA.

# Install the module (if not already installed)
Install-Module -Name ExchangeOnlineManagement

# Connect to Security & Compliance PowerShell 
Connect-IPPSSession -UserPrincipalName admin@yourdomain.com

Automating Management with Certificate-Based Authentication

For unattended scripts and automation, certificate-based authentication (CBA) provides a secure method without requiring interactive sign-in or storing credentials.

Certificate-Based Authentication (CBA) provides a secure way to automate PowerShell sessions without storing credentials, which is particularly important since Basic Authentication has been deprecated in Exchange Online.

Setting Up Certificate-Based Authentication

1. Create a Self-Signed Certificate

# Create a self-signed certificate valid for 2 years
$certName = "PowerShellAutomation"
$cert = New-SelfSignedCertificate -Subject "CN=$certName" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256 -NotAfter (Get-Date).AddYears(2)

# Export the certificate for uploading to Azure AD
Export-Certificate -Cert $cert -FilePath "$env:USERPROFILE$certName.cer"

2. Register an Application in Microsoft Entra ID

  1. Go to the Microsoft Entra admin center (previously Azure AD portal)
  2. Navigate to App registrations > New registration
  3. Provide a name for your application
  4. Select "Accounts in this organizational directory only"
  5. Register the application
  6. Upload the certificate (.cer file) under Certificates & secrets
  7. Add API permissions based on the operations your script will perform
  8. Grant admin consent for the required permissions

3. Connect Using Certificate Authentication

For Microsoft Graph:

Connect-MgGraph -ClientId "YOUR_APP_ID" -TenantId "YOUR_TENANT_ID" -CertificateThumbprint $cert.Thumbprint

For Exchange Online:

Connect-ExchangeOnline -AppId "YOUR_APP_ID" -CertificateThumbprint $cert.Thumbprint -Organization "yourdomain.onmicrosoft.com"

Using Azure Managed Identities for Automation

For scripts running in Azure resources, managed identities provide an even more secure approach by eliminating the need to manage credentials altogether.

Connect-MgGraph -Identity

Consolidating PowerShell Connections

Instead of having multiple PowerShell sessions open for different services, you can connect to all Microsoft 365 services in a single PowerShell window. This approach simplifies administration and allows for easier data exchange between services.

Here's an example script to connect to multiple services in a single session:

Connect-MgGraph -Scopes "User.Read.All","Group.ReadWrite.All"

# Connect to Exchange Online
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -ShowProgress $true

# Connect to SharePoint Online
$orgName = "contoso" # Your tenant name (e.g., contoso for contoso.onmicrosoft.com)
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
Connect-SPOService -Url "https://$orgName-admin.sharepoint.com"

# Connect to Teams
Import-Module MicrosoftTeams
Connect-MicrosoftTeams

# Connect to Security & Compliance Center
Connect-IPPSSession

Security Best Practices

1. Using Least-Privileged Permissions

When connecting to Microsoft Graph, the level of access is controlled by the scopes you request. Request only the specific permissions needed for your task rather than broad administrative permissions.

2. Custom Applications for Controlled Access

Instead of using the default Microsoft Graph PowerShell SDK enterprise app, which can accumulate many permissions over time, create custom registered apps with limited, specific permissions for different administrative tasks.

3. Secure Storage of Certificates and Secrets

Never hardcode secrets or certificate thumbprints in scripts. Use secure storage solutions like:

  • Azure Key Vault
  • Secure environment variables
  • Managed identities when running in Azure

4. Regular Rotation of Certificates and Secrets

Set a schedule to regularly rotate certificates and client secrets to limit the impact if they're ever compromised.

5. Implement Conditional Access Policies

Use Conditional Access policies to restrict PowerShell connections to specific networks, devices, or conditions.

Conclusion

The landscape of PowerShell connectivity to Microsoft 365 and Azure has evolved significantly, with a strong emphasis on security, modern authentication, and consolidation of management tools. With the deprecation of older modules like MSOnline and AzureAD scheduled for March 2025, it's essential for administrators to migrate to the Microsoft Graph PowerShell SDK and other modern modules.

Multi-Factor Authentication is no longer optional but a requirement for secure administration. Microsoft's phased enforcement of mandatory MFA for administrative portals starting in February 2025 and extending to PowerShell and other endpoints by July 2025 means organizations must adapt their administrative practices.

Certificate-Based Authentication provides a secure method for automating administrative tasks without compromising security. By following the practices outlined in this article, administrators can ensure their PowerShell connections to Microsoft 365 and Azure are both secure and efficient.

We Can Help

  1. Audit your existing PowerShell scripts for deprecated modules (MSOnline and AzureAD) and start migrating them to the Microsoft Graph PowerShell SDK.
  2. Implement Certificate-Based Authentication for all automated scripts to eliminate the need for stored credentials.
  3. Review the permissions assigned to your PowerShell connections and apply the principle of least privilege.
  4. Set up a regular schedule for rotating certificates and secrets used in your PowerShell scripts.
  5. Contact us for personalized guidance on implementing these security practices in your environment.

References

  1. Microsoft Graph PowerShell SDK Documentation
  2. Exchange Online PowerShell V3 Module Documentation
  3. App-only Authentication Documentation
  4. Microsoft Entra Certificate-based Authentication
  5. Mandatory MFA for Microsoft 365
  6. PnP PowerShell Documentation
  7. Microsoft Teams PowerShell Documentation

Share this article

Help others discover this content

Need Help Implementing This Solution?

Schedule a free 30-minute consultation to discuss your specific Microsoft 365 or Azure needs.

Schedule Free Consultation

Related Articles

How to: Connect to Microsoft 365 Exchange Online with PowerShell
Microsoft 365

How to: Connect to Microsoft 365 Exchange Online with PowerShell

Microsoft 365 Exchange Online PowerShell Connection Guide Table of Contents Part 1: Exchange Online PowerShell Quick Start

Apr 15, 2025
17 min
How to: Install and Use OpenSSH on Windows for PowerShell Core Remoting via SSH
PowerShell

How to: Install and Use OpenSSH on Windows for PowerShell Core Remoting via SSH

Introduction The integration of SSH with Windows represents a significant advancement for system administrators working in cross-platform environments. Microsoft's goal has been to tightly integrate the open source Secure Shell (SSH) protocol with Windows and PowerShell, enabling two-way remote management between Linux and Windows systems. This approach provides administrators with a unified method for managing diverse environments, from Windows servers to Linux machines, network devices, and cloud infrastructure. SSH is the standard remoting tool for Linux, and Microsoft has added native support for it on clients running Windows 10 build 1809 or newer and Windows Server 2019 or newer. Starting with Windows Server 2025, OpenSSH now comes pre-installed, further simplifying deployment in enterprise environments. This evolution highlights Microsoft's commitment to embracing open standards and fostering cross-platform compatibility. Problem Definition

Nov 1, 2024
6 min
How To: Windows Profile Migration To Entra ID Using PowerShell
Entra ID

How To: Windows Profile Migration To Entra ID Using PowerShell

Summary This article documents migrating a local Windows user profile to a new Microsoft Entra ID account on the same machine. The primary focus is on developing a detailed, PowerShell driven methodology as a viable alternative to commercial, third-party tools such as Profwiz. The inherent complexity of this task stems from the need to re-associate an existing user profile with a new security context. This is not a simple data transfer but a precise, low-level reconfiguration of core Windows components, including the file system and the registry. The analysis concludes that a "PowerShell only" solution is a misnomer. A robust and reliable scripted approach must orchestrate a hybrid workflow, leveraging native cmdlets in conjunction with essential command-line utilities like reg.exe, icacls.exe, and takeown.exe. The limitations of 's built-in providers necessitate this approach for critical actions, such as loading and unloading another user's registry hive. A manual, scripted migration provides granular control and eliminates licensing costs associated with commercial software. However, it is a high-risk operation that lacks built-in transactional safety and a "rollback" feature, making it suitable for one-off tasks or for IT professionals who require a deep, auditable understanding of the process. For large scale, enterprise-level deployments, commercial tools designed for high reliability and ease of use remain the preferred solution. The scripted method, while powerful and customizable, demands a high degree of technical expertise and meticulous execution to mitigate the risk of data corruption and system instability.

Sep 22, 2025
15 min

Stay Updated

Join IT professionals receiving Microsoft 365 tutorials and insights