How can I receive an access_token through Client Credentials Flow to Spotify by using Alamofire?
Here is my code so far:
// Spotify API
func callAlamo(url: String) {
let parameters = ["client_id" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"client_secret" : "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
"grant_type" : "client_credentials"]
let headers = ["Authorization" : "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"] // <- xxx is the client_id
Alamofire.request("https://accounts.spotify.com/api/token", method: .post, parameters: parameters, headers: headers).responseJSON(completionHandler: {
response in
print(response.result)
print(response.result.value)
})
}
Here is a section of my print log:
SUCCESS
Optional({
error = "invalid_client";
})
What is wrong with this code? Am I sending the wrong parameters or headers? Did I forget something?
Note: The client_id and client_secret are correct
- If there is anything unclear, please message me -
After multiple days and 2 questions later, I figured it out myself. It was an extremely simple fix, which is frustrating.
All I did was delete the headers parameter in the request.
Another option is that you can set headers to nil.
Alamofire.request("https://accounts.spotify.com/api/token", method: .post, parameters: parameters).responseJSON(completionHandler: {
response in
print(response.result)
print(response.result.value)
})
Well I don't know how this is working.
In theory, the correct execution is:
- Make a POST request to url:
https://accounts.spotify.com/api/token
set as headers:
"Content-Type": "application/x-www-form-urlencoded"
"Authorization": "Basic xxxxx"
Where xxxxx is the base64 encoded string of client_id:client_secret (so client_id string and client_secret separated by :)
set as body:
"grant_type": "client_credentials"
This will give you the correct response
eg.
{
"access_token": "BQCJeyp3ocQZzSksvNn3IXuvY0NsYI26YMF400jp-7Dd8zGz6ecXyywwmSdy4jrPWwLZA_6l4e59lu8dYfg",
"token_type": "Bearer",
"expires_in": 3600,
"scope": ""
}
Related
I am trying to send a simple push notification with APNs. Going through the Apple Docs, I'm still a bit unsure if I am formulated my POST request correctly. Can someone verify if it's correct or if something needs to be fixed?
Note1: I am using certificate-based authentication (or at least I think I am).
Note2: apnsToken is the device token returned from application(didRegisterForRemoteNotificationsWithDeviceToken: ) (converted to a String based on #ytrewq's comment).
func sendNotification(apnsToken: String, title: String, body: String) {
let params: Parameters = [
"aps" : [
"alert" : [
"title" : title,
"body" : body
]
]
]
let headers: HTTPHeaders = [
":path": "/3/device/\(apnsToken)",
"apns-push-type": "alert"
]
AF.request("https://api.push.apple.com", method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).response { response in
debugPrint(response)
}
}
Running the code above gives me the error failure(Alamofire.AFError.sessionTaskFailed(error: Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response".
I'm trying to make a post request to my server through Alamofire but it returns a bad request saying that parameters are badly formed. Same requests is working in postman and swagger.
Here is the code:
var params = [
"username": "jora#company.com",
"password": "test123",
"pushToken": "No token"
]
Alamofire.request("https://thankyouposta.com/api/auth", method: .post, parameters: params, encoding: URLEncoding.default, headers: R.Api.headers).responseJSON { response in
switch response.result {
case .success(let value):
// ...
case .failure(let error):
// ...
}
}
Update 1
Parameters needs to be sent as form url encoded body
Update 2
Value of R.Api.headers is
["Content-Type" : "application/x-www-form-urlencoded"]
If you want to send request as a form-urlencoded, you should put it as a headers and change your encoding:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
var params = [
"username": "jora#company.com",
"password": "test123",
"pushToken": "No token"
]
Alamofire.request("your_url_here", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in
}
The backend was an IIS server with redirection to Tomcat. I've excluded IIS and make the requests directly to Tomcat and it is working now. As I understood, the problem was in delivering the request from IIS to Tomcat.
Solved
I'm pretty new to using Alamofire, and I am banging my head against the wall with this request. I'm using GIDSignIn, and successfully get a token and refresh token for the user, with the scope ["https://www.googleapis.com/auth/youtube.readonly"].
I'm trying to complete this request, as shown as an example on the site. The site says to ignore using client_secret for iOS, which I do.
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token
Below is how I've implemented it with Alamofire. My client_id is the value from the CLIENT_ID key in the GoogleService-Info.Plist, a string ending in .apps.googleusercontent.com. The refresh_token also seems to have the right format from other examples I've seen online.
let endpoint = "https://www.googleapis.com/oauth2/v4/token"
let parameters = [
"client_id" : client_id,
"refresh_token" : refresh_token,
"grant_type" : "refresh_token"
]
Alamofire.request(endpoint, method: .post,
parameters: parameters,
encoding: JSONEncoding.default)
.responseJSON { (data) in
print("data: \(data)")
let json = JSON(data.result)
}
The data response is
data: SUCCESS: {
error = "unsupported_grant_type";
"error_description" = "Invalid grant_type: ";
}
Not terribly successful. Do I need to configure my request differently, or get appropriate access / permission to get the token? Thank you so much!
#BikeshThakur helped me figure it out! The URLEncoding.httpBody did the trick! I don't need any headers either.
Alamofire.request(endpoint, method: .post,
parameters: parameters,
encoding: URLEncoding.httpBody)
i have tired in my code like this way , you also need to check sometime encoding type URLEncoding.httpBody hope it may help
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
Alamofire.request("https://accounts.google.com/o/oauth2/revoke?token={\(token)}", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in
I have Consumer Key, Consumer Secret, Token Key and Token Secret to get Data API. like this in postman:
I must get data my API like in capture postman above. then I have method request with Alamofire like this:
Alamofire.request("https://conversation.8villages.com/1.0/contents/articles?state=published", headers: headers).responseJSON { response in
print("test", response.request!) // original URL request
print("ini responseny", response.response!) // HTTP URL response
print("test", response.data!) // server data
print("test", response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
So, I don't know how to add or pass my token to in method get. someone help me, please.
I'm using OAuthSwift and Alamofire.
Try this
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
debugPrint(response)
}
Hello World,
I come to you because, I try to send headers with parameters in the same function like this:
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: headers, parameters: parameters)
but maybe you already knew just headers are sent.
I tried also this way:
let manager = Alamofire.Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
"Authorization": token]
manager.request(.PUT, "http://192.168.99.100:3030/users/\(identity)", parameters: parameters, encoding:.JSON)
but the headers are not sent..
What is the easy way to implement headers in alamofire?
Thanks by advance ;-)
regards,
set headers in dictionary just like other parameter and pass it in headers. for example
let Auth_header = [ "Authorization" : token ]
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: Auth_header, parameters: parameters)
You can check details HTTP Basic Authentication
HTTP Basic Authentication
The authenticate method on a Request will automatically provide an NSURLCredential to an NSURLAuthenticationChallenge when appropriate:
let user = "user"
let password = "password"
Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(user: user, password: password)
.responseJSON { response in
debugPrint(response)
}
Depending upon your server implementation, an Authorization header may also be appropriate:
let user = "user"
let password = "password"
let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password", headers: headers)
.responseJSON { response in
debugPrint(response)
}
I already did what you said in the first comment but anyway there are just the headers sent:
let parameters : [String : NSString] = [
"username": username,
"email": email,
"currentPassword": currentpassword,
"newPassword": newpassword]
let Auth_header = [ "Authorization" : token ]
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: Auth_header, parameters: parameters)
Resolved: The probleme was that I did't give the encoding in parameter
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: Auth_header, parameters: parameters, encoding: .JSON)
Thanks to EI Captain