For the past week I have been trying to get an authentication token from a third party webservice by using their API with Alamofire. I have implemented different types of solutions. The problem is the web service only provides documentation on how to connect to their service using curl
. But I want to connect to it using Alamofire because I am developing an iOS app.
Down below I have posted the different solutions I have implemented that come back with 400 status code or 404. Would someone be kind enough to guide me thru this?
Here is the curl
command I want to convert to swift using Alamofire:
curl "https://api.webservice.com/oauth/token?client_id=<your-client-id>&client_secret=<your-client-secret>&grant_type=client_credentials"
In order to receive an access token from the authentication client you have to provide it with a client ID and client secret that is provided.
And here is some of the solutions I have tried implementing:
func doAuth(){
let parameters = ["ClientID": clientID, "clientSecret": clientSecret]
Alamofire.request("https://api.everypixel.com/oauth/token", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value as Any)
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
let user = clientID
let password = clientSecret
let credentialData = "\(user):\(password)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": "Bearer \(base64Credentials)"]
print(credentialData)
Alamofire.request(tokenRequestURL,
method: .post,
parameters: nil,
encoding: URLEncoding.default,
headers:headers)
.validate()
.responseJSON { response in
if response.result.value != nil{
print(response)
}else{
print("found an error")
}
}
let response = Alamofire.request(tokenRequestURL, method: .get).authenticate(user: clientID, password: clientSecret).response?.statusCode
print(response)
let key = clientID
let secret = clientSecret
let url = tokenRequestURL
var request = URLRequest(url: url!)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("sso-key \(key):\(secret)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
print(response)
}
task.resume()
}
In your code you are using
method: .post
, where it is not needed. Also there are some wrong parameter names (e.g."ClientID": clientID
should be renamed to"client_id": clientID
). This might be a cause of 400 or 404 status codes.At least this GET request worked for me without 400 or 404 status codes: