Swift获取Azure无用户Access Token遇AADSTS900144错误求助
解决Azure服务到服务令牌请求的invalid_request错误
你的问题很典型——Content-Type头和请求体格式不匹配导致的。你设置了application/x-www-form-urlencoded,但请求体传的是JSON数据,Azure的令牌端点识别不了里面的grant_type参数,所以抛出了这个错误。
修复核心思路
把请求体从JSON格式改成x-www-form-urlencoded要求的键值对字符串格式,让端点能正确解析参数。
完整修复代码
// 构建表单键值对(替代原来的JSON结构) let formParams = [ "grant_type": "client_credentials", "client_id": myAppClientID, "resource": "https://graph.microsoft.com", "client_secret": myClientSecret ] // 转换成符合x-www-form-urlencoded格式的字符串,注意对参数值做URL编码 let formString = formParams.map { key, value in guard let encodedValue = value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return "\(key)=" } return "\(key)=\(encodedValue)" }.joined(separator: "&") guard let requestBody = formString.data(using: .utf8) else { print("Failed to create request body") return } let url = URL(string: "https://login.microsoftonline.com/" + myDirectoryID + "/oauth2/v2.0/token")! var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") // 移除手动设置的Host头,URLSession会自动处理这部分 request.httpBody = requestBody let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error?.localizedDescription ?? "No data") return } // 改用do-catch处理JSON解析,比try?更易排查问题 do { let responseJSON = try JSONSerialization.jsonObject(with: data, options: []) if let responseJSON = responseJSON as? [String: Any] { print(responseJSON) } } catch { print("JSON parsing error: \(error.localizedDescription)") } } task.resume()
额外优化建议
- 敏感信息(比如
myClientSecret、myAppClientID)不要硬编码,建议用Xcode配置文件或环境变量管理,避免泄露。 - 如果使用Azure AD v2.0端点,也可以把
resource参数换成scope: "https://graph.microsoft.com/.default",这是v2.0版本更推荐的参数格式,功能等价。
内容的提问来源于stack exchange,提问作者Ryan Tran
相关产品推荐
相关产品推荐

