英文:
How to handle refresh tokens in golang/oauth2 client lib
问题
有一些使用https://github.com/golang/oauth2的示例,但没有一个涵盖了刷新令牌的用法。我尝试了几种方法,但对结果还不满意。
是否有任何示例代码,或者您知道一些在Github上使用oauth2 lib
的项目可以作为示例?
英文:
There are few examples of using https://github.com/golang/oauth2 but none of them covers usage of refresh tokens. I've tried few approaches, but i'm still unsatisfied with my results.
Is there any example code, or maybe you know some project at Github using oauth2 lib
to take as example?
答案1
得分: 31
你无需担心刷新令牌,直到存储“Expiry”参数的时间。在获取“Token”对象后,将以下内容存储在数据库中:
token.AccessToken
、token.RefreshToken
、token.TokenType
和token.Expiry
在获取时,使用上述参数重新构建令牌对象:
token := new(oauth2.Token)
token.AccessToken = {{从数据库获取}}
token.RefreshToken = {{从数据库获取}}
token.Expiry = {{从数据库获取}}
token.TokenType = {{从数据库获取}}
然后获取你的 HTTP 客户端:
config.Client(ctx, token)
这将处理令牌的刷新。摘录(更多信息:Golang oauth2 client):
Client 返回使用提供的令牌的 HTTP 客户端。令牌将根据需要自动刷新。
唯一的缺点是,刷新后的访问令牌不会返回。但它是有效的!Google 对刷新令牌的使用次数没有限制。
英文:
You need not bother about refreshing tokens until the time you are storing the Expiry
parameter. After getting the 'Token' object, store the following in your database:
token.AccessToken
, token.RefreshToken
, token.TokenType
and token.Expiry
while fetching, construct the token object again using the above parameters:
token := new(oauth2.Token)
token.AccessToken = {{ From DataBase }}
token.RefreshToken = {{ From DataBase }}
token.Expiry = {{ From DataBase }}
token.TokenType = {{ From DataBase }}
and then get your http client:
config.Client(ctx, token)
this will handle refreshing the token. Excerpt (more info: Golang oauth2 client):
> Client returns an HTTP client using the provided token. The token will auto-refresh as necessary.
Only downside is, the refreshed access token is not returned. But it works! Google has no restrictions on how many times the refresh token is used.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论