Swift Alamofire Getting Token from Refresh Token R

2019-07-10 05:18发布

问题:

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!

回答1:

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


回答2:

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