-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthentication-examples.ps1
More file actions
215 lines (194 loc) · 10.1 KB
/
Copy pathauthentication-examples.ps1
File metadata and controls
215 lines (194 loc) · 10.1 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# API Authentication Examples
# Secure methods for authenticating with REST APIs
#
# CRITICAL SECURITY RULE: NEVER hardcode API keys or passwords in scripts!
# Always use environment variables or secure credential prompts.
#
# WHAT YOU MUST MODIFY:
# - Set your actual API keys/tokens in environment variables
# - Replace URLs with your actual API endpoints
# - Change header names to match your API requirements
#
# WHAT YOU SHOULDN'T CHANGE:
# - The environment variable approach for storing secrets
# - Error handling patterns
# - The base64 encoding method for Basic auth
#
# SECURITY CONSIDERATIONS:
# - Use environment variables for all sensitive data
# - Prefer Bearer tokens over API keys when possible
# - Always use HTTPS with authentication
# - Implement proper error handling to avoid exposing credentials
Write-Host "=== API Authentication Examples ===" -ForegroundColor Green
Write-Host "🔒 Remember: Set your credentials first!" -ForegroundColor Yellow
# SETUP INSTRUCTIONS (run these commands before the examples)
Write-Host "`nTo test these examples, first set your credentials:" -ForegroundColor Cyan
Write-Host ' $env:API_TOKEN = "your_bearer_token_here"' -ForegroundColor Gray
Write-Host ' $env:API_KEY = "your_api_key_here"' -ForegroundColor Gray
Write-Host ' $env:GITHUB_TOKEN = "ghp_your_github_token_here"' -ForegroundColor Gray
# Example 1: Bearer Token Authentication (Most Secure)
# MODIFY: Replace URL with your API endpoint
# MODIFY: Set $env:API_TOKEN with your actual token
# DON'T CHANGE: The environment variable approach
Write-Host "`n1. Bearer Token Authentication:" -ForegroundColor Yellow
if ($env:API_TOKEN) {
$headers = @{
# DON'T CHANGE: This is the secure way to include tokens
"Authorization" = "Bearer $env:API_TOKEN"
"Accept" = "application/json"
# MODIFY: Add other headers your API requires
"User-Agent" = "YourApp/1.0"
}
try {
# MODIFY: Replace with your actual API endpoint
$response = Invoke-RestMethod -Uri "https://httpbin.org/bearer" -Headers $headers -Method GET
Write-Host "✅ Bearer auth successful!" -ForegroundColor Green
Write-Host "Authenticated: $($response.authenticated)" -ForegroundColor Cyan
} catch {
# DON'T CHANGE: Always handle auth failures gracefully
Write-Error "❌ Bearer auth failed: $($_.Exception.Message)"
}
} else {
Write-Warning "⚠️ Set `$env:API_TOKEN to test Bearer authentication"
Write-Host "Example: `$env:API_TOKEN = 'your_token_here'" -ForegroundColor Gray
}
# Example 2: API Key in Header
# MODIFY: Change header name to match your API (X-API-Key, X-Auth-Token, etc.)
# MODIFY: Set $env:API_KEY with your actual key
Write-Host "`n2. API Key in Header:" -ForegroundColor Yellow
if ($env:API_KEY) {
$headers = @{
# MODIFY: Change "X-API-Key" to your API's header name
"X-API-Key" = $env:API_KEY
"Accept" = "application/json"
# MODIFY: Add other required headers
}
try {
# MODIFY: Replace with your API endpoint that accepts API keys
$response = Invoke-RestMethod -Uri "https://httpbin.org/get" -Headers $headers -Method GET
Write-Host "✅ API Key auth configured!" -ForegroundColor Green
Write-Host "Headers sent: $($response.headers.'X-Api-Key')" -ForegroundColor Cyan
} catch {
Write-Error "❌ API Key auth failed: $($_.Exception.Message)"
}
} else {
Write-Warning "⚠️ Set `$env:API_KEY to test API Key authentication"
Write-Host "Example: `$env:API_KEY = 'your_api_key_here'" -ForegroundColor Gray
}
# Example 3: Basic Authentication (Username/Password)
# MODIFY: Replace username/password with your credentials
# SECURITY: For production, prompt for credentials instead of hardcoding
# DON'T CHANGE: The base64 encoding method
Write-Host "`n3. Basic Authentication:" -ForegroundColor Yellow
# METHOD 1: Hardcoded for testing (ONLY for demo APIs)
Write-Host " Method 1 - Demo credentials (httpbin test):" -ForegroundColor Cyan
$demoUsername = "testuser" # MODIFY: Replace with real username
$demoPassword = "testpass" # MODIFY: Replace with real password
# DON'T CHANGE: This is the correct way to encode Basic auth
$base64Creds = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${demoUsername}:${demoPassword}"))
$headers = @{
"Authorization" = "Basic $base64Creds"
"Accept" = "application/json"
}
try {
# MODIFY: Replace with your API's Basic auth endpoint
$response = Invoke-RestMethod -Uri "https://httpbin.org/basic-auth/testuser/testpass" -Headers $headers
Write-Host "✅ Basic auth successful!" -ForegroundColor Green
Write-Host "Authenticated as: $($response.authenticated)" -ForegroundColor Cyan
} catch {
Write-Error "❌ Basic auth failed: $($_.Exception.Message)"
}
# METHOD 2: Secure credential prompt (RECOMMENDED for production)
Write-Host "`n Method 2 - Secure credential prompt:" -ForegroundColor Cyan
Write-Host " (Commented out to avoid prompts in demo)" -ForegroundColor Gray
Write-Host " # Uncomment these lines for secure credential input:" -ForegroundColor Gray
Write-Host ' # $cred = Get-Credential -Message "Enter API credentials"' -ForegroundColor Gray
Write-Host ' # $base64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($cred.UserName):$($cred.GetNetworkCredential().Password)"))' -ForegroundColor Gray
Write-Host ' # $headers = @{"Authorization" = "Basic $base64"}' -ForegroundColor Gray
# Example 4: Custom Authentication Headers
# MODIFY: Replace with your API's custom authentication method
Write-Host "`n4. Custom Authentication Headers:" -ForegroundColor Yellow
$customAuthHeaders = @{
# MODIFY: Replace these with your API's custom auth headers
"X-Auth-Token" = "$env:API_TOKEN" # Some APIs use this
"X-Client-ID" = "your_client_id" # MODIFY: Replace with actual client ID
"X-Timestamp" = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() # Some APIs require timestamps
"Accept" = "application/json"
}
try {
# MODIFY: Replace with your API endpoint
$response = Invoke-RestMethod -Uri "https://httpbin.org/get" -Headers $customAuthHeaders -Method GET
Write-Host "✅ Custom auth headers sent!" -ForegroundColor Green
} catch {
Write-Error "❌ Custom auth failed: $($_.Exception.Message)"
}
# Example 5: Real-world example - GitHub API
# MODIFY: Set $env:GITHUB_TOKEN with your actual GitHub personal access token
Write-Host "`n5. Real-world example - GitHub API:" -ForegroundColor Yellow
if ($env:GITHUB_TOKEN) {
$githubHeaders = @{
# DON'T CHANGE: GitHub uses "token" prefix, not "Bearer"
"Authorization" = "token $env:GITHUB_TOKEN"
# DON'T CHANGE: GitHub recommends this Accept header
"Accept" = "application/vnd.github.v3+json"
"User-Agent" = "PowerShell-API-Examples" # MODIFY: Change to your app name
}
try {
# Test authenticated endpoint
$user = Invoke-RestMethod -Uri "https://api.github.com/user" -Headers $githubHeaders
Write-Host "✅ GitHub auth successful!" -ForegroundColor Green
Write-Host "Logged in as: $($user.login)" -ForegroundColor Cyan
Write-Host "Account type: $($user.type)" -ForegroundColor Cyan
# Test rate limit (useful for monitoring)
$rateLimit = Invoke-RestMethod -Uri "https://api.github.com/rate_limit" -Headers $githubHeaders
Write-Host "API calls remaining: $($rateLimit.rate.remaining)/$($rateLimit.rate.limit)" -ForegroundColor Cyan
} catch {
Write-Error "❌ GitHub auth failed: $($_.Exception.Message)"
Write-Host "💡 Check your token at: https://github.com/settings/tokens" -ForegroundColor Yellow
}
} else {
Write-Warning "⚠️ Set `$env:GITHUB_TOKEN to test GitHub authentication"
Write-Host "Get a token at: https://github.com/settings/tokens" -ForegroundColor Gray
}
# Example 6: Authentication Error Handling
# DON'T CHANGE: This shows proper error handling patterns
Write-Host "`n6. Authentication Error Handling:" -ForegroundColor Yellow
$badHeaders = @{
"Authorization" = "Bearer invalid_token_12345"
"Accept" = "application/json"
}
try {
$response = Invoke-RestMethod -Uri "https://httpbin.org/bearer" -Headers $badHeaders
} catch [System.Net.WebException] {
# DON'T CHANGE: This is the correct way to handle HTTP errors
$statusCode = $_.Exception.Response.StatusCode
if ($statusCode -eq 401) {
Write-Host "🔑 Authentication failed (401 Unauthorized)" -ForegroundColor Red
Write-Host "💡 Check your API key/token" -ForegroundColor Yellow
} elseif ($statusCode -eq 403) {
Write-Host "🚫 Access forbidden (403 Forbidden)" -ForegroundColor Red
Write-Host "💡 Check your permissions" -ForegroundColor Yellow
} else {
Write-Host "❌ HTTP Error: $statusCode" -ForegroundColor Red
}
} catch {
Write-Host "❌ Network or other error: $($_.Exception.Message)" -ForegroundColor Red
}
Write-Host "`n=== Authentication Best Practices ===" -ForegroundColor Magenta
Write-Host "✅ DO:" -ForegroundColor Green
Write-Host " • Store credentials in environment variables" -ForegroundColor White
Write-Host " • Use HTTPS endpoints only" -ForegroundColor White
Write-Host " • Implement proper error handling" -ForegroundColor White
Write-Host " • Use Get-Credential for interactive scripts" -ForegroundColor White
Write-Host " • Rotate API keys regularly" -ForegroundColor White
Write-Host "`n❌ DON'T:" -ForegroundColor Red
Write-Host " • Hardcode API keys in scripts" -ForegroundColor White
Write-Host " • Put credentials in query parameters" -ForegroundColor White
Write-Host " • Ignore authentication errors" -ForegroundColor White
Write-Host " • Use HTTP for authenticated requests" -ForegroundColor White
Write-Host " • Share API keys in code repositories" -ForegroundColor White
Write-Host "`n🔧 Setup Commands:" -ForegroundColor Cyan
Write-Host "Run these before testing:" -ForegroundColor White
Write-Host ' $env:API_TOKEN = "your_bearer_token"' -ForegroundColor Gray
Write-Host ' $env:API_KEY = "your_api_key"' -ForegroundColor Gray
Write-Host ' $env:GITHUB_TOKEN = "ghp_your_github_token"' -ForegroundColor Gray