Google Python API客户端使用refresh_token刷新access_token

时间:2015-11-16 11:33:56

标签: python google-api google-api-python-client

好的,所以我一直试图围绕google python api客户端库。这就是我所拥有的:

  1. Oauth2Credentials类 - >提供方法refresh(),允许重新发出新的access_token。在客户端中,这是重新发布新令牌的唯一公开可见方法。此外,如果使用此类的实例授权http请求,则隐式处理刷新。 此外,理想情况下,不应直接创建此实例,而应通过流对象创建此实例。 https://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.client.OAuth2Credentials-class.html

  2. AccessTokenCredentials类 - >仅接受access_token,并且只能用于验证http请求。不提供刷新方法。 https://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.client.AccessTokenCredentials-class.html

  3. 如果通常不创建Oauth2Credentials实例,如何使用刷新令牌获取新的access_token?我应该在第一次生成时存储凭证对象吗?如果是这样的话?

1 个答案:

答案 0 :(得分:0)

是的,您应该以某种方式将访问令牌存储在您的数据库中。

当您从数据库加载它时,以下是在使用它之前实际刷新它的方法:

    #when you load the credentials from the DB, make sure it is 
    #this type of object:
    credentials = google.oauth2.credentials.Credentials()
    #here is the object (with type) that the credential object needs to
    #do the refreshing
    request = google.auth.transport.requests.Request()
    #and now we actually refresh the token.
    credentials.refresh(request)
    #and now the credentials object should be usable.

如果您正在寻找更多详细信息,我已经在整个oauth2流程中使用谷歌库从头到尾写了一篇文章:

https://stackoverflow.com/a/48242762/1626536