Files
powershell-scripts/docs/API_KEY_INTEGRATION.md
cproudlock 96cb1dd946 Remove all emojis from markdown documentation
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-10 11:03:45 -05:00

10 KiB

API Key Integration Guide for PowerShell Scripts

Overview

This guide explains how to configure API key authentication in the PowerShell asset collection scripts when deploying to production environments.


Configuration Methods

Set both the dashboard URL and API key as Windows environment variables:

# Set environment variables (run as Administrator)
[Environment]::SetEnvironmentVariable("ASSET_DASHBOARD_URL", "http://10.48.130.158/dashboard-v2/api.php", "User")
[Environment]::SetEnvironmentVariable("ASSET_API_KEY", "your-secret-api-key-here", "User")

Method 2: Configuration File

Create a dashboard-config.json file in the script directory:

{
    "DashboardURL": "http://10.48.130.158/dashboard-v2/api.php",
    "ApiKey": "your-secret-api-key-here",
    "ProxyURL": "http://10.48.130.158/vendor-api-proxy.php"
}

Method 3: Command Line Parameter

Pass the API key when running the script:

.\Update-PC-CompleteAsset.ps1 -DashboardURL "http://10.48.130.158/dashboard-v2/api.php" -ApiKey "your-secret-api-key-here"

PowerShell Script Modifications

1. Add API Key Parameter

Add to the param block in Update-PC-CompleteAsset.ps1:

param(
    [Parameter(Mandatory=$false)]
    [string]$DashboardURL,
    
    [Parameter(Mandatory=$false)]
    [string]$ProxyURL,
    
    [Parameter(Mandatory=$false)]
    [string]$ApiKey,  # New parameter for API key
    
    [Parameter(Mandatory=$false)]
    [switch]$SkipWarranty = $false,
    
    [Parameter(Mandatory=$false)]
    [switch]$TestConnections = $false
)

2. Create Get-ApiKey Function

Add this function after the Get-DashboardURL function:

function Get-ApiKey {
    param([string]$ProvidedKey)
    
    # Priority 1: Command line parameter
    if (-not [string]::IsNullOrEmpty($ProvidedKey)) {
        Write-Host "    Using provided API key" -ForegroundColor Gray
        return $ProvidedKey
    }
    
    # Priority 2: Environment variable
    $envKey = [Environment]::GetEnvironmentVariable("ASSET_API_KEY", "User")
    if (-not [string]::IsNullOrEmpty($envKey)) {
        Write-Host "    Using API key from environment variable" -ForegroundColor Gray
        return $envKey
    }
    
    # Priority 3: Config file
    $configPath = "$PSScriptRoot\dashboard-config.json"
    if (Test-Path $configPath) {
        try {
            $config = Get-Content $configPath | ConvertFrom-Json
            if ($config.ApiKey) {
                Write-Host "    Using API key from config file" -ForegroundColor Gray
                return $config.ApiKey
            }
        } catch {
            Write-Warning "Failed to read config file: $_"
        }
    }
    
    # No API key found (okay for development)
    Write-Host "    No API key configured (running without authentication)" -ForegroundColor Yellow
    return $null
}

3. Update API Calls to Include Authentication

For GET Requests:

# Original code
$response = Invoke-RestMethod -Uri "$DashboardURL?action=getDashboardData" -Method Get -TimeoutSec 10

# Updated with API key
$apiKey = Get-ApiKey -ProvidedKey $ApiKey
$uri = "$DashboardURL?action=getDashboardData"
if ($apiKey) {
    $uri += "&api_key=$apiKey"
}
$response = Invoke-RestMethod -Uri $uri -Method Get -TimeoutSec 10

For POST Requests (Preferred Method):

# Get API key
$apiKey = Get-ApiKey -ProvidedKey $ApiKey

# Build headers
$headers = @{
    'Content-Type' = 'application/x-www-form-urlencoded'
}

# Add Authorization header if API key exists
if ($apiKey) {
    $headers['Authorization'] = "Bearer $apiKey"
}

# Make the request
$response = Invoke-RestMethod -Uri $DashboardURL -Method Post -Body $postData -Headers $headers -TimeoutSec 30

4. Update Send-ToDatabase Function

Modify the Send-ToDatabase function to include authentication:

function Send-ToDatabase {
    param(
        [hashtable]$Data,
        [string]$DashboardURL,
        [string]$ApiKey  # Add ApiKey parameter
    )
    
    try {
        Write-Host "`n  Sending complete asset data to database..." -ForegroundColor Cyan
        
        # Create form data
        $postData = @{
            action = 'updatePCComplete'
        }
        
        # Add all data fields
        foreach ($key in $Data.Keys) {
            if ($null -ne $Data[$key]) {
                $postData[$key] = $Data[$key]
            }
        }
        
        # Build headers
        $headers = @{
            'Content-Type' = 'application/x-www-form-urlencoded'
        }
        
        # Add API key authentication if provided
        if ($ApiKey) {
            $headers['Authorization'] = "Bearer $ApiKey"
            Write-Host "    Using API key authentication" -ForegroundColor Gray
        }
        
        $response = Invoke-RestMethod -Uri $DashboardURL -Method Post -Body $postData -Headers $headers -TimeoutSec 30
        
        if ($response.success) {
            Write-Host "  [OK] Complete asset data stored in database!" -ForegroundColor Green
            if ($response.message) {
                Write-Host "      $($response.message)" -ForegroundColor Gray
            }
            return $true
        } else {
            Write-Warning "Database update failed: $($response.message)"
            return $false
        }
    } catch {
        Write-Error "Failed to send data to database: $_"
        return $false
    }
}

