Get-AzureToken.psm1
# Get-AzureToken.psm1 function Get-AzureToken { param( [Parameter(Mandatory=$false)] [string]$TenantId="common", [Parameter(Mandatory=$false)] [string]$ClientId="1950a258-227b-4e31-a9cf-717495945fc2", [Parameter(Mandatory=$false)] [string]$Authority, [Parameter(Mandatory=$false)] [string]$LoginHint, [Parameter(Mandatory=$false)] [string]$Scopes = "https://graph.microsoft.com/.default" ) Import-Module MSAL.PS try { Write-Host "Starting interactive authentication..." -ForegroundColor Cyan # Build authentication parameters $authParams = @{ ClientId = $ClientId TenantId = $TenantId Scopes = $Scopes Interactive = $true } # Add custom authority if specified if ($Authority) { $authParams.Authority = $Authority } # Add login hint if specified if ($LoginHint) { $authParams.LoginHint = $LoginHint Write-Host "Using login hint: $LoginHint" -ForegroundColor Yellow } Write-Host "Opening browser for authentication..." $tokenResponse = Get-MsalToken @authParams if ($tokenResponse.AccessToken) { Write-Host "✓ Authentication successful!" -ForegroundColor Green Write-Host "Access Token acquired for: $($tokenResponse.Account.Username)" Write-Host "Token expires: $($tokenResponse.ExpiresOn)" # Return the token for use return $tokenResponse } else { throw "Failed to acquire access token" } } catch { Write-Error "Authentication failed: $($_.Exception.Message)" return $null } # Example usage: # # Basic interactive auth: # $token = .\Get-AzureToken.ps1 -ClientId "your-app-id" # # With specific email address: # $token = .\Get-AzureToken.ps1 -ClientId "your-app-id" -LoginHint "user@contoso.com" # # Multi-tenant with email hint: # $token = .\Get-AzureToken.ps1 -TenantId "common" -ClientId "your-app-id" -LoginHint "user@any-tenant.com" # # With custom authority: # $token = .\Get-AzureToken.ps1 -ClientId "your-app-id" -Authority "https://login.microsoftonline.com/organizations" # # Use the token: # $headers = @{ Authorization = "Bearer $($token.AccessToken)" } # Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/me" -Headers $headers } # Export only the functions you want users to access Export-ModuleMember -Function Get-AzureToken |