Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,16 @@ This repository publishes complete bundle modules, the authentication module, an

### 1. Installation

Microsoft Graph PowerShell module is published on [PowerShell Gallery](https://www.powershellgallery.com/packages/Microsoft.Graph). Installing is as simple as:
PowerShell 7 or later is recommended on all platforms. Install the modules you need from [PowerShell Gallery](https://www.powershellgallery.com/packages/Microsoft.Graph). For the examples below:

```powershell
Install-Module Microsoft.Graph
Install-Module Microsoft.Graph.Users -Scope CurrentUser
Install-Module Microsoft.Graph.Applications -Scope CurrentUser
```

> Run `Install-Module` with `-AllowClobber` and `-Force` parameters if you run into command name conflicts when upgrading to older versions of the module. This may be the case when upgrading from v1.x to v2.x:
These modules automatically install `Microsoft.Graph.Authentication`, which provides `Connect-MgGraph`. To install all v1.0 modules instead, use `Install-Module Microsoft.Graph -Scope CurrentUser`.

> If you encounter command name conflicts when upgrading from v1.x to v2.x, use `-AllowClobber` and `-Force`:
>
> ```powershell
> Install-Module Microsoft.Graph -AllowClobber -Force
Expand All @@ -132,23 +135,27 @@ The module supports two main types of authentication:

#### Delegated access

Get access to Microsoft Graph resources on behalf of a user.
Get access to Microsoft Graph resources on behalf of a user. Request only the delegated permissions needed for your operations; some permissions require administrator consent.

```powershell
# Using interactive authentication.
Connect-MgGraph -Scopes "User.ReadBasic.All", "Application.ReadWrite.All"
```

On Windows, interactive sign-in uses Web Account Manager (WAM) by default. `-LoginHint "user@contoso.com"` can pre-populate the account for interactive sign-in; it does not guarantee a prompt-free sign-in. For device code authentication, use `-UseDeviceCode`.

Delegated sign-in uses the `CurrentUser` token cache by default, so it can persist across PowerShell sessions. Use `-ContextScope Process` to keep tokens in the current process instead; this does not select a different account. Inspect the connected account, tenant, and permissions with `Get-MgContext`.

#### App-only access (client credentials grant flow)

Get access to Microsoft Graph resources using the identity on an app and not on behalf of a user.
Get access to Microsoft Graph resources using an application's identity, not on behalf of a user. Configure the required application permissions and grant administrator consent before connecting.

```powershell
# Using -CertificateThumbprint
Connect-MgGraph -ClientId "YOUR_APP_ID" -TenantId "YOUR_TENANT_ID" -CertificateThumbprint "YOUR_CERT_THUMBPRINT"
```

See [Authentication](./docs/authentication.md) for more information on the usage of `Connect-MgGraph`.
See [Authentication](./docs/authentication.md) for client secret, managed identity, custom application, sovereign cloud, and WAM configuration examples.

### 3. List users in your tenant

Expand All @@ -170,20 +177,22 @@ New-MgApplication -DisplayName "ScriptedGraphPSApp" `
-Web @{ RedirectUris = "https://localhost"}
```

### 6. Sign out of the current logged-in context i.e. app only or delegated access
### 6. Sign out of the current authentication context

```powershell
Disconnect-MgGraph
```

This clears the SDK's in-memory authentication state and, for `CurrentUser`, clears persisted tokens for the session's account when it can be identified. It does not clear the Windows WAM broker cache by default. See [Sign out and token caching](./docs/authentication.md#sign-out-and-token-caching) before using `-SignOutFromBroker`.

## API Version

Install `Microsoft.Graph.Beta` module to commands that call Microsoft Graph Beta API endpoint.
Use v1.0 APIs for production scripts. Beta APIs are preview features and can introduce breaking changes. Install the beta scenario-specific modules you need (or `Microsoft.Graph.Beta` for all beta modules); v1.0 and beta modules can coexist and share authentication.

```powershell
Install-Module Microsoft.Graph.Beta
Install-Module Microsoft.Graph.Beta.Users -Scope CurrentUser
# Consume Microsoft Graph beta resources.
Connect-MgGraph
Connect-MgGraph -Scopes "User.ReadBasic.All"
$Users = Get-MgBetaUser
```

Expand Down Expand Up @@ -213,7 +222,7 @@ See the [v2 upgrade guide](./docs/upgrade-to-v2.md) for more details.

When working with various operations in the Graph, you may encounter an error such as "Insufficient privileges to complete the operation." For example, this particular error can occur when using the `New-MgApplication` command if the appropriate permissions are not granted.

If permission-related errors occur and the signed-in user/app has been granted the appropriate permissions to perform the operation, you can explicitly fetch a new access token by running `Disconnect-MgGraph`, then `Connect-MgGraph`. This will trigger a refresh of the access token in your cache. Microsoft Authentication Library (MSAL) will only refresh access tokens in your cache if they have expired (usually an hour).
Check the tenant, authentication type, and granted permissions with `Get-MgContext`. Delegated access also depends on the signed-in user's privileges; app-only access requires application permissions with administrator consent. After permissions or consent change, allow time for propagation, then run `Disconnect-MgGraph` and reconnect with the required scopes or app credentials. Caller-provided access tokens must be replaced by the caller.

See [Microsoft Graph API Permissions Reference](https://learn.microsoft.com/graph/permissions-reference) for more details.

Expand All @@ -225,10 +234,7 @@ See our [troubleshooting guide](https://learn.microsoft.com/powershell/microsoft

- Using the `-Property {PropertyName}` parameter will not select the property as the output of the command. All commands return CLR objects, and customers should pipe the command outputs to `Format-Table` or `Select-Object` to return individual properties.

- Customers upgrading from previous versions of the SDK may encounter auth prompts on every command call. If this happens, one can use the following steps to reset their token cache:
- Use `Disconnect-MgGraph` to sign out of the current session.
- Run `Remove-Item "$env:USERPROFILE\.mg" -Recurse -Force` to delete your token cache.
- Run `Connect-MgGraph` to reconstruct a clean token cache.
- Customers upgrading from previous versions of the SDK may encounter authentication prompts on every command call. Start by running `Disconnect-MgGraph`, then reconnect with `Connect-MgGraph`. Do not delete the entire `.mg` directory: it also contains SDK options and environment settings. For Windows broker sign-in issues, see [WAM guidance](./docs/authentication.md#web-account-manager-wam), including the custom `-ClientId` requirement when disabling WAM.

## Feedback

Expand Down
93 changes: 81 additions & 12 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,34 @@ Microsoft Graph PowerShell module supports the following delegated access scenar

### Interactive Browser

On Windows, interactive authentication uses Web Account Manager (WAM) by default. On other platforms, it uses the browser. Request only the delegated permissions required for your operations; some permissions require administrator consent. If you omit `-Scopes`, the default is `User.Read`.

```PowerShell
Connect-MgGraph -Scopes "User.ReadBasic.All", "Calendars.Read.Shared"
```

Use `-LoginHint` to pre-populate a known account during browser or WAM sign-in:

```PowerShell
Connect-MgGraph -Scopes "User.ReadBasic.All" -LoginHint "user@contoso.com"
```

A matching cached authentication record can be reused for that account. An account picker, consent, or other authentication prompt may still be required by the identity provider or tenant policy; `-LoginHint` does not guarantee silent sign-in. It is not used by device code authentication.

### Custom application

To use your own application registration instead of the default Microsoft Graph PowerShell application:

```PowerShell
Connect-MgGraph -ClientId "YOUR_APP_CLIENT_ID" -TenantId "YOUR_TENANT_ID" -Scopes "User.ReadBasic.All"
```

Configure a public client application with `http://localhost` as a redirect URI for browser sign-in. For WAM sign-in on Windows, also register `ms-appx-web://Microsoft.AAD.BrokerPlugin/<YOUR_APP_CLIENT_ID>`. See [Use delegated access with a custom application](https://learn.microsoft.com/en-us/powershell/microsoftgraph/authentication-commands?view=graph-powershell-1.0#use-delegated-access-with-a-custom-application-for-microsoft-graph-powershell) for registration and access assignment steps.

### Device Code

Use device code authentication when interactive browser or WAM sign-in is unsuitable, provided your tenant's policies allow this flow.

```PowerShell
Connect-MgGraph -Scopes "User.ReadBasic.All", "Calendars.Read.Shared" -UseDeviceCode
```
Expand All @@ -27,11 +49,13 @@ Connect-MgGraph -Scopes "User.ReadBasic.All", "Calendars.Read.Shared" -UseDevice

App-only access uses a confidential client to get an access token and consume Microsoft Graph resources without a user context (uses an app's context).

Configure Microsoft Graph application permissions and grant administrator consent before connecting. `-Scopes` is for delegated access and is not used with app-only credentials.

Microsoft Graph PowerShell module supports the following app-only access scenarios:

### Client credential via a certificate

Load certificate from store using a certificate's thumbprint.
Load a certificate with its private key from `Cert:\CurrentUser\My` or `Cert:\LocalMachine\My` using its thumbprint. The current user's store is searched first.

```PowerShell
Connect-MgGraph -ClientId "Client_Id" -TenantId "Tenant_Id" -CertificateThumbprint "Cert_Thumbprint"
Expand All @@ -43,7 +67,7 @@ Load certificate from store using a certificate's subject name.
Connect-MgGraph -ClientId "Client_Id" -TenantId "Tenant_Id" -CertificateSubjectName "Cert_Subject_Name"
```

Load certificate from file.
Pass a certificate object explicitly, for example from the local machine certificate store.

```PowerShell
$Cert = Get-ChildItem Cert:\LocalMachine\My\$CertThumbprint
Expand All @@ -64,7 +88,7 @@ Connect-MgGraph -EnvironmentVariable

### Client credential via client secret

Using PSCredential object.
Using a PSCredential object. Supply the application (client) ID as the username and the client secret as the password. Do not store secrets in scripts or source control.

```PowerShell
$ClientSecretCredential = Get-Credential -Username "Client_Id"
Expand All @@ -86,6 +110,8 @@ Connect-MgGraph -EnvironmentVariable

### Managed Identity

Run these commands on an Azure resource configured with the corresponding managed identity. Grant that identity the Microsoft Graph application permissions required by your operations.

System-assigned managed identity

```PowerShell
Expand All @@ -102,6 +128,13 @@ Connect-MgGraph -Identity -ClientId "User_Assigned_Managed_identity_Client_Id"

Customers can acquire an access token using their preferred auth library and pass the access token to the Microsoft Graph PowerShell module using `-AccessToken` parameter on `Connect-MgGraph`. The module will then use the provided access token to consume Microsoft Graph resources.

`-AccessToken` requires a `SecureString` and accepts either a delegated or app-only Microsoft Graph token. If your authentication library returns a plain-text token in `$AccessToken`, convert it before connecting:

```PowerShell
$SecureAccessToken = ConvertTo-SecureString -String $AccessToken -AsPlainText -Force
Connect-MgGraph -AccessToken $SecureAccessToken
```

The following considerations should be made before using `-AccessToken`:

### Access Token Expiry
Expand All @@ -112,26 +145,62 @@ When using `-AccessToken`, we won't have access to the refresh token and the cli

Before using the provided `-AccessToken` to get Microsoft Graph resources, customers should ensure that the access token has the necessary scopes/ permissions needed to access/modify a resource.

## Environments and sovereign clouds

`Connect-MgGraph` targets the global public cloud by default. Use `Get-MgEnvironment` to list available environments and `-Environment` to select one:

```PowerShell
Get-MgEnvironment
Connect-MgGraph -Environment USGov -Scopes "User.ReadBasic.All"
```

BleuCloud, DelosCloud, and GovSGCloud require a custom application registration in the target cloud and Microsoft.Graph.Authentication v2.36.1 or later. Azure China also requires an application registered in that cloud.

```PowerShell
Connect-MgGraph -ClientId "YOUR_APP_CLIENT_ID" -TenantId "YOUR_TENANT_ID" -Environment BleuCloud -Scopes "User.ReadBasic.All"
```

If WAM sign-in hangs in a sovereign cloud, use the custom-application browser sign-in configuration described below.

## Sign out and token caching

Delegated authentication defaults to `-ContextScope CurrentUser`, which securely caches tokens for reuse across PowerShell sessions. Use `-ContextScope Process` to keep tokens in memory for the current PowerShell process. On Windows Subsystem for Linux (WSL), delegated authentication uses `Process` scope. Certificate, client secret, managed identity, and environment-variable authentication default to `Process`; caller-provided access tokens always use `Process`.

`-ContextScope` controls token persistence, not account selection. Use `-LoginHint` to hint at a particular account during interactive sign-in, and verify the connected identity and permissions:

```PowerShell
Get-MgContext
Get-MgContext | Select-Object -ExpandProperty Scopes
Disconnect-MgGraph
```

`Disconnect-MgGraph` clears the SDK's in-memory cache and authentication context and removes the session's authentication record. With `CurrentUser` scope, it also clears persisted MSAL tokens for the session's account when it can be identified; cache clearing can fall back to the full SDK token cache when no matching account is found. Cache-clearing failures are reported as warnings.

The Windows WAM broker cache is not cleared by default, so a subsequent connection may still use Windows single sign-on. To also remove the cached broker account, opt in explicitly:

```PowerShell
Disconnect-MgGraph -SignOutFromBroker
```

**Caution:** The broker store is shared at the operating-system level. This can affect other broker-enabled applications using the same Windows account, and removal can fall back to all accounts for this module if the session's account cannot be identified. The switch only takes effect on Windows when WAM is in use.

## Web Account Manager (WAM)

WAM is a Windows 10+ component that acts as an authentication broker allowing the users of an app benefit from integration with accounts known to Windows, such as the account already signed into an active Windows session.

Microsoft Graph PowerShell module supports WAM in the following scenario:

- To disable WAM on supported devices (requires a custom ClientId)
WAM is enabled by default for interactive sign-in on Windows and cannot be disabled for the default Microsoft Graph PowerShell client ID. Starting with v2.35.1, you can disable WAM for a custom application. Register `http://localhost` as a redirect URI for browser sign-in, then set the option before connecting:

```PowerShell
Set-MgGraphOption -DisableLoginByWAM $true
Connect-MgGraph -ClientId "YOUR_APP_CLIENT_ID" -TenantId "YOUR_TENANT_ID" -Scopes "User.ReadBasic.All"
```

- To re-enable WAM after disabling it
The option persists across PowerShell sessions and applies to subsequent connections. It does not disable WAM for other applications and has no effect on non-Windows platforms or device code authentication.

To re-enable WAM for subsequent interactive connections:

```PowerShell
Set-MgGraphOption -DisableLoginByWAM $false
```

**Note: Signin by Web Account Manager (WAM) is enabled by default on Windows and cannot be disabled. Setting this option to $False will have no effect on Windows systems. Except if you use your own app (see below)**

Starting with v2.35.1, to disable WAM on Windows, use `Set-MgGraphOption -DisableLoginByWAM $true` and then connect with a custom `-ClientId`.
To create your custom app, follow the guide to [Use delegated access with a custom application for Microsoft Graph PowerShell](https://learn.microsoft.com/en-us/powershell/microsoftgraph/authentication-commands?view=graph-powershell-1.0#use-delegated-access-with-a-custom-application-for-microsoft-graph-powershell
). You should also add the redirect URI of `ms-appx-web://Microsoft.AAD.BrokerPlugin/<yourAppId>` to ensure that you can use WAM against that app registration as well.
Ensure the custom application's WAM redirect URI is registered as described in [Custom application](#custom-application). In embedded terminals, the WAM sign-in window can appear behind other windows.
Loading
Loading