Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Github oauth return error: The code passed is incorrect or expired #714

Closed
xiaolin310 opened this issue Apr 2, 2024 · 0 comments
Closed

Comments

@xiaolin310
Copy link

After I do login, github returned a validate token, and When do login again , it raised an error The code passed is incorrect or expired

My code is as follows,

import (
    "context"
    "fmt"
    "github.com/gin-gonic/gin"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/github"
    "net/http"
)

var (
    oauthConf = &oauth2.Config{
        ClientID:     "your-client-id",
        ClientSecret: "your-client-secret",
        RedirectURL:  "http://localhost:8080/callback",
        Scopes:       []string{"user:email"},
        Endpoint:     github.Endpoint,
    }
)

func main() {
    r := gin.Default()

    r.GET("/", func(c *gin.Context) {
        html := "<a href='/login/github'>Login with GitHub</a>"
        c.HTML(http.StatusOK, "login.html", gin.H{"html": html})
    })

    r.GET("/login/github", func(c *gin.Context) {
        url := oauthConf.AuthCodeURL("state", oauth2.AccessTypeOffline)
        c.Redirect(http.StatusTemporaryRedirect, url)
    })

    r.GET("/callback", func(c *gin.Context) {
        code := c.Query("code")
        token, err := oauthConf.Exchange(context.Background(), code)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        client := oauthConf.Client(context.Background(), token)
        resp, err := client.Get("https://api.github.com/user/emails")
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        defer resp.Body.Close()

        c.JSON(http.StatusOK, resp)
    })

    r.Run(":8080")
}

The error is traced to this line,

        url := oauthConf.AuthCodeURL("state", oauth2.AccessTypeOffline)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant