doukong1391 2016-03-08 06:48
浏览 387
已采纳

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

I write a handler so that when accessing the route /auth/google/callback, I try to login with Google account through OAuth2. The handler is implemented like this:

package route

import (
    "net/http"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "fmt"
)

func GoogleOAuthHandler(w http.ResponseWriter, r *http.Request) {
    conf:=&oauth2.Config{
        ClientID:"myclientid",
        ClientSecret:"myclientsecret",
        RedirectURL:"http://localhost:3000",
        Scopes:[]string{
            "https://www.googleapis.com/auth/userinfo.profile",
            "https://www.googleapis.com/auth/userinfo.email",
        },
        Endpoint:google.Endpoint,
    }

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

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

    fmt.Println(token)

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

In func main(), http.HandleFunc("/auth/google/callback",route.GoogleOAuthHandler) is setup

When I access that path, it throws an error like this on browser:

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

Did I miss something? Please instruct me to make a proper access to OAuth2 and get token and information from Google account

  • 写回答

1条回答 默认 最新

  • doumizhi0809 2016-03-08 07:54
    关注

    You are trying to access an url parameter (code) which is not defined in your url.

    r.URL.Query().Get() returns an url parameter defined in the url address. In your case you are searching for code param, which is missing.

    Checking the Exchange method, this converts an authorization code into a token.

    func (c *Config) Exchange(ctx context.Context, code string) (*Token, error).
    

    The token in your case is an url parameter, but it's not declared. To sum up please include the token string in the url as a parameter otherwise declare somewhere in your code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题