登录
首页 >  Golang >  Go问答

在没有用户配置文件的情况下,如何通过Google OAuth2获取用户电子邮件?

来源:stackoverflow

时间:2024-02-06 12:27:21 338浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《在没有用户配置文件的情况下,如何通过Google OAuth2获取用户电子邮件?》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

如何在不需要访问整个用户个人资料的情况下访问用户电子邮件?

下面调用 oauthconfig.exchange 后得到的 tok 似乎没有提供访问“id 令牌”的编程方式,即使我在范围中包含“电子邮件”。

import (
  ...
  "github.com/gin-gonic/gin"
  "golang.org/x/oauth2"
  "golang.org/x/oauth2/google"
  "google.golang.org/api/gmail/v1",
  "google.golang.org/api/option"
)

var (
  ctx = context.Background()

  oauthConfig = &oauth2.Config{
    ClientID: ...,
    ClientSecret: ...,
    RedirectURL: ...,

    // ... but it looks like what I want is userinfo.email
    Scopes: [ "https://www.googleapis.com/auth/userinfo.profile" ],

    Endpoint: google.Endpoint,
  }
)

// Handler for the redirect URL.
func redirectHandler(c *gin.Context) {
  tok, _ := oauthConfig.Exchange(ctx, c.Query("code"))
  httpClient := oauthConfig.Client(ctx, tok)
  gmailService, _ := gmail.NewService(ctx, option.WithHTTPClient(httpClient)
  userProfile, _ := gmailService.Users.GetProfile("me").Do()

  // And now we have the user's email address
  // userProfile.EmailAddress
}

// Omitting main etc.

正确答案


您似乎正在尝试使用 gmail api,

gmailservice.users.getprofile("me").do()

您没有请求 gmail api 范围。要访问该方法,您需要使用以下范围之一。

如果您只想知道他们的电子邮件地址,请尝试仅添加范围电子邮件,看看会发生什么

{
  "access_token": "redacted", 
  "id_token": "redacted", 
  "expires_in": 3599, 
  "token_type": "bearer", 
  "scope": "https://www.googleapis.com/auth/userinfo.email openid", 
  "refresh_token": "redacted"
}

但是如果我们解码 id 令牌,我们就会收到我的电子邮件。

{
  "iss": "https://accounts.google.com",
  "azp": "407408718192.apps.googleusercontent.com",
  "aud": "407408718192.apps.googleusercontent.com",
  "sub": "117200475532672775",
  "email": "[email protected]",
  "email_verified": true,
  "at_hash": "hMyUqSfZ0ZFhvNfGF0RndA",
  "iat": 1690878599,
  "exp": 1690882199
}

请注意,您可以使用其中任何一个。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>