├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── app-auth ├── GraphTutorialAppOnly.ps1 ├── README.md └── settings.example.json ├── qs.json └── user-auth ├── GraphTutorial.ps1 ├── README.md ├── RegisterAppForUserAuth.ps1 ├── settings.example.json └── version /.gitignore: -------------------------------------------------------------------------------- 1 | *.cer 2 | settings.json 3 | *.zip 4 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | - Employees can reach out at [aka.ms/opensource/moderation-support](https://aka.ms/opensource/moderation-support) 11 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Microsoft Graph training repositories 2 | 3 | Thank you for contributing to this project! Before submitting your pull request, be sure to consider the following. 4 | 5 | ## Overview 6 | 7 | The code in this repository serves two purposes: 8 | 9 | - The sample project in the [user-auth](/user-auth) folder is the source for a [Microsoft Graph quick start](https://developer.microsoft.com/graph/quick-start). 10 | - The code in the [user-auth](/user-auth) and [app-auth](/app-auth) folders are directly referenced by [Microsoft Graph tutorials](https://learn.microsoft.com/graph/tutorials) 11 | 12 | This is important to keep in mind, because changes in one place *may* require changes in another, to keep things in sync. The Markdown files for the tutorials refer to the source code files directly (using a custom `:::code` syntax), so that updating code in source will automatically update the code in Markdown. 13 | 14 | ## Updating code 15 | 16 | The `:::code` syntax used in Markdown depends on specific comments in the source code file. These comments look like the following: 17 | 18 | ```csharp 19 | // 20 | Console.WriteLine("Hello World!"); 21 | // 22 | ``` 23 | 24 | If you update code between these "marker" comments, the Markdown files will automatically get those changes when published to the Microsoft Graph documentation site. If you update code outside of those comments, it's very likely that you'll need to update the corresponding Markdown in the [Microsoft Graph training repository](https://github.com/microsoftgraph/microsoft-graph-training). 25 | 26 | ## Adding features 27 | 28 | While the enthusiasm is appreciated, please don't send pull requests to add new features to the sample. Because this repository is primarily a "build your first app" tutorial, the feature set is limited, by design. 29 | 30 | ## Submitting pull requests 31 | 32 | Please submit all pull requests to the `main` branch. 33 | 34 | ## When do changes get published? 35 | 36 | Publishing of updates to the [Microsoft Graph tutorials](https://learn.microsoft.com/graph/tutorials) site is not automatic. Changes must first be promoted to the `live` branch, then a build must be triggered by the site admins. This is typically done on an "as-needed" basis. 37 | 38 | ## Code of conduct 39 | 40 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Microsoft Graph 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Build PowerShell scripts with Microsoft Graph - Completed project 2 | 3 | This sample will introduce you to working with the Microsoft Graph PowerShell SDK to access data in Microsoft 365 from .NET applications. This code is the result of completing the [PowerShell Microsoft Graph tutorial](https://learn.microsoft.com/graph/tutorials/powershell) and the [PowerShell Microsoft Graph app-only tutorial](https://learn.microsoft.com/graph/tutorials/powershell-app-only). 4 | 5 | ## Running the sample 6 | 7 | The code for the delegated user authentication sample is in the [user-auth](user-auth) folder. Instructions to configure and run the sample can be found in the [README](user-auth/README.md) in that folder. 8 | 9 | The code for the app-only authentication sample is in the [app-auth](app-auth) folder. Instructions to configure and run the sample can be found in the [README](app-auth/README.md) in that folder. 10 | 11 | ## Code of conduct 12 | 13 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 14 | 15 | ## Disclaimer 16 | 17 | **THIS CODE IS PROVIDED _AS IS_ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.** 18 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** 12 | 13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). 14 | 15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). 16 | 17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). 18 | 19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 20 | 21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 22 | * Full paths of source file(s) related to the manifestation of the issue 23 | * The location of the affected source code (tag/branch/commit or direct URL) 24 | * Any special configuration required to reproduce the issue 25 | * Step-by-step instructions to reproduce the issue 26 | * Proof-of-concept or exploit code (if possible) 27 | * Impact of the issue, including how an attacker might exploit the issue 28 | 29 | This information will help us triage your report more quickly. 30 | 31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. 32 | 33 | ## Preferred Languages 34 | 35 | We prefer all communications to be in English. 36 | 37 | ## Policy 38 | 39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). 40 | 41 | 42 | -------------------------------------------------------------------------------- /app-auth/GraphTutorialAppOnly.ps1: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # Note: Use of this script requires configuring app-only auth 5 | # as described in README.md 6 | 7 | Write-Host 'PowerShell Graph Tutorial - App Only' 8 | 9 | # Load settings 10 | $settings = Get-Content './settings.json' -ErrorAction Stop | Out-String | ConvertFrom-Json 11 | 12 | $clientId = $settings.clientId 13 | $tenantId = $settings.tenantId 14 | $certificate = $settings.clientCertificate 15 | 16 | # 17 | Connect-MgGraph -ClientId $clientId -TenantId $tenantId -CertificateName $certificate 18 | # 19 | 20 | # 21 | Get-MgUser -Select "displayName,id,mail" -Top 25 -OrderBy "displayName" 22 | # 23 | -------------------------------------------------------------------------------- /app-auth/README.md: -------------------------------------------------------------------------------- 1 | # How to run the completed project 2 | 3 | ## Prerequisites 4 | 5 | To run the script in this folder, you need the following: 6 | 7 | - The [Microsoft Graph PowerShell SDK](https://learn.microsoft.com/powershell/microsoftgraph/installation) installed on your development machine. (**Note:** This tutorial was written with PowerShell 7.2.2 and Microsoft Graph PowerShell SDK version 1.9.5. The steps in this guide may work with other versions, but that has not been tested.) 8 | - A Microsoft work or school account with the **Global administrator** role. 9 | 10 | If you don't have a Microsoft account, you can [sign up for the Microsoft 365 Developer Program](https://developer.microsoft.com/microsoft-365/dev-program) to get a free Microsoft 365 subscription. 11 | 12 | ## Register an application 13 | 14 | 1. Open a browser and navigate to the [Azure Active Directory admin center](https://aad.portal.azure.com) and login using a Global administrator account. 15 | 16 | 1. Select **Azure Active Directory** in the left-hand navigation, then select **App registrations** under **Manage**. 17 | 18 | 1. Select **New registration**. Enter a name for your application, for example, `PowerShell Graph Tutorial`. 19 | 20 | 1. Set **Supported account types** to **Accounts in this organizational directory only**. 21 | 22 | 1. Leave **Redirect URI** empty. 23 | 24 | 1. Select **Register**. On the application's **Overview** page, copy the value of the **Application (client) ID** and **Directory (tenant) ID** and save them, you will need these values in the next step. 25 | 26 | ### Create a self-signed certificate 27 | 28 | The Microsoft Graph PowerShell SDK requires a certificate for app-only authentication. For development purposes, a self-signed certificate is sufficient. You need a certificate with the private key installed on the local machine, and the public key exported in a .CER, .PEM, or .CRT file. 29 | 30 | #### Windows 31 | 32 | On Windows, you can use the [pki PowerShell module](https://learn.microsoft.com/powershell/module/pki) to generate the certificate. 33 | 34 | ```powershell 35 | $cert = New-SelfSignedCertificate -Subject "CN=PowerShell App-Only" -CertStoreLocation ` 36 | "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 ` 37 | -KeyAlgorithm RSA -HashAlgorithm SHA256 38 | Export-Certificate -Cert $cert -FilePath "./PowerShellAppOnly.cer" 39 | ``` 40 | 41 | #### Linux/MacOS 42 | 43 | On Linux or MacOS, you can use [OpenSSL](https://www.openssl.org/) to generate the private and public keys, then use PowerShell to install the private key into a certificate store readable by PowerShell. 44 | 45 | 1. Generate a new X509 certificate using the following command. 46 | 47 | ```bash 48 | openssl req -x509 -newkey rsa:2048 -sha256 -days 365 -keyout powershell.pem -out powershell.crt -subj "/CN=PowerShell App-Only" 49 | ``` 50 | 51 | 1. OpenSSL prompts you for a PEM pass phrase. Enter a pass phrase you will remember. 52 | 53 | 1. Create a PFX file using the following command. 54 | 55 | ```bash 56 | openssl pkcs12 -export -out powershell.pfx -inkey powershell.pem -in powershell.crt 57 | ``` 58 | 59 | 1. OpenSSL prompts you for the pass phrase for **powershell.pem**, enter the pass phrase you used in the previous step. 60 | 61 | 1. OpenSSL prompts you for an export password. Enter a password you will remember. 62 | 63 | 1. Open PowerShell and run the following commands, replacing *<export-password>* with the export password you used in the previous step. 64 | 65 | ```powershell 66 | using namespace System.Security.Cryptography.X509Certificates 67 | $store = [X509Store]::new('My', 'CurrentUser', 'ReadWrite') 68 | $store.Add([X509Certificate2]::new('./powershell.pfx', '', [X509KeyStorageFlags]::PersistKeyS 69 | et)) 70 | $store.Dispose() 71 | ``` 72 | 73 | ### Update the app registration 74 | 75 | 1. In the AAD Admin Center, select **API permissions** under **Manage**. 76 | 77 | 1. Remove the default **User.Read** permission under **Configured permissions** by selecting the ellipses (**...**) in its row and selecting **Remove permission**. 78 | 79 | 1. Select **Add a permission**, then **Microsoft Graph**. 80 | 81 | 1. Select **Application permissions**. 82 | 83 | 1. Select **User.Read.All**, then select **Add permissions**. 84 | 85 | 1. Select **Grant admin consent for...**, then select **Yes** to provide admin consent for the selected permission. 86 | 87 | 1. Select **Certificates and secrets** under **Manage**, then select **Certificates**. 88 | 89 | 1. Select **Upload certificate**. Upload the **PowerShellAppOnly.cer** or **powershell.crt** file you created in the previous step, then select **Add**. 90 | 91 | ## Configure the sample 92 | 93 | 1. Open [settings.json](./graphtutorial/settings.json) and update the values according to the following table. 94 | 95 | | Setting | Value | 96 | |---------|-------| 97 | | `clientId` | The client ID of your app registration | 98 | | `clientCertificate` | The subject of the certificate generated in [Create a self-signed certificate](#create-a-self-signed-certificate). For example, `CN=PowerShell App-Only`. | 99 | | `tenantId` | The tenant ID of your organization | 100 | 101 | ## Run the sample 102 | 103 | In PowerShell, navigate to the project directory and run the following command. 104 | 105 | ```Shell 106 | ./GraphTutorialAppOnly.ps1 107 | ``` 108 | 109 | **Note:** The scripts included in this sample are not digitally signed. Attempting to run them may result in the following error: 110 | 111 | ```powershell 112 | .\GraphTutorialAppOnly.ps1: File C:\Source\GraphTutorialAppOnly.ps1 cannot be loaded. The file C:\Source\GraphTutorialAppOnly.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170. 113 | ``` 114 | 115 | If you get this error, use the following commands to unblock the file and temporarily allow unsigned scripts in the current PowerShell session. This will not change the default execution policy, the setting is only effective in the current session. 116 | 117 | ```powershell 118 | Unblock-File .\GraphTutorialAppOnly.ps1 119 | Set-ExecutionPolicy Unrestricted -Scope Process 120 | ``` 121 | -------------------------------------------------------------------------------- /app-auth/settings.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "clientId": "YOUR_CLIENT_ID_HERE", 3 | "tenantId": "YOUR_TENANT_ID_HERE", 4 | "clientCertificate": "YOUR_CLIENT_CERTIFICATE_HERE", 5 | "graphUserScopes": [ 6 | "user.read", 7 | "mail.read", 8 | "mail.send" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /qs.json: -------------------------------------------------------------------------------- 1 | { 2 | "sourceDirectory": "./user-auth", 3 | "exampleConfigFile": "./settings.example.json", 4 | "configFile": "settings.json", 5 | "archiveFile": "PowerShellQuickStart.zip", 6 | "zipReadMe": "./README.md", 7 | "excludeFiles": [ 8 | "user-auth/RegisterAppForUserAuth.ps1" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /user-auth/GraphTutorial.ps1: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | Write-Host 'PowerShell Graph Tutorial' 5 | 6 | # Load settings 7 | $settings = Get-Content './settings.json' -ErrorAction Stop | Out-String | ConvertFrom-Json 8 | 9 | $clientId = $settings.clientId 10 | $tenantId = $settings.tenantId 11 | $graphScopes = $settings.graphUserScopes 12 | 13 | # 14 | # Authenticate the user 15 | Connect-MgGraph -ClientId $clientId -TenantId $tenantId -Scopes $graphScopes -UseDeviceAuthentication 16 | # 17 | 18 | # 19 | # Get the Graph context 20 | Get-MgContext 21 | # 22 | 23 | # 24 | $context = Get-MgContext 25 | # 26 | 27 | # 28 | # Get the authenticated user by UPN 29 | $user = Get-MgUser -UserId $context.Account -Select 'displayName, id, mail, userPrincipalName' 30 | # 31 | 32 | # 33 | Write-Host "Hello," $user.DisplayName 34 | # For Work/school accounts, email is in Mail property 35 | # Personal accounts, email is in UserPrincipalName 36 | Write-Host "Email:", ($user.Mail ?? $user.UserPrincipalName) 37 | # 38 | 39 | # 40 | Get-MgUserMailFolderMessage -UserId $user.Id -MailFolderId Inbox -Select ` 41 | "from,isRead,receivedDateTime,subject" -OrderBy "receivedDateTime DESC" ` 42 | -Top 25 | Format-Table Subject,@{n='From';e={$_.From.EmailAddress.Name}}, ` 43 | IsRead,ReceivedDateTime 44 | # 45 | 46 | # 47 | $sendMailParams = @{ 48 | Message = @{ 49 | Subject = "Testing Microsoft Graph" 50 | Body = @{ 51 | ContentType = "text" 52 | Content = "Hello world!" 53 | } 54 | ToRecipients = @( 55 | @{ 56 | EmailAddress = @{ 57 | Address = ($user.Mail ?? $user.UserPrincipalName) 58 | } 59 | } 60 | ) 61 | } 62 | } 63 | # 64 | 65 | # 66 | Send-MgUserMail -UserId $user.Id -BodyParameter $sendMailParams 67 | # 68 | 69 | Disconnect-MgGraph | Out-Null 70 | -------------------------------------------------------------------------------- /user-auth/README.md: -------------------------------------------------------------------------------- 1 | # How to run the completed project 2 | 3 | ## Prerequisites 4 | 5 | To run the script in this folder, you need the following: 6 | 7 | - The [Microsoft Graph PowerShell SDK](https://learn.microsoft.com/powershell/microsoftgraph/installation) installed on your development machine. (**Note:** This tutorial was written with PowerShell 7.2.2 and Microsoft Graph PowerShell SDK version 1.9.5. The steps in this guide may work with other versions, but that has not been tested.) 8 | - Either a personal Microsoft account with a mailbox on Outlook.com, or a Microsoft work or school account. If you don't have a Microsoft account, there are a couple of options to get a free account: 9 | - You can [sign up for a new personal Microsoft account](https://signup.live.com/signup?wa=wsignin1.0&rpsnv=12&ct=1454618383&rver=6.4.6456.0&wp=MBI_SSL_SHARED&wreply=https://mail.live.com/default.aspx&id=64855&cbcxt=mai&bk=1454618383&uiflavor=web&uaid=b213a65b4fdc484382b6622b3ecaa547&mkt=E-US&lc=1033&lic=1). 10 | - You can [sign up for the Microsoft 365 Developer Program](https://developer.microsoft.com/microsoft-365/dev-program) to get a free Microsoft 365 subscription. 11 | 12 | ## Register an application 13 | 14 | You can register an application using the Azure Active Directory admin center, or by using the [Microsoft Graph PowerShell SDK](https://learn.microsoft.com/graph/powershell/get-started). 15 | 16 | ### Azure Active Directory admin center 17 | 18 | 1. Open a browser and navigate to the [Azure Active Directory admin center](https://aad.portal.azure.com) and login using a **personal account** (aka: Microsoft Account) or **Work or School Account**. 19 | 20 | 1. Select **Azure Active Directory** in the left-hand navigation, then select **App registrations** under **Manage**. 21 | 22 | 1. Select **New registration**. Enter a name for your application, for example, `PowerShell Graph Tutorial`. 23 | 24 | 1. Set **Supported account types** as desired. The options are: 25 | 26 | | Option | Who can sign in? | 27 | |--------|------------------| 28 | | **Accounts in this organizational directory only** | Only users in your Microsoft 365 organization | 29 | | **Accounts in any organizational directory** | Users in any Microsoft 365 organization (work or school accounts) | 30 | | **Accounts in any organizational directory ... and personal Microsoft accounts** | Users in any Microsoft 365 organization (work or school accounts) and personal Microsoft accounts | 31 | 32 | 1. Leave **Redirect URI** empty. 33 | 34 | 1. Select **Register**. On the application's **Overview** page, copy the value of the **Application (client) ID** and save it, you will need it in the next step. If you chose **Accounts in this organizational directory only** for **Supported account types**, also copy the **Directory (tenant) ID** and save it. 35 | 36 | 1. Select **Authentication** under **Manage**. Locate the **Advanced settings** section and change the **Allow public client flows** toggle to **Yes**, then choose **Save**. 37 | 38 | ### PowerShell 39 | 40 | 1. Open PowerShell and run the [RegisterAppForUserAuth.ps1](RegisterAppForUserAuth.ps1) file with the following command, replacing *<audience-value>* with the desired value (see table below). 41 | 42 | > **Note:** The RegisterAppForUserAuth.ps1 script requires a work/school account with the Application administrator, Cloud application administrator, or Global administrator role. 43 | 44 | ```powershell 45 | .\RegisterAppForUserAuth.ps1 -AppName "PowerShell Graph Tutorial" -SignInAudience 46 | ``` 47 | 48 | | SignInAudience value | Who can sign in? | 49 | |----------------------|------------------| 50 | | `AzureADMyOrg` | Only users in your Microsoft 365 organization | 51 | | `AzureADMultipleOrgs` | Users in any Microsoft 365 organization (work or school accounts) | 52 | | `AzureADandPersonalMicrosoftAccount` | Users in any Microsoft 365 organization (work or school accounts) and personal Microsoft accounts | 53 | | `PersonalMicrosoftAccount` | Only personal Microsoft accounts | 54 | 55 | 1. Copy the **Client ID** and **Auth tenant** values from the script output. You will need these values in the next step. 56 | 57 | ```powershell 58 | SUCCESS 59 | Client ID: 2fb1652f-a9a0-4db9-b220-b224b8d9d38b 60 | Auth tenant: common 61 | ``` 62 | 63 | ## Configure the sample 64 | 65 | 1. Open [settings.json](./graphtutorial/settings.example.json) and update the values according to the following table. 66 | 67 | | Setting | Value | 68 | |---------|-------| 69 | | `clientId` | The client ID of your app registration | 70 | | `tenantId` | If you chose the option to only allow users in your organization to sign in, change this value to your tenant ID. Otherwise leave as `common`. | 71 | 72 | ## Run the sample 73 | 74 | In PowerShell, navigate to the project directory and run the following command. 75 | 76 | ```Shell 77 | ./GraphTutorial.ps1 78 | ``` 79 | 80 | **Note:** The scripts included in this sample are not digitally signed. Attempting to run them may result in the following error: 81 | 82 | ```powershell 83 | .\GraphTutorial.ps1: File C:\Source\GraphTutorial.ps1 cannot be loaded. The file C:\Source\GraphTutorial.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170. 84 | ``` 85 | 86 | If you get this error, use the following commands to unblock the file and temporarily allow unsigned scripts in the current PowerShell session. This will not change the default execution policy, the setting is only effective in the current session. 87 | 88 | ```powershell 89 | Unblock-File .\GraphTutorial.ps1 90 | Set-ExecutionPolicy Unrestricted -Scope Process 91 | ``` 92 | -------------------------------------------------------------------------------- /user-auth/RegisterAppForUserAuth.ps1: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | # 5 | param( 6 | [Parameter(Mandatory=$true, 7 | HelpMessage="The friendly name of the app registration")] 8 | [String] 9 | $AppName, 10 | 11 | [Parameter(Mandatory=$false, 12 | HelpMessage="The sign in audience for the app")] 13 | [ValidateSet("AzureADMyOrg", "AzureADMultipleOrgs", ` 14 | "AzureADandPersonalMicrosoftAccount", "PersonalMicrosoftAccount")] 15 | [String] 16 | $SignInAudience = "AzureADandPersonalMicrosoftAccount", 17 | 18 | [Parameter(Mandatory=$false)] 19 | [Switch] 20 | $StayConnected = $false 21 | ) 22 | 23 | # Tenant to use in authentication. 24 | # See https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-device-code#device-authorization-request 25 | $authTenant = switch ($SignInAudience) 26 | { 27 | "AzureADMyOrg" { "tenantId" } 28 | "AzureADMultipleOrgs" { "organizations" } 29 | "AzureADandPersonalMicrosoftAccount" { "common" } 30 | "PersonalMicrosoftAccount" { "consumers" } 31 | default { "invalid" } 32 | } 33 | 34 | if ($authTenant -eq "invalid") 35 | { 36 | Write-Host -ForegroundColor Red "Invalid sign in audience:" $SignInAudience 37 | Exit 38 | } 39 | 40 | # Requires an admin 41 | Connect-MgGraph -Scopes "Application.ReadWrite.All User.Read" -UseDeviceAuthentication -ErrorAction Stop 42 | 43 | # Get context for access to tenant ID 44 | $context = Get-MgContext -ErrorAction Stop 45 | 46 | if ($authTenant -eq "tenantId") 47 | { 48 | $authTenant = $context.TenantId 49 | } 50 | 51 | # Create app registration 52 | $appRegistration = New-MgApplication -DisplayName $AppName -SignInAudience $SignInAudience ` 53 | -IsFallbackPublicClient -ErrorAction Stop 54 | Write-Host -ForegroundColor Cyan "App registration created with app ID" $appRegistration.AppId 55 | 56 | # Create corresponding service principal 57 | if ($SignInAudience -ne "PersonalMicrosoftAccount") 58 | { 59 | New-MgServicePrincipal -AppId $appRegistration.AppId -ErrorAction SilentlyContinue ` 60 | -ErrorVariable SPError | Out-Null 61 | if ($SPError) 62 | { 63 | Write-Host -ForegroundColor Red "A service principal for the app could not be created." 64 | Write-Host -ForegroundColor Red $SPError 65 | Exit 66 | } 67 | 68 | Write-Host -ForegroundColor Cyan "Service principal created" 69 | } 70 | 71 | Write-Host 72 | Write-Host -ForegroundColor Green "SUCCESS" 73 | Write-Host -ForegroundColor Cyan -NoNewline "Client ID: " 74 | Write-Host -ForegroundColor Yellow $appRegistration.AppId 75 | Write-Host -ForegroundColor Cyan -NoNewline "Auth tenant: " 76 | Write-Host -ForegroundColor Yellow $authTenant 77 | 78 | if ($StayConnected -eq $false) 79 | { 80 | Disconnect-MgGraph | Out-Null 81 | Write-Host "Disconnected from Microsoft Graph" 82 | } 83 | else 84 | { 85 | Write-Host 86 | Write-Host -ForegroundColor Yellow ` 87 | "The connection to Microsoft Graph is still active. To disconnect, use Disconnect-MgGraph" 88 | } 89 | # 90 | -------------------------------------------------------------------------------- /user-auth/settings.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "clientId": "YOUR_CLIENT_ID_HERE", 3 | "tenantId": "common", 4 | "graphUserScopes": [ 5 | "user.read", 6 | "mail.read", 7 | "mail.send" 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /user-auth/version: -------------------------------------------------------------------------------- 1 | 1.1 2 | --------------------------------------------------------------------------------