简体   繁体   中英

Gmail API server access “invalid_grant” iOS?

We have integrated Google sign in in our iOS application we want to access Gmail APIs offline from server.

We are submitting the token_Id to server but server is throwing following exception (Server is in Java ):

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_grant",
  "error_description" : "Bad Request"
}

To get the token id we are using following code iOS code :

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if (error == nil) {
            let idToken = user.authentication.idToken
            let fullName = user.profile.name
            print("Connected for user: \(fullName)")
            print("Id Token: \(idToken)")
            setAppUserContext(userId: idToken!)
        } else {
            print("\(error.localizedDescription)")
        }
    }

We are sending user.authentication.idToken to server for offline access.

Scope is as below :

gid?.scopes.append("https://www.googleapis.com/auth/gmail.readonly")

We have set the required clientID & serverIds correctly.

For GIDSignIn we have made following properties :

GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signInSilently()

invalid_grant normally has two causes.

  1. Your server's clock is not in sync with NTP. (Solution: check the server time if its incorrect fix it. )
  2. The refresh token limit has been exceeded. (Solution: Nothing you can do they cant have more refresh tokens in use) Applications can request multiple refresh tokens. For example, this is useful in situations where a user wants to install an application on multiple machines. In this case, two refresh tokens are required, one for each installation. When the number of refresh tokens exceeds the limit, older tokens become invalid. If the application attempts to use an invalidated refresh token, an invalid_grant error response is returned. The limit for each unique pair of OAuth 2.0 client and is 50 refresh tokens (note that this limit is subject to change). If the application continues to request refresh tokens for the same Client/Account pair, once the 26th token is issued, the 1st refresh token that was previously issued will become invalid. The 27th requested refresh token would invalidate the 2nd previously issued token and so on.

It can be tricky using the ID token in this way. The clock on the server you are using will probably have to match the time that it was created on the client. I am not an IOS dev so cant help much more then that. You cant validate the id token if the time zones are messing you up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM