OAuth令牌已过期且刷新令牌未设置。

huangapple go评论140阅读模式
英文:

OAuth token expired and refresh token is not set

问题

我正在为一些HTTP API编写代码,需要使用OAuth。我正在使用OAuth Package。一开始它是正常工作的,但是过一段时间后我开始收到错误信息:

> Token expired and refresh token is not set.

这是我的配置:

userCfg := &oauth2.Config{
    ClientID:     a.ClientID,
	ClientSecret: a.ClientSecret,
	Endpoint: oauth2.Endpoint{
		TokenURL:  a.ProviderURL,
		AuthStyle: oauth2.AuthStyleInParams, // basic auth is not supported by Ping
	},
}
英文:

I am working on some HTTP APIs for which I need OAuth. I am using OAuth Package. It works at first but after some time I start getting error

> Token expired and refresh token is not set.

Here is my config

userCfg := &oauth2.Config{
    ClientID:     a.ClientID,
	ClientSecret: a.ClientSecret,
	Endpoint: oauth2.Endpoint{
		TokenURL:  a.ProviderURL,
		AuthStyle: oauth2.AuthStyleInParams, // basic auth is not supported by Ping
	},
}

答案1

得分: 2

我看到有人说添加Scopes: []string{"offline_access"}可以解决这个问题。但是我添加、部署和测试需要花费很多时间,所以我只想知道这是否是正确的答案,还是我需要做其他的事情。

英文:

I see somewhere that adding Scopes: []string{"offline_access"} can resolve this issue. It takes a lot of time for me to actually add something and then deploy and test. So i just want to know if it's the correct answer or do I need to do something else.

答案2

得分: 1

我自己解决了这个问题,我添加了一个检查,如果接收到的令牌过期错误,那么我会重新请求令牌,而不是将错误发送回去,否则我会返回错误。

refreshErr := "oauth2: 令牌已过期且刷新令牌未设置"

// 使用令牌源检索配置的令牌或新令牌
token, err := a.tokenSource.Token()
if err != nil && strings.Contains(err.Error(), refreshErr) {
// 更新令牌源
a.tokenSource, err = a.getUserToken()
if err != nil {
return "", err
}

// 获取新令牌
token, err = a.tokenSource.Token()
if err != nil {
    return "", err
}

} else if err != nil { // 刷新令牌错误以外的其他错误
return "", err
}

你可以在代码中将refreshErr定义为一个常量。

英文:

I fixed the problem on my own, I put a check that if a received token expires error then instead of sending the error back, I request the token again else I return the error.

refreshErr := "oauth2: token expired and refresh token is not set"

// use token source to retrieve the configured token or a new token
token, err := a.tokenSource.Token()
if err != nil && strings.Contains(err.Error(), refreshErr) {
	// update the token source
	a.tokenSource, err = a.getUserToken()
	if err != nil {
		return "", err
	}

	// get the new token
	token, err = a.tokenSource.Token()
	if err != nil {
		return "", err
	}
} else if err != nil { // some other error than refresh token error
	return "", err
}

You can define the refreshErr as a constant in your code.

huangapple
  • 本文由 发表于 2023年3月8日 18:36:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定