如何使用PowerShell通过Google/Microsoft OAuth认证访问Truecaller网站?
Got it, let's tackle this OAuth problem you're facing with Truecaller and PowerShell. The core issue here is that Truecaller's Google OAuth client is set up as a web application, which restricts you to their pre-configured redirect URI—so you can't use the urn:ietf:wg:oauth:2.0:oob trick for desktop apps, and the web redirect doesn't expose the authorization code directly to your script.
The workaround here is to automate a real browser session to intercept the authorization code before it gets passed to Truecaller's callback endpoint. Here's a practical, step-by-step implementation:
Approach: Browser Automation with Playwright
We'll use the Playwright PowerShell module to simulate a full browser flow. This lets us:
- Navigate to the Google OAuth login page
- Complete authentication (including 2FA if needed)
- Capture the redirect URL containing the authorization code
- Exchange that code for an access token
- Use the token to access Truecaller's protected pages
Step-by-Step Implementation
1. Install Playwright
First, set up the Playwright module and browser binaries:
# Install the Playwright PowerShell module (run once) Install-Module -Name Playwright -Scope CurrentUser -Force # Install required browser binaries (run once) pwsh -Command "Install-Playwright"
2. Full Automation Script
This script handles the entire flow from login to accessing Truecaller:
# OAuth Configuration (match Truecaller's Google client settings) $clientId = "22378802832-klpcj5dosalhnu0vshg3hjm9qgidmp8j.apps.googleusercontent.com" $redirectUri = "https://www.truecaller.com/auth/google/callback" $scopes = "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/contacts.readonly" $authUrl = "https://accounts.google.com/o/oauth2/v2/auth?client_id=$clientId&scope=$([Uri]::EscapeDataString($scopes))&access_type=offline&response_type=code&redirect_uri=$([Uri]::EscapeDataString($redirectUri))" # Initialize Playwright and launch Chrome $playwright = [Microsoft.Playwright.Playwright]::CreateAsync().GetAwaiter().GetResult() $browser = $playwright.Chromium.LaunchAsync([Microsoft.Playwright.BrowserTypeLaunchOptions]@{ Headless = $false # Set to $true for silent mode after first login }).GetAwaiter().GetResult() $page = $browser.NewPageAsync().GetAwaiter().GetResult() # Navigate to Google's OAuth login page $page.GotoAsync($authUrl).GetAwaiter().GetResult() # Wait for redirect to Truecaller's callback (you'll need to complete login/2FA manually here) Write-Host "Please complete Google login in the browser window..." $page.WaitForNavigationAsync([Microsoft.Playwright.PageWaitForNavigationOptions]@{ Url = "$redirectUri*" }).GetAwaiter().GetResult() # Extract authorization code from the callback URL $currentUrl = $page.UrlAsync().GetAwaiter().GetResult() $queryParams = [System.Web.HttpUtility]::ParseQueryString([Uri]$currentUrl).Query $authCode = [System.Web.HttpUtility]::ParseQueryString($queryParams)["code"] if (-not $authCode) { Write-Error "Failed to capture authorization code" $browser.CloseAsync().GetAwaiter().GetResult() exit 1 } Write-Host "Successfully captured authorization code: $authCode" # Exchange code for access/refresh tokens $tokenBody = @{ client_id = $clientId code = $authCode redirect_uri = $redirectUri grant_type = "authorization_code" } try { $tokenResponse = Invoke-RestMethod -Uri "https://oauth2.googleapis.com/token" -Method Post -Body $tokenBody Write-Host "Access Token: $($tokenResponse.access_token)" Write-Host "Refresh Token: $($tokenResponse.refresh_token)" # Save this for future sessions } catch { Write-Error "Failed to exchange code for tokens: $_" $browser.CloseAsync().GetAwaiter().GetResult() exit 1 } # Access Truecaller's protected page using the access token $headers = @{ "Authorization" = "Bearer $($tokenResponse.access_token)" } try { $searchResponse = Invoke-WebRequest -Uri "https://www.truecaller.com/search/eg/xxxx" -Headers $headers Write-Host "Successfully fetched page! Content length: $($searchResponse.Content.Length)" # Optional: Save content to file # $searchResponse.Content | Out-File "truecaller_search.html" -Encoding UTF8 } catch { Write-Error "Failed to access Truecaller page: $_" } # Clean up browser resources $browser.CloseAsync().GetAwaiter().GetResult() $playwright.DisposeAsync().GetAwaiter().GetResult()
Key Notes
- First-Time Login: You'll need to manually complete Google login (and 2FA if enabled) the first time you run the script. After that, you can set
Headless = $trueand save the browser context to avoid re-authenticating every session. - Client Secret: Since this is a web app client, Google doesn't require a client secret for the code exchange (redirect URI validation is sufficient). Leave the
client_secretfield empty in the token request. - Session Persistence: To avoid re-logging in every time, you can save the browser context using
$page.Context.StorageStateAsync()and load it on subsequent runs. - Truecaller's Additional Checks: Truecaller may require additional cookies or headers. You can capture these from the Playwright session using
$page.Context.CookiesAsync()and include them in yourInvoke-WebRequestcalls if needed.
内容的提问来源于stack exchange,提问作者Powershell Man

