functions/Connect-AzureADUserAuthenticationMethod.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function Connect-AzureADUserAuthenticationMethod {
    [CmdletBinding(DefaultParameterSetName = 'Interactive')]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $TenantId,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
        [System.Security.Cryptography.X509Certificates.X509Certificate2]
        $Certificate,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'Thumbprint')]
        [string]
        $Thumbprint,
        
        [Parameter(ParameterSetName = 'Thumbprint')]
        [string]
        $CertificateStore = 'Cert:\CurrentUser\My',
        
        [Parameter(ParameterSetName = 'Interactive')]
        [switch]
        $Interactive,
        
        [string]
        $ClientID = "",
        
        [string]
        $RedirectUri = "urn:ietf:wg:oauth:2.0:oob",
        
        [string]
        $BaseUri = 'https://graph.microsoft.com/beta/',
        
        [switch]
        $PassThru
    )
    
    process {
        if ($Thumbprint) {
            try { $Certificate = Get-Item -Path (Join-Path -Path $CertificateStore -ChildPath $Thumbprint) }
            catch { throw "Unable to find certificate $Thumbprint in certificate store $CertificateStore !" }
        }
        switch ($PSCmdlet.ParameterSetName) {
            'Interactive' {
                try { $token = Get-MsalToken -TenantId $TenantId -ClientId $ClientID -RedirectUri $RedirectUri -Interactive }
                catch {
                    Write-Warning "Failed to authenticate to tenant $TenantID : $_"
                    throw
                }
            }
            default {
                try { $token = Get-MsalToken -TenantId $TenantId -ClientId $ClientID -ClientCertificate $Certificate }
                catch {
                    Write-Warning "Failed to authenticate to tenant $TenantID : $_"
                    throw
                }
            }
        }
        
        $script:msgraphToken = $token
        $script:baseUri = $BaseUri
        $script:tenantID = $TenantId
        $script:clientID = $ClientID
        $script:redirectUri = $RedirectUri
        $script:clientCertificate = $Certificate
        
        if ($PassThru) { $token }
    }
}