You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure Runbook中用PowerShell生成调用Invoke-RestMethod的令牌

在Azure Runbook中用PowerShell基于密钥创建JWT令牌(用于Invoke-RestMethod)

以下是和你提供的C#代码逻辑完全一致的PowerShell实现,可直接在Azure Runbook中使用,生成带JTI声明、HMAC-SHA256签名并指定过期时间的JWT令牌,用于后续调用Invoke-RestMethod。

PowerShell实现代码

function New-JwtToken {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Secret,
        [Parameter(Mandatory=$true)]
        [int]$ExpirationMinutes
    )

    # 加载依赖的.NET程序集
    Add-Type -AssemblyName System.IdentityModel.Tokens.Jwt
    Add-Type -AssemblyName System.Security.Claims

    # 将密钥转换为对称安全密钥
    $keyBytes = [System.Text.Encoding]::UTF8.GetBytes($Secret)
    $securityKey = New-Object System.IdentityModel.Tokens.SymmetricSecurityKey($keyBytes)

    # 初始化JWT令牌处理器
    $tokenHandler = New-Object System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler

    # 构建令牌描述符
    $tokenDescriptor = [System.IdentityModel.Tokens.SecurityTokenDescriptor]@{
        Expires = [System.DateTime]::UtcNow.AddMinutes($ExpirationMinutes)
        Subject = [System.Security.Claims.ClaimsIdentity]::new(@(
            [System.Security.Claims.Claim]::new([System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames]::Jti, [System.Guid]::NewGuid().ToString())
        ))
        SigningCredentials = [System.IdentityModel.Tokens.SigningCredentials]::new(
            $securityKey,
            [System.IdentityModel.Tokens.SecurityAlgorithms]::HmacSha256Signature
        )
    }

    # 创建并生成JWT字符串
    $securityToken = $tokenHandler.CreateToken($tokenDescriptor)
    return $tokenHandler.WriteToken($securityToken)
}

在Runbook中使用示例

# 配置参数
$apiSecret = "你的密钥内容"
$tokenExpiryMinutes = 60 # 令牌1小时后过期

# 生成JWT令牌
$jwtToken = New-JwtToken -Secret $apiSecret -ExpirationMinutes $tokenExpiryMinutes

# 调用API时携带令牌
$requestHeaders = @{
    "Authorization" = "Bearer $jwtToken"
}

Invoke-RestMethod -Uri "目标API地址" -Headers $requestHeaders -Method Get

代码说明

  • 完全对应你提供的C#逻辑:生成包含jti(唯一标识)声明的JWT,使用HMAC-SHA256算法签名,设置UTC时间的过期时间
  • Azure Automation的PowerShell环境已预装所需的.NET程序集,无需额外安装依赖
  • 函数参数ExpirationMinutes对应C#中的TimeSpan,可根据需求调整过期时长

内容的提问来源于stack exchange,提问作者Andre Rubnikowich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 19:05:36