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

通过PowerShell获取Azure Bearer Token时遇AADSTS7000215密钥无效错误

问题描述

尝试通过PowerShell获取Microsoft Graph的Bearer Token时,持续返回**"invalid_client"**错误,错误详情:

Invoke-RestMethod : {"error":"invalid_client","error_description":"AADSTS7000215: Invalid client secret provided. Ensure the secret being sent in the request is the client secret value, not the client secret ID, for a secret added to app

已多次创建未过期的客户端密钥并确认有效,使用的脚本如下:

Function Connect-MgGraph -clientID 'CLIENTID' -tenantID 'TENANTID' -clientSecret 'SECRETVALUE' {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)]
        [string]$clientID,
        [Parameter(Mandatory)]
        [string]$tenantID,
        [Parameter(Mandatory)]
        [string]$clientSecret
    )
    begin {
        $ReqTokenBody = @{
            Grant_Type    = "client_credentials"
            Scope         = "https://graph.microsoft.com/.default"
            client_Id     = $clientID
            Client_Secret = $clientSecret
        }
    }
    process {
        $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
    }
    end {
        return $tokenResponse
    }
}
解决方法

针对AADSTS7000215错误,按以下步骤排查修复:

  • 确认客户端秘钥使用的是值而非ID
    在Azure AD应用注册的「证书和密码」页面,创建客户端密码后,只会显示一次密码值(Secret Value),而不是列表中的密码ID(Secret ID)。确保脚本中clientSecret参数传入的是这个一次性显示的完整值,不要误传ID。

  • 检查秘钥是否包含特殊字符
    如果秘钥值中有&、=、+等URL特殊字符,直接传入会导致参数解析错误。可以对秘钥值进行URL编码后再传入:

    Add-Type -AssemblyName System.Web
    $clientSecret = [System.Web.HttpUtility]::UrlEncode("你的秘钥值")
    
  • 修正函数定义的语法错误
    当前函数定义存在语法问题,不能在函数名后直接附带参数。修正后的函数定义:

    Function Connect-MgGraph {
        [CmdletBinding()]
        Param (
            [Parameter(Mandatory)]
            [string]$clientID,
            [Parameter(Mandatory)]
            [string]$tenantID,
            [Parameter(Mandatory)]
            [string]$clientSecret
        )
        begin {
            $ReqTokenBody = @{
                Grant_Type    = "client_credentials"
                Scope         = "https://graph.microsoft.com/.default"
                client_Id     = $clientID
                Client_Secret = $clientSecret
            }
        }
        process {
            $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
        }
        end {
            return $tokenResponse
        }
    }
    

    调用时再传入参数:

    Connect-MgGraph -clientID "你的客户端ID" -tenantID "你的租户ID" -clientSecret "你的秘钥值"
    
  • 检查应用权限配置
    确保Azure AD应用已添加Microsoft Graph的应用权限(而非委派权限),且已完成管理员同意。权限未配置或未同意也可能触发客户端验证类错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:42:46