Deployment Batch File Updates

Update Deploy-To-Multiple-PCs-Enhanced.bat to include API key:

REM Configuration section
set SOURCE_DIR=S:\DT\adata\script
set TARGET_DIR=C:\Temp\AssetCollection
set API_KEY=your-secret-api-key-here

REM Create config file on target PC
echo Creating configuration file...
(
    echo {
    echo     "DashboardURL": "http://10.48.130.158/dashboard-v2/api.php",
    echo     "ApiKey": "%API_KEY%",
    echo     "ProxyURL": "http://10.48.130.158/vendor-api-proxy.php"
    echo }
) > "\\!COMPUTER!\C$\Temp\AssetCollection\dashboard-config.json"

Security Best Practices

1. Never Hardcode API Keys

  • Don't put API keys directly in scripts
  • Use environment variables or config files
  • Add dashboard-config.json to .gitignore

2. Secure Storage on Client PCs

# Set restrictive permissions on config file
$configPath = "C:\Temp\AssetCollection\dashboard-config.json"
$acl = Get-Acl $configPath
$acl.SetAccessRuleProtection($true, $false)
$adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators", "FullControl", "Allow")
$systemRule = New-Object System.Security.AccessControl.FileSystemAccessRule("SYSTEM", "FullControl", "Allow")
$acl.SetAccessRule($adminRule)
$acl.SetAccessRule($systemRule)
Set-Acl $configPath $acl

3. Use HTTPS in Production

When API key is configured, always use HTTPS:

$DashboardURL = "https://your-server/dashboard-v2/api.php"

Testing API Key Authentication

Test Script

Create Test-ApiAuth.ps1:

param(
    [string]$DashboardURL = "http://10.48.130.158/dashboard-v2/api.php",
    [string]$ApiKey
)

Write-Host "Testing API Authentication..." -ForegroundColor Cyan

# Test without API key
Write-Host "`nTest 1: Without API key"
try {
    $response = Invoke-RestMethod -Uri "$DashboardURL?action=health" -Method Get
    Write-Host "  Result: Success (no auth required)" -ForegroundColor Green
} catch {
    Write-Host "  Result: Failed - $($_.Exception.Message)" -ForegroundColor Red
}

# Test with API key in header
if ($ApiKey) {
    Write-Host "`nTest 2: With API key (Bearer token)"
    $headers = @{
        'Authorization' = "Bearer $ApiKey"
    }
    try {
        $response = Invoke-RestMethod -Uri "$DashboardURL?action=health" -Method Get -Headers $headers
        Write-Host "  Result: Success (authenticated)" -ForegroundColor Green
    } catch {
        Write-Host "  Result: Failed - $($_.Exception.Message)" -ForegroundColor Red
    }
}

# Test with API key in query
if ($ApiKey) {
    Write-Host "`nTest 3: With API key (query parameter)"
    try {
        $response = Invoke-RestMethod -Uri "$DashboardURL?action=health&api_key=$ApiKey" -Method Get
        Write-Host "  Result: Success (authenticated via query)" -ForegroundColor Green
    } catch {
        Write-Host "  Result: Failed - $($_.Exception.Message)" -ForegroundColor Red
    }
}

Environment-Specific Configuration

Development Environment

{
    "DashboardURL": "http://localhost/dashboard-v2/api.php",
    "ApiKey": "",
    "ProxyURL": "http://localhost/vendor-api-proxy.php"
}

Production Environment

{
    "DashboardURL": "https://asset-server.company.com/api.php",
    "ApiKey": "sk_live_a7b9c2d8e5f4g6h3i9j0k1l2m3n4o5p6q7r8s9t0",
    "ProxyURL": "https://asset-server.company.com/vendor-api-proxy.php"
}

Troubleshooting

Common Issues

  1. 401 Unauthorized Error

    • Verify API key is correct
    • Check if APP_ENV=production in .env
    • Ensure API_KEY is set in .env file
  2. API Key Not Being Sent

    • Check if headers are properly constructed
    • Verify Authorization header format: Bearer YOUR_KEY
    • Try query parameter method as fallback
  3. Script Works Locally but Not on Remote PCs

    • Ensure config file is deployed to target PCs
    • Check environment variables on target machines
    • Verify network connectivity to API server

Debug Mode

Add verbose output to troubleshoot:

# Enable verbose mode
$VerbosePreference = "Continue"

# Add debug output
Write-Verbose "API Key present: $($null -ne $ApiKey)"
Write-Verbose "Dashboard URL: $DashboardURL"
Write-Verbose "Headers: $($headers | ConvertTo-Json)"

Summary

When deploying to production:

  1. Generate secure API key: openssl rand -hex 32
  2. Set in .env file: API_KEY=your-generated-key
  3. Set environment to production: APP_ENV=production
  4. Configure PowerShell scripts with one of the three methods above
  5. Test authentication before mass deployment
  6. Use HTTPS for all production API calls

The API key provides an additional layer of security for your asset management system, ensuring only authorized scripts and users can update the database.