<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Configure Delegated Permissions To Use For Interactive Sessions Archives - the Sysadmin Channel</title>
	<atom:link href="https://thesysadminchannel.com/tag/configure-delegated-permissions-to-use-for-interactive-sessions/feed/" rel="self" type="application/rss+xml" />
	<link>https://thesysadminchannel.com/tag/configure-delegated-permissions-to-use-for-interactive-sessions/</link>
	<description>Documenting My Life as a System Administrator</description>
	<lastBuildDate>Wed, 18 Oct 2023 00:17:36 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
<site xmlns="com-wordpress:feed-additions:1">144174110</site>	<item>
		<title>How To Connect To Microsoft Graph API Using PowerShell</title>
		<link>https://thesysadminchannel.com/how-to-connect-to-microsoft-graph-api-using-powershell/</link>
					<comments>https://thesysadminchannel.com/how-to-connect-to-microsoft-graph-api-using-powershell/#comments</comments>
		
		<dc:creator><![CDATA[Paul Contreras]]></dc:creator>
		<pubDate>Sat, 22 Jan 2022 01:28:11 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Graph API]]></category>
		<category><![CDATA[Powershell]]></category>
		<category><![CDATA[Configure API Permissions For The Application]]></category>
		<category><![CDATA[Configure Application Permissions To Use For Unattended Automation]]></category>
		<category><![CDATA[Configure Delegated Permissions To Use For Interactive Sessions]]></category>
		<category><![CDATA[Configure The App To Use Certificate Based Authentication]]></category>
		<category><![CDATA[Configure The App To Use Client Secret Based Authentication]]></category>
		<category><![CDATA[Connect to Microsoft Graph API Using Interactive Logon]]></category>
		<category><![CDATA[Connect To Microsoft Graph API Using PowerShell]]></category>
		<category><![CDATA[Connect Using A Service Principal and Certificate Based Authentication]]></category>
		<category><![CDATA[Connect Using A Service Principal Secret Based Authentication]]></category>
		<category><![CDATA[Creating an App Registration and Service Principal]]></category>
		<category><![CDATA[Download Microsoft.Graph Powershell Module]]></category>
		<category><![CDATA[How To Get The Scope of a Cmdlet]]></category>
		<category><![CDATA[How To Get The Scopes From The Current Session]]></category>
		<category><![CDATA[Import Self Signed Certificate to Azure AD]]></category>
		<category><![CDATA[Overview of Microsoft Graph API Scopes]]></category>
		<category><![CDATA[Powershell Graph API Examples]]></category>
		<guid isPermaLink="false">https://thesysadminchannel.com/?p=2553</guid>

					<description><![CDATA[<p>Microsoft has confirmed on multiple occasions that the Azure AD Graph Endpoint is deprecated and will be fully decommissioned in the future. This means that if you&#8217;re currently using the AzureAD (or AzureADPreview) Module(s) then after it&#8217;s deprecated, your scripts&#8230; <a href="https://thesysadminchannel.com/how-to-connect-to-microsoft-graph-api-using-powershell/" class="more-link">Continue Reading <span class="meta-nav">&#8594;</span></a></p>
<p>The post <a href="https://thesysadminchannel.com/how-to-connect-to-microsoft-graph-api-using-powershell/">How To Connect To Microsoft Graph API Using PowerShell</a> appeared first on <a href="https://thesysadminchannel.com">the Sysadmin Channel</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Microsoft has confirmed on multiple occasions that the Azure AD Graph Endpoint is deprecated and will be fully decommissioned in the future. This means that if you&#8217;re currently using the AzureAD (or AzureADPreview) Module(s) then after it&#8217;s deprecated, your scripts will no longer work.  In order to avoid any issues, we&#8217;re going to go step by step as well as the multiple ways for <strong>how to connect to Microsoft Graph API using Powershell</strong>.</p>
<p>If you&#8217;re interested in learning more about the decommission of Azure AD Graph, here&#8217;s a doc from <a href="https://docs.microsoft.com/en-us/graph/migrate-azure-ad-graph-overview" rel="noopener" target="_blank">Microsoft</a>.  Below is snippet from that article.</p>
<div id="blockquote1">
Azure Active Directory (Azure AD) Graph is deprecated. Going forward, we will make no further investment in Azure AD Graph, and Azure AD Graph APIs have no SLA or maintenance commitment beyond security-related fixes. Investments in new features and functionalities will only be made in Microsoft Graph.</p>
<p>June 30, 2023 will mark the end of the three-year deprecation period for Azure AD Graph. Before June 30, 2023, existing applications using Azure AD Graph will not be impacted. After June 30, 2023, Azure AD Graph will enter its retirement phase where we will retire it in incremental steps to allow you sufficient time to migrate your applications to Microsoft Graph APIs
</p></div>
<div id="ConnectToGraph" style="scroll-margin-top: 15px;"></div>
<h2>How To Connect To Microsoft Graph API Using PowerShell</h2>
<p>This is going to be a pretty in-depth article on how to connect to Microsoft Graph API using PowerShell so hopefully it will give you a pretty good understanding of all the parts and pieces at play.</p>
<p>Feel free to use the table of contents to navigate through the individual topics.</p>
<div id="tableofcontents">
<h2>Table Of Contents</h2>
<ul>
<li><a href="#DownloadModule">Download Microsoft.Graph Powershell Module</a></li>
<li><a href="#Scopes">Overview of Microsoft Graph API Scopes</a></li>
<ul>
<li><a href="#CmdletScopes">How To Get The Scope of a Cmdlet</a></li>
<li><a href="#CurrentScopes">How To Get The Scopes From The Current Session</a></li>
</ul>
<li><a href="#InteractiveLogon">Connect to Microsoft Graph API Using Interactive Logon</a></li>
<li><a href="#ServicePrincipal">Creating an App Registration and Service Principal</a></li>
<ul>
<li><a href="#CertificateAuthentication">Configure The App To Use Certificate Based Authentication</a></li>
<ul>
<li><a href="#ImportSelfSignedCert">Import Self Signed Certificate to Azure AD</a></li>
</ul>
<li><a href="#SecretAuthentication">Configure The App To Use Client Secret Based Authentication</a></li>
<li><a href="#APIPermissions">Configure API Permissions For The Application</a></li>
<ul>
<li><a href="#ApplicationPermissions">Configure Application Permissions To Use For Unattended Automation</a></li>
<li><a href="#DelegatedPermissions">Configure Delegated Permissions To Use For Interactive Sessions</a></li>
</ul>
<li><a href="#ServicePrincipalCertificateAuthentication">Connect Using A Service Principal and Certificate Based Authentication</a></li>
<li><a href="#ServicePrincipalSecretAuthentication">Connect Using A Service Principal and Secret Based Authentication</a></li>
</ul>
<li><a href="#GraphProfile">Set Microsoft Graph Profile to use v1.0 or Beta Versions</a></li>
<li><a href="#MgContext">How To Get Your Current Permission Scope</a></li>
<li><a href="#Examples">Powershell Graph API Examples</a></li>
<li><a href="#Conclusion">Conclusion</a></li>
</ul>
</div>
<div id="DownloadModule" style="scroll-margin-top: 15px;"></div>
<h2>Download Microsoft.Graph Powershell Module</h2>
<p>In order to get started with Using Microsoft Graph API in your Powershell session, the first thing we want to do is install the <strong>Microsoft.Graph</strong> Module.  This is more commonly known as the Microsoft Graph Powershell SDK and all the cmdlets in this module start with &#8220;Mg&#8221;.  Another thing that I absolutely love about this module is that it works great with Powershell 7.</p>
<p>In this article I&#8217;m going to use PS7 but if you&#8217;re using PS5.1, everything is pretty much the same.</p>
<pre class="brush: powershell; title: ; notranslate">
Install-Module Microsoft.Graph -Scope AllUsers -Force
Install-Module Microsoft.Graph.Beta -Scope AllUsers -Force
</pre>
<p><div id="attachment_3720" style="width: 859px" class="wp-caption aligncenter"><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Install-Microsoft-Graph-Api.png" target="_blank" rel="noopener"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-3720" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Install-Microsoft-Graph-Api.png" alt="Install Microsoft Graph API" width="849" height="329" class="size-full wp-image-3720" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Install-Microsoft-Graph-Api.png?v=1642476411 849w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Install-Microsoft-Graph-Api-768x298.png?v=1642476411 768w" sizes="(max-width: 849px) 100vw, 849px" /></a><p id="caption-attachment-3720" class="wp-caption-text">Note: -Scope AllUsers requires admin rights whereas -Scope CurrentUser does not.</p></div><br />
&nbsp;</p>
<div id="Scopes" style="scroll-margin-top: 15px;"></div>
<h2>Overview of Microsoft Graph API Scopes</h2>
<p>One very important topic to understand when dipping your toes into using Microsoft Graph API are Scopes. Understanding Scopes will definitely ease the transition and flatten the learning curve. I&#8217;m not going to lie when I first started using it, I ran into many challenges. Especially with documentation! Since this is still relatively new there&#8217;s not a ton of articles or examples at the ready.<br />
&nbsp;</p>
<p>As with anything, the more you practice and learn, the easier it becomes. With that said, Microsoft Graph API as a whole encompasses all of the APIs that are available in your tenant.  However under the hood, there&#8217;s an API for users, authentication methods, MS Teams, Azure Key Vault and many more but for simplicity sake it&#8217;s all referred to as Graph API.<br />
&nbsp;</p>
<p>Just because your account has permissions to a certain role, doesn&#8217;t mean it&#8217;s automatically granted that scope.  Here&#8217;s a real world example for you.<br />
&nbsp;</p>
<p>Buzz Lightyear has the &#8216;User Administrator&#8217; Azure AD Role which allows him to manage all aspects of users and groups, including resetting passwords for limited admins. However, if he only connects using the User.Read.All scope then it will not allow him to modify any properties on the account even though the underlying permissions are there.<br />
&nbsp;</p>
<p>A simple way to put it.  Scopes are permissions for the session, whereas roles are permissions for the account.  Hopefully that makes sense.</p>
<div id="CmdletScopes" style="scroll-margin-top: 15px;"></div>
<h3>How To Get The Scope of a Cmdlet</h3>
<p>It&#8217;s a good idea to only use the scopes that are applicable to the current session to ensure you&#8217;re not over-privileged at run-time.  But how exactly do we know what scopes are needed for the cmdlets we want to use?<br />
&nbsp;</p>
<p>To answer this question, I always turn to <a href="https://developer.microsoft.com/en-us/graph/graph-explorer" rel="noopener" target="_blank">Graph Explorer</a>.  It&#8217;s by far easier for me to quickly check here than read through the documentation.  if you prefer the documentation, by all means go ahead but this has typically worked well for me.</p>
<p>Let&#8217;s take a look at Graph Explorer to give a better example of what I&#8217;m talking about.<br />
<div id="attachment_3725" style="width: 1779px" class="wp-caption aligncenter"><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Consent-Graph-Api1.png" target="_blank" rel="noopener"><img decoding="async" aria-describedby="caption-attachment-3725" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Consent-Graph-Api1.png" alt="Grant Consent Graph Api" width="1769" height="813" class="size-full wp-image-3725" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Consent-Graph-Api1.png?v=1642480678 1769w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Consent-Graph-Api1-1024x471.png?v=1642480678 1024w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Consent-Graph-Api1-768x353.png?v=1642480678 768w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Consent-Graph-Api1-1536x706.png?v=1642480678 1536w" sizes="(max-width: 1769px) 100vw, 1769px" /></a><p id="caption-attachment-3725" class="wp-caption-text">Note: I am signed in as myself to allow queries from Graph Explorer to be ran under my tenant and my actual data.  If you&#8217;re not signed in, sample data can be used.</p></div><br />
&nbsp;</p>
<p>In the screenshot above, I ran a sample query to list all of the items in my OneDrive.  We can also see on the upper right pane under <strong>Permissions</strong> what scopes are needed.  In this case, I should be good to go with &#8216;Files.Read.All&#8217; if I plan on using it for reading files outside my own account.<br />
&nbsp;</p>
<p>However, one important thing to take note on is the Status column.  All permissions require consent in order to run.  An administrator can grant consent on behalf of the entire organization if needed, or grant consent to the individual identity.  Once consent is granted, you will not need to reconsent on any future sessions since it stays tied to the identity. A lot of layers and restrictions are put in place so I see it as a security win!</p>
<div id="CurrentScopes" style="scroll-margin-top: 15px;"></div>
<h3>How To Get The Scopes From The Current Session</h3>
<p>Last but not least, if you&#8217;re connected and you want a reminder of what Scopes you&#8217;re currently using, you can always use the <code>Get-MgContext</code> cmdlet to display an output.<br />
<div id="attachment_3734" style="width: 1009px" class="wp-caption aligncenter"><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Get-MgContext-Example1.png" target="_blank" rel="noopener"><img decoding="async" aria-describedby="caption-attachment-3734" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Get-MgContext-Example1.png" alt="Get-MgContext Example" width="999" height="372" class="size-full wp-image-3734" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Get-MgContext-Example1.png?v=1642532977 999w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Get-MgContext-Example1-768x286.png?v=1642532977 768w" sizes="(max-width: 999px) 100vw, 999px" /></a><p id="caption-attachment-3734" class="wp-caption-text">I am signed in under delegated permissions using Interactive Logon.</p></div></p>
<div id="InteractiveLogon" style="scroll-margin-top: 15px;"></div>
<h2>Connect to Microsoft Graph API Using Interactive Logon</h2>
<p>The quickest and easiest way to connect to Microsoft Graph API using PowerShell is to use delegated permissions with interactive sign-in.  The screenshot above shows the aftermath, however, let&#8217;s look at how we can get there.</p>
<ul>
<li>Open Powershell where the module was downloaded</li>
<li>Type <strong>Connect-Graph</strong></li>
<li>Enter in the credentials in the browser that pops up</li>
<li>You should see <strong>authentication complete</strong></li>
</ul>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-Graph-API-using-Delegated-Authentication.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-Graph-API-using-Delegated-Authentication.png" alt="Connect Graph API using Delegated Authentication" width="978" height="572" class="aligncenter size-full wp-image-3733" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-Graph-API-using-Delegated-Authentication.png?v=1642532767 978w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-Graph-API-using-Delegated-Authentication-768x449.png?v=1642532767 768w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-Graph-API-using-Delegated-Authentication-300x175.png?v=1642532767 300w" sizes="(max-width: 978px) 100vw, 978px" /></a><br />
&nbsp;<br />
Something to note here is that simply calling Connect-Graph (Connect-MgGraph) is using the DEFAULT Graph PowerShell Application.  Some folks aren&#8217;t comfortable with using that because it has all of the delegated permissions added, however, there is a way to use your own app for a specific purpose.  This is useful so we&#8217;re not over-permissioning users.  The way to do that is to use the AppId (ClientId) and omit the key credentials (certificate or secret)</p>
<pre class="brush: powershell; title: ; notranslate">
Connect-Graph -AppId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -TenantId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
</pre>
<p>&nbsp;</p>
<p>There are some pros and cons with using interactive logon. The biggest drawback in my opinion is that this is in no way usable for automation, albeit, it&#8217;s also not intended for automation purposes.<br />
&nbsp;<br />
If you&#8217;re looking to setup an account for automated use, creating an App Registration and Service Principal is definitely the route to go.  Let&#8217;s continue along and go through the motions on how to set that up.</p>
<div id="ServicePrincipal" style="scroll-margin-top: 15px;"></div>
<h2>Creating an App Registration and Service Principal</h2>
<p>As mentioned, using an App Registration along with a Service Principal is definitely the way to go when you want to use it for automation.  This has really become my go-to because its quick, easy and removes a lot of the guess work.  It&#8217;s also great for security but we&#8217;ll touch on that a little later.<br />
&nbsp;</p>
<div id="blockquote2">
By default, when you create an application, a Service Principal is automatically created on your behalf and is named similarly to your application. The Service Principal however, is the identity that&#8217;s created for use with the application and it can be found under the <a href="https://portal.azure.com/#blade/Microsoft_AAD_IAM/StartboardApplicationsMenuBlade/AppAppsPreview/menuId/" rel="noopener" target="_blank">Enterprise Applications</a> blade in your tenant.</p>
<p>In short, <strong>the Service Principal is what&#8217;s actually logging into Azure and the application is setting the API permissions</strong> that it&#8217;s bound to.
</div>
<p>&nbsp;</p>
<p>That was kind of a lot to take in, so for now, let&#8217;s go through the steps to create an App Registration.</p>
<ul>
<li>In your Azure AD Tenant, navigate to <strong>AzureAD </strong>-> <strong>App registrations</strong></li>
<ul>
<li>Direct Link: <a href="https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps" rel="noopener" target="_blank">https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps</a></li>
</ul>
<li>Click on <strong>New registration</strong></li>
<li>Enter in the preferred <strong>name</strong>.  I&#8217;ll name mine &#8216;<strong>My Automation App</strong>&#8216;</li>
<li>Under supported account types: Choose <strong>Single tenant</strong></li>
<li>Under Redirect URI: choose web and set the URL address to http://localhost</li>
<li>Click Register</li>
</ul>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Register-an-app-Microsoft-Graph-API.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Register-an-app-Microsoft-Graph-API.png" alt="Register an app Microsoft Graph API" width="1140" height="669" class="aligncenter size-full wp-image-3738" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Register-an-app-Microsoft-Graph-API.png?v=1642731497 1140w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Register-an-app-Microsoft-Graph-API-1024x601.png?v=1642731497 1024w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Register-an-app-Microsoft-Graph-API-768x451.png?v=1642731497 768w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Register-an-app-Microsoft-Graph-API-300x175.png?v=1642731497 300w" sizes="(max-width: 1140px) 100vw, 1140px" /></a><br />
&nbsp;</p>
<p>Once that&#8217;s complete you should automatically be redirected back to App&#8217;s overview page.  While you&#8217;re there, be sure to jot down the Application (client) Id and the Directory (tenant) ID.  You&#8217;ll need this later when you&#8217;re making up your connection string but that&#8217;s it,  You&#8217;ve made an app in your tenant.</p>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/App-registration-over-page.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/App-registration-over-page.png" alt="App registration over page" width="1019" height="430" class="aligncenter size-full wp-image-3740" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/App-registration-over-page.png?v=1642731860 1019w, https://thesysadminchannel.com/wp-content/uploads/2022/01/App-registration-over-page-768x324.png?v=1642731860 768w" sizes="(max-width: 1019px) 100vw, 1019px" /></a></p>
<div id="CertificateAuthentication" style="scroll-margin-top: 15px;"></div>
<h3>Configure The App To Use Certificate Based Authentication</h3>
<p>Now that we&#8217;ve talked a bit about Service Principals, it&#8217;s important to note that there are 2 methods to authenticating to your newly created application.  Those methods are using a certificate or a client secret. We&#8217;ll cover both ways in this article, but we&#8217;ll start with certificates first.<br />
&nbsp;</p>
<p>Azure allows you to use a either a self-signed certificate or a certificate from your PKI infrastructure.  The more secure route of these 2 options would definitely be your PKI infrastructure, but it&#8217;s also understandable that not every environment has one.  I don&#8217;t have a PKI infrastructure in my lab so I&#8217;m going to share the steps with using a self-signed certificate.  The end goal is have to a .pfx on the client machine and a .cer file that&#8217;s uploaded to Azure.</p>
<pre class="brush: powershell; title: ; notranslate">
#splatting for human readability
$CertParam = @{
    'KeyAlgorithm'      = 'RSA'
    'KeyLength'         = 2048
    'KeyExportPolicy'   = 'NonExportable'
    'DnsName'           = 'server.thesysadminchannel.com'
    'FriendlyName'      = 'GraphApi - My Automation App'
    'CertStoreLocation' = 'Cert:\CurrentUser\My\'
    'NotAfter'          = (Get-Date).AddYears(1)
}

#Creating self signed cert with parameters from above.
$Cert = New-SelfSignedCertificate @CertParam

</pre>
<div id="attachment_3746" style="width: 953px" class="wp-caption aligncenter"><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/New-Self-Signed-Cert-for-Azure-AD1.png" target="_blank" rel="noopener"><img decoding="async" aria-describedby="caption-attachment-3746" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/New-Self-Signed-Cert-for-Azure-AD1.png" alt="New Self Signed Cert for Azure AD" width="943" height="399" class="size-full wp-image-3746" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/New-Self-Signed-Cert-for-Azure-AD1.png?v=1642735776 943w, https://thesysadminchannel.com/wp-content/uploads/2022/01/New-Self-Signed-Cert-for-Azure-AD1-768x325.png?v=1642735776 768w" sizes="(max-width: 943px) 100vw, 943px" /></a><p id="caption-attachment-3746" class="wp-caption-text">Note: The DnsName should be the Server&#8217;s Fully Qualified Domain Name (FQDN)</p></div>
<div id="ImportSelfSignedCert" style="scroll-margin-top: 15px;"></div>
<h3>Import Self Signed Certificate to Azure AD</h3>
<p>Once the self signed certificate is created from above, we&#8217;ll need to export it to a .cer and upload that to Azure AD.  Since we&#8217;re already in Powershell, let&#8217;s export it using Powershell.</p>
<pre class="brush: powershell; title: ; notranslate">
#Since we captured the output to the $Cert variable in our previous step.  We'll use that to specify the cert parameter. 
#The .cer file will exported to the user's desktop.

Export-Certificate -Cert $Cert -FilePath $Home\Desktop\MyAutomationApp.cer
</pre>
<p>&nbsp;</p>
<p>Back in Azure AD:</p>
<ul>
<li>Navigate to Certificates &#038; secrets</li>
<li>Click the certificates tab</li>
<li>Click Upload certificate</li>
<li>Click the folder icon and browse to your desktop to select the exported cert</li>
<li>Click Add</li>
</ul>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD.png" alt="Upload Certificate to Azure AD" width="1785" height="910" class="aligncenter size-full wp-image-3750" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD.png?v=1642743182 1785w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD-1024x522.png?v=1642743182 1024w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD-768x392.png?v=1642743182 768w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD-1536x783.png?v=1642743182 1536w" sizes="(max-width: 1785px) 100vw, 1785px" /></a></p>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD-Confirmation.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD-Confirmation.png" alt="Upload Certificate to Azure AD Confirmation" width="1111" height="245" class="aligncenter size-full wp-image-3752" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD-Confirmation.png?v=1642743546 1111w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD-Confirmation-1024x226.png?v=1642743546 1024w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Upload-Certificate-to-Azure-AD-Confirmation-768x169.png?v=1642743546 768w" sizes="(max-width: 1111px) 100vw, 1111px" /></a></p>
<p>We can confirm that the certificate is now uploaded to the Azure application.</p>
<div id="SecretAuthentication" style="scroll-margin-top: 15px;"></div>
<h3>Configure The App To Use Client Secret Based Authentication</h3>
<p>Our next option for authenticating to a Service Principal is being able to use a client secret.  Not to throw shade at using secrets, but personally, I prefer using a certificate because I can get a bit more control over it and can prioritize security above all else.<br />
&nbsp;</p>
<p>What do you mean by that you may ask?  Well, for one, a secret can be passed around and used anywhere just like a regular password can. Meaning a user/app owner can share this secret with other teammates and it&#8217;s up to the user to uphold the security measures.<br />
&nbsp;</p>
<p>Two, this introduces a chicken and egg scenario.  Say this application was used for some kind of unattended automation, you&#8217;re going to need a way to automatically grab this secret to pass into the connection string.  There are ways to programmatically retrieve this using Azure Key Vault or Secrets Management PowerShell Module but now you&#8217;ll need to store <em><strong>that</strong></em> password somewhere securely.  Again, security will most likely be left to the user so your best case scenario is everything is encrypted and stored securely in a vault.  </p>
<p>Or, worse case scenario the secret (along with the Appid and TenantId) are saved to that person&#8217;s personal github repo and has it open to the public.  So before you go down this path, think about how your users would likely treat it.</p>
<p>Now that I got that off my chest, let&#8217;s move forward with generating a secret for your app.<br />
&nbsp;</p>
<p>Back in Azure AD:</p>
<ul>
<li>Navigate to Certificates &#038; secrets</li>
<li>Click the Client Secrets tab</li>
<li>Click New client secret</li>
<li>Enter a useful description.  e.g TicketNumber and Person who&#8217;s primarily responsible for it</li>
<li>Set the expiration date to the recommended 6 months</li>
<li>Click Add</li>
</ul>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Creating-a-client-secret-in-azure-ad.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Creating-a-client-secret-in-azure-ad.png" alt="Creating a client secret in azure ad" width="1793" height="873" class="aligncenter size-full wp-image-3757" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Creating-a-client-secret-in-azure-ad.png?v=1642746937 1793w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Creating-a-client-secret-in-azure-ad-1024x499.png?v=1642746937 1024w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Creating-a-client-secret-in-azure-ad-768x374.png?v=1642746937 768w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Creating-a-client-secret-in-azure-ad-1536x748.png?v=1642746937 1536w" sizes="(max-width: 1793px) 100vw, 1793px" /></a></p>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Confirm-creating-a-client-secret-in-azure-ad.png"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Confirm-creating-a-client-secret-in-azure-ad.png" alt="Confirm creating a client secret in azure ad" width="1122" height="224" class="aligncenter size-full wp-image-3758" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Confirm-creating-a-client-secret-in-azure-ad.png?v=1642747217 1122w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Confirm-creating-a-client-secret-in-azure-ad-1024x204.png?v=1642747217 1024w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Confirm-creating-a-client-secret-in-azure-ad-768x153.png?v=1642747217 768w" sizes="(max-width: 1122px) 100vw, 1122px" /></a></p>
<p><strong>Important</strong>: Immediately copy the secret because once you leave the page it&#8217;s no longer accessible and you&#8217;ll have to generate a new one. Make sure it&#8217;s secured as well.</p>
<div id="APIPermissions" style="scroll-margin-top: 15px;"></div>
<h3>Configure API Permissions For The Application</h3>
<p>Moving along to our next topic which will be to provide an overview of the API permissions that are going to be granted for the application.  These permission sets can either be Application or Delegated.  The scenario for which the application is used will most likely dictate which sets are used but let&#8217;s give a brief overview and how to set them.</p>
<div id="ApplicationPermissions" style="scroll-margin-top: 15px;"></div>
<h3>Configure Application Permissions To Use For Unattended Automation</h3>
<p>If you want your application to 100% automated, choosing Application permissions is going to be your best bet since it doesn&#8217;t require any user interaction whatsoever. </p>
<p>Going back into your application:</p>
<ul>
<li>Navigate to API permissions</li>
<li>Choose Add a permission</li>
<li>Choose Microsoft Graph (since this is what is most commonly used)</li>
<li>Choose Application Permissions</li>
<li>Select the permissions that are required for this app</li>
<ul>
<li>To get started, choose Dirctory.Read.All and User.Read.All</li>
</ul>
<li>Click Add</li>
<li>Grant admin consent for your organization</li>
</ul>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Add-Application-Permissions-to-Graph-API-app1.gif" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Add-Application-Permissions-to-Graph-API-app1.gif" alt="Add Application Permissions to Graph API app" width="1280" height="626" class="aligncenter size-full wp-image-3767" /></a></p>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Admin-consent.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Admin-consent.png" alt="Grant Admin consent" width="1153" height="250" class="aligncenter size-full wp-image-3770" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Admin-consent.png 1153w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Admin-consent-1024x222.png 1024w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Grant-Admin-consent-768x167.png 768w" sizes="(max-width: 1153px) 100vw, 1153px" /></a></p>
<div id="DelegatedPermissions" style="scroll-margin-top: 15px;"></div>
<h3>Configure Delegated Permissions To Use For Interactive Sessions</h3>
<p>As you can see, delegated permissions are located in the same place that application permissions are so you&#8217;ll just need to select that instead of the app box.<br />
&nbsp;</p>
<p>The key take away between the 2 permissions are this:</p>
<ul>
<li><strong>Delegated Permissions:</strong> Used by apps that have a signed-in user present</li>
<li><strong>Application Permissions:</strong> Used by apps that run unattended automation. Application permissions can only be consented by an administrator</li>
</ul>
<p>Depending on the permissions applied, admin consent will also be needed for the permissions.  The Admin consent required column should notify you if consent is needed.</p>
<div id="ServicePrincipalCertificateAuthentication" style="scroll-margin-top: 15px;"></div>
<h3>Connect Using A Service Principal and Certificate Based Authentication</h3>
<p>We&#8217;re finally nearing the home stretch here and got our App registration and Service Principal created.  Now we just need to bring it all together to connect to Microsoft Graph API using Powershell. In this case we&#8217;re going to start off by connecting using a certificate.  Here&#8217;s how we do that.</p>
<pre class="brush: powershell; title: ; notranslate">
$AppId = &quot;90cb4cab-xxxx-xxxx-xxxx-xxxxxxxxxxxx&quot;
$TenantId = &quot;95cb1f18-xxxx-xxxx-xxxx-xxxxxxxxxxxx&quot;
$Certificate = Get-ChildItem Cert:\CurrentUser\My\180CE345F9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Connect-Graph -TenantId $TenantId -AppId $AppId -Certificate $Certificate
</pre>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-To-Microsoft-Graph-API-using-Powershell-Cert-Auth.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-To-Microsoft-Graph-API-using-Powershell-Cert-Auth.png" alt="Connect To Microsoft Graph API using Powershell - Cert Auth" width="929" height="213" class="aligncenter size-full wp-image-3773" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-To-Microsoft-Graph-API-using-Powershell-Cert-Auth.png 929w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-To-Microsoft-Graph-API-using-Powershell-Cert-Auth-768x176.png 768w" sizes="(max-width: 929px) 100vw, 929px" /></a><br />
&nbsp;</p>
<p>If all is successful, you should see &#8220;Welcome To Microsoft Graph!&#8221;  Congrats, you&#8217;re now successfully connected to Microsoft Graph API using certificate based authentication!</p>
<div id="ServicePrincipalSecretAuthentication" style="scroll-margin-top: 15px;"></div>
<h3>Connect Using A Service Principal and Secret Based Authentication</h3>
<p>If you decided going the secret route was the better option for your application, let&#8217;s take a second to show you how to connect using this method.  To get started you will need to install the MSAL.PS Powershell module from the PSGallery.<br />
&nbsp;</p>
<p>This module allows you to create an access token which you will need to connect to MSGraph.</p>
<pre class="brush: powershell; title: ; notranslate">
#Install MSAL.PS module for all users (requires admin rights)
Install-Module MSAL.PS -Scope AllUsers -Force

#Generate Access Token to use in the connection string to MSGraph
$AppId = '90cb4cab-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$TenantId = '95cb1f18-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$ClientSecret = 'app registration secret'

Import-Module MSAL.PS
$MsalToken = Get-MsalToken -TenantId $TenantId -ClientId $AppId -ClientSecret ($ClientSecret | ConvertTo-SecureString -AsPlainText -Force)

#Connect to Graph using access token
Connect-Graph -AccessToken $MsalToken.AccessToken

</pre>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-To-Microsoft-Graph-API-using-Powershell-Secret-Auth.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-To-Microsoft-Graph-API-using-Powershell-Secret-Auth.png" alt="Connect-To-Microsoft-Graph-API-using-Powershell-Secret-Auth" width="1099" height="316" class="aligncenter size-full wp-image-3774" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-To-Microsoft-Graph-API-using-Powershell-Secret-Auth.png 1099w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-To-Microsoft-Graph-API-using-Powershell-Secret-Auth-1024x294.png 1024w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Connect-To-Microsoft-Graph-API-using-Powershell-Secret-Auth-768x221.png 768w" sizes="(max-width: 1099px) 100vw, 1099px" /></a></p>
<p>If all is successful, you should see &#8220;Welcome To Microsoft Graph!&#8221;  Congrats, you&#8217;re now successfully connected to Microsoft Graph API using secret based authentication!</p>
<div id="GraphProfile" style="scroll-margin-top: 15px;"></div>
<h2>Set Microsoft Graph Profile to use v1.0 or Beta Versions</h2>
<p>Microsoft has 2 versions of Graph API that we&#8217;re able to send requests to. v1.0 which is all generally available endpoints and beta, which is the prerelease version.</p>
<p>It&#8217;s important to note that some items will only work in the beta profile so you might want to give that a try if you see something online and want to try it for yourself.  In any event, we can change profiles by using the Beta prefix on any cmdlet.  Here is a simple example.</p>
<ul>
<li>Get-MgUser -UserId username@thesysadminchannel.com</li>
<li>Get-MgBetaUser -UserId username@thesysadminchannel.com</li>
</ul>
<p>&nbsp;</p>
<p>Something to note when using the v1.0 and beta versions is that the beta returns more properties.  The v1.0 cmdlet typically returns the skeleton properties so the query can run faster.  Depending on what you&#8217;re querying, it is also a good idea to use the -Property parameter so you can get the attributes you need without having to call everything.  This is essential for larger environments.</p>
<div id="Examples" style="scroll-margin-top: 15px;"></div>
<h2>Powershell Graph API Examples</h2>
<p>Finally we&#8217;re at a point where we&#8217;re able to connect To Microsoft Graph API using PowerShell to send some requests.  I&#8217;ll get a user object and group object so you can see how quick and easy it is.</p>
<pre class="brush: powershell; title: ; notranslate">
#Search user by UserPrincipalName
PS C:\&gt; Get-MgUser -UserId buzz@thesysadminchannel.com | select UserPrincipalName, DisplayName

UserPrincipalName           DisplayName
-----------------           -----------
buzz@thesysadminchannel.com Buzz Lightyear

#Get Top 2 objects of Get-MgUser
PS C:\&gt; Get-MgUser -Top 2 | select UserPrincipalName, DisplayName

UserPrincipalName               DisplayName
-----------------               -----------
aaduser3@thesysadminchannel.com aaduser3
aaduser4@thesysadminchannel.com aaduser4

#Get all the groups with fakegroup in the DisplayName
PS C:\&gt; Get-MgGroup -Search &quot;DisplayName:fakegroup&quot; -ConsistencyLevel eventual | select DisplayName, Description

DisplayName    Description
-----------    -----------
SG - FakeGroup A group that's not real
FakeGroup

#Get group object by Id.
PS C:\&gt; Get-MgGroup -GroupId 51fb0824-5318-448c-8de6-ffc06c192b0d

Id                                   DisplayName    Description             GroupTypes
--                                   -----------    -----------             ----------
51fb0824-5318-448c-8de6-ffc06c192b0d SG - FakeGroup A group that's not real {}

PS C:\&gt;
</pre>
<p><a href="https://thesysadminchannel.com/wp-content/uploads/2022/01/Powershell-Graph-API-Examples.png" target="_blank" rel="noopener"><img decoding="async" src="https://thesysadminchannel.com/wp-content/uploads/2022/01/Powershell-Graph-API-Examples.png" alt="Powershell Graph API Examples" width="1099" height="632" class="aligncenter size-full wp-image-3776" srcset="https://thesysadminchannel.com/wp-content/uploads/2022/01/Powershell-Graph-API-Examples.png 1099w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Powershell-Graph-API-Examples-1024x589.png 1024w, https://thesysadminchannel.com/wp-content/uploads/2022/01/Powershell-Graph-API-Examples-768x442.png 768w" sizes="(max-width: 1099px) 100vw, 1099px" /></a></p>
<div id="Conclusion" style="scroll-margin-top: 15px;"></div>
<h2>Conclusion</h2>
<p>I&#8217;m hoping this deep dive on how to connect to Microsoft Graph API using PowerShell was informative enough to get your started.  As an IT Professional, this is something you can use to automate many of your Azure tasks.  If you&#8217;re a developer, this can be useful to interact with other applications in your wheelhouse.<br />
&nbsp;</p>
<p>If you&#8217;re looking for more Powershell content, be sure to check out our <a href="https://thesysadminchannel.com/powershell/" rel="noopener" target="_blank">category full of useful scripts</a>.  The same goes for <a href="https://thesysadminchannel.com/azure/" rel="noopener" target="_blank">Azure Active Directory</a>.  I&#8217;ll also be starting a new series of posts dedicated to Graph API so stay tuned.</p>
<p>The post <a href="https://thesysadminchannel.com/how-to-connect-to-microsoft-graph-api-using-powershell/">How To Connect To Microsoft Graph API Using PowerShell</a> appeared first on <a href="https://thesysadminchannel.com">the Sysadmin Channel</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://thesysadminchannel.com/how-to-connect-to-microsoft-graph-api-using-powershell/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2553</post-id>	</item>
	</channel>
</rss>
