golang操作golang.org/x/oauth2库第三方登录github

593 阅读1分钟

golang操作golang.org/x/oauth2库第三方登录github

 package main
 ​
 import (
    "net/http"
 ​
    "github.com/gin-gonic/gin"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/github"
 )
 ​
 // 创建 GitHub OAuth2 配置
 var (
    githubOauthConfig = &oauth2.Config{
       ClientID:     "14023dc0974e8eef4aea",
       ClientSecret: "eb869c9936f2c6e0de68f1fe2ed3680127cc1ef8",
       Scopes:       []string{"user:email", "repo"},
       Endpoint:     github.Endpoint,
    }
 )
 ​
 // 处理第三方 Github 登录请求
 func handleGithubLogin(c *gin.Context) {
    // 构造重定向到 GitHub 认证 URL 的 URL
    authURL := githubOauthConfig.AuthCodeURL("state")
 ​
    // 重定向到 GitHub 认证 URL
    c.Redirect(http.StatusTemporaryRedirect, authURL)
 }
 ​
 // 处理 GitHub 登录回调请求
 func handleGithubCallback(c *gin.Context) {
    // 从查询参数中提取认证令牌
    code := c.Query("code")
 ​
    // 使用认证令牌交换访问令牌
    token, err := githubOauthConfig.Exchange(c, code)
    if err != nil {
       c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
       return
    }
 ​
    // 在响应中返回访问令牌
    c.JSON(http.StatusOK, gin.H{"access_token": token.AccessToken})
 }
 ​
 func main() {
    // 初始化 Gin 引擎
    r := gin.Default()
 ​
    // 创建 GitHub OAuth2 配置
    githubOauthConfig.RedirectURL = "http://localhost:8080/github/callback"
 ​
    // 注册第三方 GitHub 登录路由
    r.GET("/github/login", handleGithubLogin)
 ​
    // 注册 GitHub 登录回调路由
    r.GET("/github/callback", handleGithubCallback)
 ​
    // 启动 HTTP 服务器
    r.Run(":8080")
 }