Azure/Microsoft身份平台PHP调用/token端点无法获取访问令牌
基于Microsoft Identity Platform调用/token端点返回400 Bad Request问题排查
我正在开发基于Microsoft Identity Platform的自定义Web应用,用于用户认证与授权。已成功调用/authorize端点完成认证,并获取到返回的code凭证,但调用/token端点提交POST请求以获取访问令牌(用于API调用)时,服务器返回400 Bad Request错误,响应头无有效排错信息,也未返回JSON响应,无法定位问题。
我的调用代码如下:
$clientId = '00000000-0000-0000....'; // Omitted $tenantId = '00000000-0000-0000....'; // Omitted $grantType = 'authorization_code'; $scope = urlencode('User.Read'); $code = '......' // Obtained from authentication $redirect_uri = 'http://localhost/smp/auth/handle'; $clientSecret = '...' // Omitted, set up in Azure App registrations under Certificates and secrets $resource = 'api://00000000-0000-0000....'; // Omitted, set up in Azure App registrations under Overview -> App ID URI $url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"; $parameters = [ 'client_id' => $clientId, 'grant_type' => $grantType, 'scope' => $scope, 'code' => $code, 'redirect_uri' => $redirectUri, 'client_secret' => $clientSecret, 'resource' => $resource ]; $options = [ 'http' => [ 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($parameters) ] ]; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); if (!$result) { exit('an error has occured'); }
PHP返回警告:
Warning: file_get_contents(https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token): Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\xampp\htdocs\smp\application\models\user-model.php on line 261
我已验证以下内容:
- Client ID与Tenant ID有效(认证请求已成功)
- code已从认证请求中正确获取
- Redirect URI与认证请求中使用的一致
- 已尝试添加/移除client_secret(按理解此场景需要该参数)
- 已尝试添加/移除resource(采用Azure默认命名格式
api://)
恳请协助排查问题,可能是Azure权限或额外配置问题?目前无法通过平台返回信息进行排错。
内容的提问来源于stack exchange,提问作者smartroof
相关产品推荐
相关产品推荐

