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

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` 👇
    

```plaintext
Install-Module Az.Accounts, Microsoft.Graph.Authentication
```

* Paste the `Connect-MgGraphViaCred` function into your console 👇
    
    ```plaintext
    #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 👇
    
    ```plaintext
    $cred = Get-Credential
    
    Connect-MgGraphViaCred -credential $cred
    ```
    
* Call any \*MG\* (Get-MgUser, ...) command you like 🙂
