简体   繁体   中英

How to get access token without a user of microsoft azure using swift?

I have problem with getting access token without a user of microsoft azure using swift. My function based on https://docs.microsoft.com/en-us/graph/auth-v2-service#4-get-an-access-token and like this :

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()

But i get error : ["error": invalid_request, "error_description": AADSTS900144: The request body must contain the following parameter: 'grant_type'.

As you are trying oauth2/v2.0/token

So you must replace below property

Incorrect for V2.0 : "resource": "https://graph.microsoft.com"

Correct for V2.0 : "scope": "https://graph.microsoft.com/.default"

See the screen shot:

在此处输入图片说明

For details refer this official docs

Two things:

  • As stated by @md-farid-uddin-kiron, the scope is incorrect for v2 endpoint and should be https://graph.microsoft.com/.default

  • The body of the request should be form-data not 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM