【问题标题】:How to get access token without a user of microsoft azure using swift?如何在没有 microsoft azure 用户的情况下使用 swift 获取访问令牌?
【发布时间】:2019-07-30 10:25:48
【问题描述】:

在没有 microsoft azure 用户的情况下使用 swift 获取访问令牌时遇到问题。 我的函数基于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”:invalid_request,“error_description”:AADSTS900144:请求正文必须包含以下参数:'grant_type'。

【问题讨论】:

  • 看一看。希望这能解决您的问题

标签: swift azure microsoft-graph-api


【解决方案1】:

两件事:

  • 正如@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)

【讨论】:

    【解决方案2】:

    当你尝试oauth2/v2.0/token

    所以你必须替换下面的属性

    V2.0 不正确 :"resource": "https://graph.microsoft.com"

    V2.0 更正"scope": "https://graph.microsoft.com/.default"

    查看屏幕截图:

    详情请参考official docs

    【讨论】:

    • 感谢法里德·乌丁·基隆博士!我明白了。
    • 很高兴听到。快乐的编码!
    猜你喜欢
    • 2015-04-25
    • 2020-08-02
    • 2018-07-20
    • 2022-01-08
    • 2018-05-21
    • 1970-01-01
    • 2022-11-24
    • 2015-09-12
    • 1970-01-01
    相关资源
    最近更新 更多