duanla4959 2016-03-15 04:10 采纳率: 0%
浏览 377
已采纳

go-oauth2无法获取令牌:错误的请求

I write a callback handler to login with Google account:

func GoogleCallbackHandler(w http.ResponseWriter, r *http.Request) {
    conf:=&oauth2.Config{
        ClientID:"700740834863-m4om9r91htn19htq2b6a05fu6vu4j7i5.apps.googleusercontent.com",
        ClientSecret:"...-rB",
        RedirectURL:"http://localhost:3000/auth/google/callback",
        Scopes:[]string{"profile"},
        Endpoint:google.Endpoint,
    }

    fmt.Println(conf.AuthCodeURL("state"))

    code := r.URL.Query().Get("code")

    token, err := conf.Exchange(oauth2.NoContext, code)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    client := conf.Client(oauth2.NoContext, token)
    resp, err := client.Get("https://www.googleapis.com/userinfo/v2/me")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    raw, err := ioutil.ReadAll(resp.Body)
    defer resp.Body.Close()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    var profile map[string]interface{}
    if err := json.Unmarshal(raw, &profile); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    session, _ := util.GlobalSessions.SessionStart(w, r)
    defer session.SessionRelease(w)

    session.Set("id_token", token.Extra("id_token"))
    session.Set("access_token", token.AccessToken)
    session.Set("profile", profile)

    // // Redirect to logged in page

    http.Redirect(w, r, "/user", http.StatusMovedPermanently)
}

In main, I serve handlers

http.HandleFunc("/",route.IndexHandler)
http.HandleFunc("/auth/google/",route.GoogleCallbackHandler)
http.Handle("/user",negroni.New(
    negroni.HandlerFunc(route.IsAuthenticated),
    negroni.Wrap(http.HandlerFunc(route.UserHandler)),
))

I encounter the same problem I got with my old question: oauth2 cannot fetch token: bad request

oauth2: cannot fetch token: 400 Bad Request
Response: {
  "error" : "invalid_request",
  "error_description" : "Missing required parameter: code"
}

After I asked this question last time, I managed to fix it with my above code, accessing and getting data successfully, but last night it suddenly got this error again, and I don't get why it no longer works after last few days working with totally same code

How can I get the code from AuthCodeURL? Is there any way to get the code for exchanging without redirecting to any other handler? I want to handle all things in just one this handler

  • 写回答

1条回答 默认 最新

  • dongyanjing5975 2016-03-15 06:40
    关注

    I can solve it by adding one more handler

    var (
        conf *oauth2.Config
    )
    
    func GoogleCallbackHandler(w http.ResponseWriter, r *http.Request) {
        conf=&oauth2.Config{
            ClientID:"700740834863-m4om9r91htn19htq2b6a05fu6vu4j7i5.apps.googleusercontent.com",
            ClientSecret:"...-rB",
            RedirectURL:"http://localhost:3000/auth/google/callback",
            Scopes:[]string{"profile"},
            Endpoint:google.Endpoint,
        }
    
        http.Redirect(w, r, conf.AuthCodeURL("state"), http.StatusMovedPermanently)
    }
    
    func GoogleLoginHandler(w http.ResponseWriter, r *http.Request) {
        code := r.URL.Query().Get("code")
    
        token, err := conf.Exchange(oauth2.NoContext, code)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    
        client := conf.Client(oauth2.NoContext, token)
        resp, err := client.Get("https://www.googleapis.com/userinfo/v2/me")
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    
        raw, err := ioutil.ReadAll(resp.Body)
        defer resp.Body.Close()
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    
        var profile map[string]interface{}
        if err := json.Unmarshal(raw, &profile); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    
        session, _ := util.GlobalSessions.SessionStart(w, r)
        defer session.SessionRelease(w)
    
        session.Set("id_token", token.Extra("id_token"))
        session.Set("access_token", token.AccessToken)
        session.Set("profile", profile)
    
        http.Redirect(w, r, "/user", http.StatusMovedPermanently)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动
  • ¥15 大一C语言期末考试,求帮助🙏🙏
  • ¥15 ch340驱动未分配COM
  • ¥15 Converting circular structure to JSON
  • ¥30 Hyper-v虚拟机相关问题,求解答。
  • ¥15 TSM320F2808PZA芯片 Bootloader
  • ¥45 谷歌浏览器出现开发者工具无法显示已创建的,但您可以调试已部署的代码。 状态代码 404, net::ERR HTTP RESPONSE CODE FAILURE
  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错