Reputation: 487
I have problem with getting access token without a user of microsoft azure using swift. My function based on https://learn.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'.
Upvotes: 2
Views: 323
Reputation: 29726
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)
Upvotes: 3
Reputation: 22495
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
Upvotes: 2