Golang-Google OAuth 2授权-错误:重定向_uri_不匹配

vpfxa7rd  于 2022-10-08  发布在  Go
关注(0)|答案(1)|浏览(196)

我做了所有这些:Google OAuth 2 authorization - Error: redirect_uri_mismatch我已经添加了auth URI,但仍然不能使用“reDirect_uris”:[“https://localhost:8080”,“http://localhost:8080”,“http://localhost:8080/google_login”,“http://localhost:8080/google_callback”,“https://localhost”,“http://localhost”]

但我仍然收到这个错误消息:

我的main.go

func main() {
    // load configs
    godotenv.Load(".env")
    config.SetupConfig()

    // create a router
    mux := http.NewServeMux()

    // define routes
    mux.HandleFunc("/google_login", controllers.GoogleLogin)
    mux.HandleFunc("/google_callback", controllers.GoogleCallback)

    // run server
    log.Println("started server on :: http://localhost:8080/")
    if oops := http.ListenAndServe(":8080", mux); oops != nil {
        log.Fatal(oops)
    }
}

conants.go

func SetupConfig() *oauth2.Config {

    conf := &oauth2.Config{
        ClientID:     os.Getenv("NoteClientId"),
        ClientSecret: os.Getenv("NoteClientSecret"),
        RedirectURL:  "http://localhost:8080/google/callback",
        Scopes: []string{
            "https://www.googleapis.com/auth/userinfo.email",
            "https://www.googleapis.com/auth/userinfo.profile",
        },
        Endpoint: google.Endpoint,
    }

    return conf
}

google.go:

func GoogleLogin(res http.ResponseWriter, req *http.Request) {
    googleConfig := config.SetupConfig()
    url := googleConfig.AuthCodeURL("randomstate")

    http.Redirect(res, req, url, http.StatusSeeOther)
}

func GoogleCallback(res http.ResponseWriter, req *http.Request) {
    state := req.URL.Query()["state"][0]
    if state != "randomstate" {
        fmt.Fprintln(res, "states dont match")
        return
    }

    code := req.URL.Query()["code"][0]

    googleConfig := config.SetupConfig()

    token, err := googleConfig.Exchange(context.Background(), code)
    if err != nil {
        fmt.Fprintln(res, "Code-Token Exchange failed")
    }

    resp, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)
    if err != nil {
        fmt.Fprintln(res, "User data fetch failed")
    }

    userData, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Fprintln(res, "Json Parsing Failed")
    }

    fmt.Fprintln(res, string(userData))
}
zour9fqk

zour9fqk1#

这些URI都不是
[“https://localhost:8080”,“http://localhost:8080”,“http://localhost:8080/google_login”,“http://localhost:8080/google_callback”,“https://localhost”,“http://localhost”]

使您在constants.go中配置的重定向URI前进

重定向URL:“http://localhost:8080/google/callback”,

更改其中之一,以使它们匹配

相关问题