Follow

Follow

How to connect to the Microsoft Graph API using saved user credentials

Ondrej Sebela's photo
Ondrej Sebela
ยทJan 25, 2023ยท

2 min read

Play this article

The official command Connect-MgGraph doesn't support authentication using saved credentials. But there is a solution ๐Ÿ‘

Preview v.2 version of the Az.Accounts module supports passing saved credentials in `Connect-MgGraph` by default.

You can authenticate to Azure using Connect-AzAccount at first and then save generated token and use it for making a connection to the Graph API ๐Ÿ™‚

How?

  • Make sure you have installed&imported modules Az.Accounts, Microsoft.Graph.Authentication ๐Ÿ‘‡
Install-Module Az.Accounts, Microsoft.Graph.Authentication
  • Paste the Connect-MgGraphViaCred function into your console ๐Ÿ‘‡

      #requires -modules Az.Accounts,Microsoft.Graph.Authentication
      function Connect-MgGraphViaCred {
          <#
          .SYNOPSIS
          Function for connecting to the Microsoft Graph using given credentials.
          This option is unavailable with official Connect-MgGraph command.
    
          .DESCRIPTION
          Function for connecting to the Microsoft Graph using given credentials.
          This option is unavailable with official Connect-MgGraph command.
    
          .PARAMETER credential
          Credential object.
    
          .PARAMETER tenant
          (optional) Azure tenant name or id.
    
          .EXAMPLE
          $cred = Get-Credential
          Connect-MgGraphViaCred -credential $cred
          #>
    
          [CmdletBinding()]
          param (
              [Parameter(Mandatory = $true)]
              [System.Management.Automation.PSCredential] $credential,
    
              [string] $tenant = $_tenantDomain
          )
    
          # connect to Azure using credentials
          $param = @{
              Credential = $credential
              Force      = $true
          }
          if ($tenant) { $param.tenant = $tenant }
          $null = Connect-AzAccount @param
    
          # retrieve token for MSGraph
          $token = (Get-AzAccessToken -ResourceTypeName MSGraph -ErrorAction Stop).token
    
          # convert token string to securestring if new version of Connect-MgGraph is used
          if ((Get-Help Connect-MgGraph -Parameter accesstoken).type.name -eq "securestring") {
              $token = ConvertTo-SecureString $token -AsPlainText -Force
          }
          # use token for connecting to Microsoft Graph
          $null = Connect-MgGraph -AccessToken $token -ErrorAction Stop
      }
    
  • Call the function Connect-MgGraphViaCred like ๐Ÿ‘‡

      $cred = Get-Credential
    
      Connect-MgGraphViaCred -credential $cred
    
  • Call any *MG* (Get-MgUser, ...) command you like ๐Ÿ™‚

Did you find this article valuable?

Support Ondrej Sebela by becoming a sponsor. Any amount is appreciated!

See recent sponsors |ย Learn more about Hashnode Sponsors
ย 
Share this