Invoke-WebRequest遇特殊字符失效,如何优化GetToken函数?
问题描述
我在发布流水线中通过Azure Key Vault获取令牌、客户端密钥和用户密码,客户端密钥和密码本身是正确的,但调用GetToken函数获取令牌时失败。对比发现密码里的$符号及后续内容丢失:
- 正确密码:
5p5q6#F2#kv3Iul#Ou0R$NDGGoX*YK8e - 函数获取到的密码:
5p5q6#F2#kv3Iul#Ou0R*YK8e
当前使用的GetToken函数如下:
function GetToken ($Username, $Password, $ClientSecret, $ClientId) { Write-Host "starting to get the token" Write-Host "UserName = $Username Password = $Password ClientSecret = $ClientSecret ClientID = $ClientId" # ToDo: pass tenant as parameter $uri= "https://login.microsoftonline.com/0450f3eaf-1e2e-5baf-8c3b-e36006ff4ty6/oauth2/v2.0/token" $body = @{grant_type='password' client_id= $ClientId client_secret= "$ClientSecret" redirect_uri= 'http://localhost:5005/signin-oidc' scope= 'openid offline_access https://xxx.onmicrosoft.com/f08d4dfc-480f-41a5-91f9-0cd4103dc97f/user_impersonation' username= $Username password= $Password state = '12345'} $contentType = 'application/x-www-form-urlencoded' $result = Invoke-WebRequest -Method POST -Uri $uri -body $body -ContentType $contentType $body = $result.Content | ConvertFrom-Json; return $body.access_token; }
问题原因及修复方案
原因
PowerShell中$是变量标识符,密码包含$时,直接传递会被解析为变量引用,若对应变量不存在则这部分内容直接丢失。另外,Invoke-WebRequest直接使用哈希表作为-Body参数时,对特殊字符的URL编码处理存在缺陷,导致部分字符无法正确传递。
修复后的函数
function GetToken ($Username, $Password, $ClientSecret, $ClientId) { Write-Host 'starting to get the token' Write-Host "UserName = $Username Password = $('$Password') ClientSecret = $('$ClientSecret') ClientID = $ClientId" # ToDo: pass tenant as parameter $uri= "https://login.microsoftonline.com/0450f3eaf-1e2e-5baf-8c3b-e36006ff4ty6/oauth2/v2.0/token" # 手动构建并编码表单数据 $formData = @( "grant_type=password", "client_id=$([Uri]::EscapeDataString($ClientId))", "client_secret=$([Uri]::EscapeDataString($ClientSecret))", "redirect_uri=$([Uri]::EscapeDataString('http://localhost:5005/signin-oidc'))", "scope=$([Uri]::EscapeDataString('openid offline_access https://xxx.onmicrosoft.com/f08d4dfc-480f-41a5-91f9-0cd4103dc97f/user_impersonation'))", "username=$([Uri]::EscapeDataString($Username))", "password=$([Uri]::EscapeDataString($Password))", "state=12345" ) -join '&' $contentType = 'application/x-www-form-urlencoded' $result = Invoke-WebRequest -Method POST -Uri $uri -Body $formData -ContentType $contentType $body = $result.Content | ConvertFrom-Json return $body.access_token }
关键修改说明
- 避免变量解析:
Write-Host输出敏感参数时,用$('$Password')转义$符号,防止PowerShell误解析。 - 手动URL编码:使用
[Uri]::EscapeDataString()对所有表单字段值进行编码,确保$、#、*等特殊字符都能正确转换为符合application/x-www-form-urlencoded标准的格式。 - 替换哈希表传参:不再用哈希表作为
-Body参数,而是手动拼接编码后的字符串,彻底避免PowerShell自动处理时的编码问题。
内容的提问来源于stack exchange,提问作者Bandit
相关产品推荐
相关产品推荐

