我无法在没有使用swift的Microsoft azure用户的情况下获取访问令牌。
我的功能基于https://docs.microsoft.com/en-us/graph/auth-v2-service#4-get-an-access-token并且如下所示:

let json: [String: Any] =
        [
            "grant_type": "client_credentials",
            "client_id": myAppClientID,
            "resource": "https://graph.microsoft.com",
            "client_secret": myClientSecret
        ]

    let jsonData = try? JSONSerialization.data(withJSONObject: json)
    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")
    request.setValue("Host", forHTTPHeaderField: "login.microsoftonline.com")
    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON)
        }
    }

    task.resume()

但我得到错误:[“error”:无效的请求,“error\u description”:aadsts900144:请求正文必须包含以下参数:“grant\u type”。

最佳答案

两件事:
如@md farid uddin kiron所述,v2端点的作用域不正确,应该https://graph.microsoft.com/.default
请求的主体应该是表单数据,而不是json:

func getPostString(params:[String:Any]) -> String
{
    var data = [String]()
    for(key, value) in params
    {
        data.append(key + "=\(value)")
    }
    return data.map { String($0) }.joined(separator: "&")
}

...

let params: [String: Any]  = [
    "client_id": myAppClientID,
    "client_secret": myClientSecret,
    "grant_type": "client_credentials",
    "scope": "https://graph.microsoft.com/.default"
]

let postString = getPostString(params: params)
request.httpBody = postString.data(using: .utf8)

10-07 19:54
查看更多