如何在没有Microsoft Azure用户的情况下使用Swift获得访问令牌?

时间:2019-07-30 10:25:48

标签: swift azure microsoft-graph

在没有使用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()

但是我收到错误消息:[“错误”:invalid_request,“错误_说明”:AADSTS900144:请求正文必须包含以下参数:'grant_type'。

2 个答案:

答案 0 :(得分:2)

尝试oauth2/v2.0/token

因此您必须替换下面的属性

V2.0错误 "resource": "https://graph.microsoft.com"

针对V2.0正确 "scope": "https://graph.microsoft.com/.default"

查看屏幕截图:

enter image description here

有关详细信息,请参见此official docs

答案 1 :(得分:2)

两件事:

  • 如@ md-farid-uddin-kiron所述,作用域对于v2端点不正确,应为https://graph.microsoft.com/.default

  • 请求的正文应为form-data而不是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)