Google API - Invalid Credentials

2020-05-08 07:12发布

问题:

I am trying to make an iOS app where a user can rate a YouTube video using the YouTube API. To do this, the user has to be authenticated. So, I used Google's Google Sign-In to authenticate my users. I followed the implementation guide, and it seems as if the user gets signed in. I can access data from the user such as their profile image, name, etc.

Because I am using the YouTube API, I need to add the YouTube scope to Google Sign-In before the user signs in. So, I do that like so...

GIDSignIn.sharedInstance().scopes = ["https://www.googleapis.com/auth/youtube"]

Now whenever a user signs in, it will request access to their YouTube channel.

It seems as if everything is working perfectly. But, now to rate the YouTube video. You can check out Google's documentation on how to rate a YouTube video, but basically, this is what I have to do.

Alamofire.request("https://www.googleapis.com/youtube/v3/videos/rate", method: .post, parameters: ["access_token":token, "id":"9T56NNzHE7A","rating":"like"], encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            print("\(response)")
        }

Now because this requires authentication, the API needs an access token. So (as you can see above) I give the API the access token Google Sign-In gives me. Which is:

let token = GIDSignIn.sharedInstance().currentUser.authentication.accessToken!

But, the request does not work. The response I get is

SUCCESS: {
    error =     {
        code = 401;
        errors =         (
                        {
                domain = global;
                location = Authorization;
                locationType = header;
                message = "Invalid Credentials";
                reason = authError;
            }
        );
        message = "Invalid Credentials";
    };
}

I don't understand how the credentials could be invalid if the user signed in only seconds before. If it helps, here is an example of what my access token looks like (don't worry this isn't actually it):

ve35.LmaIBHsK3dUPNR34rb0fgThwiZj-dNB7k935EhyVK1X8nkgMBmA-_3Hxhys7uk-HEm3ggg-HIgJv83RHXhGNKdVkWn0sEn7XtaWhTbeVjg8hsBK3hK8H1Gx8KzhhaEJGVg

I've been looking all over the internet trying to find an answer to this but to no avail. So I decided to ask. Does anyone have any idea on how to fix this? Any input would be highly appreciated!

回答1:

Try adding the access token to the headers of your Alamofire request instead of passing it as a parameter. As such:

let headers: HTTPHeaders = ["Authorization": "Bearer \(token)"]
let request = Alamofire.request(path, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)