go - 如何正确读取 golang oauth2 的错误

标签 go oauth oauth-2.0 godoc

token, err := googleOauthConfig.Exchange(context.Background(), code)
if err != nil {
 fmt.Fprintf(w, "Err: %+v", err)
}

fprintf 的输出是:

Err: oauth2: cannot fetch token: 401 Unauthorized
Response: {"error":"code_already_used","error_description":"code_already_used"}

我想检查是否“error”=“code_already_used”。对于我的生活,我无法弄清楚如何。

如何检查/返回/读取错误的“error”或“error_description”?

我看过oauth2的代码,有点看不懂

// retrieveToken takes a *Config and uses that to retrieve an *internal.Token.
// This token is then mapped from *internal.Token into an *oauth2.Token which is returned along
// with an error..
func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) {
    tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v)
    if err != nil {
        if rErr, ok := err.(*internal.RetrieveError); ok {
            return nil, (*RetrieveError)(rErr)
        }
        return nil, err
    }
    return tokenFromInternal(tk), nil
}

怎么猜我想看看 (*RetrieveError) 部分。对吧?

谢谢!

最佳答案

表达式:

(*RetrieveError)(rErr)

rErr 的类型从 *internal.RetrieveError 转换为 *RetrieveError。由于 RetrieveError 是在 oauth2 包中声明的,您可以键入断言您收到的错误 *oauth2.RetrieveError获取详细信息。详细信息作为 byte slice 段包含在该类型的 Body 字段中。

由于一段字节不是要检查的最佳格式,并且在您的情况下,字节似乎包含一个 json 对象,您可以通过预定义一种类型来简化您的生活,您可以将这些细节解码到其中。

即:

type ErrorDetails struct {
    Error            string `json:"error"`
    ErrorDescription string `json:"error_description"`
}

token, err := googleOauthConfig.Exchange(context.Background(), code)
if err != nil {
    fmt.Fprintf(w, "Err: %+v", err)

    if rErr, ok := err.(*oauth2.RetrieveError); ok {
        details := new(ErrorDetails)
        if err := json.Unmarshal(rErr.Body, details); err != nil {
            panic(err)
        }

        fmt.Println(details.Error, details.ErrorDescription)
    }        
}

关于go - 如何正确读取 golang oauth2 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55010207/

相关文章:

dictionary - Golang map 内部实现 - 它如何在 map 中搜索键?

ssl - 自己的 https certbot web 服务器返回 404 页面未找到

security - 通过 ssl 完成 OAuth 请求时是否需要验证随机数?

android - Android 应用程序的 Oauth2 重定向 URI

Azure AD B2C 开放 ID 连接与 OAuth 2.0

go - 意外的模块路径 go-modules

go - 在 buffalo 中调试单个测试函数

node.js - 如何将 Node js 连接到 Quickbooks v3 REST API

python - 代表客户验证 keycloak 承载 token

ruby-on-rails - 使用 Ember.js 和 Torii (oauth2) 连接到 github