Swift Alamofire Getting Token from Refresh Token Request Error - ios

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

Related

Client Credentials Flow - getting access token

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": ""
}

Alamofire POST Bad Request

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

How to pass Token Key and Token Secret to Alamofire request?

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

Alamofire 4.3 can't send JSON request

Iam Trying to send a JSON request using Alamofire but it's not working as a JSON Request here's my JSON :
{"ClientID":"55050","AdminId":"myemail","Password":"123"}
content-type → application/json; charset=utf-8
and here's my code :
import Alamofire
func doLogin(username:String ,password:String) {
let parameters = ["ClientID":"55050" , "AdminId":username,"Password":password]
Alamofire.request("myurl.com", method: .post, parameters: parameters, encoding: JSONEncoding(options: []) ).responseJSON(completionHandler: {
response in
print(response)
})
and here's the response which i am getting
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))
By reading the documentation i just need to put header to set the request as application/json
so i added extra parameter header :
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(ApiKeys().login, method : .post , parameters : parameters, encoding: JSONEncoding.default , headers: headers).responseJSON { response in
}
and now it's working perfectly thanks everyone for trying to help :)
It seems you must have missed header in your request. So, there has been no response.
Your header must be a dictionary [String: String].
let header = ["Content-Type" : "application/json"]
And your sample request should be:
Alamofire.request(getCategoryPath, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header)
.responseJSON { response in
guard response.result.error == nil else {
print(response.result.error!)
}
print(response.result.value)
}

alamofire header + parameters

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

Resources