我写了一个回调处理程序来登录Google帐户:
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)
}
在main
中,我提供处理程序
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)),
))
我遇到了与旧问题相同的问题: oauth2 cannot fetch token: bad request
oauth2: cannot fetch token: 400 Bad Request
Response: {
"error" : "invalid_request",
"error_description" : "Missing required parameter: code"
}
上次我问过这个问题之后,我设法用上面的代码修复它,成功访问并获取数据,但是昨晚又突然出现了这个错误,我不明白为什么它不再适用了几天使用完全相同的代码
如何从code
获取AuthCodeURL
?有没有办法获得交换代码而无需重定向到任何其他处理程序?我想在一个这个处理程序中处理所有事情
答案 0 :(得分:0)
我可以通过添加一个处理程序来解决它
if(isset($_POST['cmd_delete_location'])){
// echo $LocationID = $this->input->post('hidden_id');
$LocationID = $this->input->post('cmd_delete_location');
$location_used_in_other_transaction = $this->main_m->get_where('temperaturelogs', array('LocationID' => $LocationID));
if($location_used_in_other_transaction)
{
$_SESSION['type'] = "warning";
$_SESSION['message'] = "Unable to Delete: Location is already used in other transaction!";
redirect(current_url());
}else{
$this->main_m->delete_data('locations', array('LocationID' => $LocationID));
$_SESSION['type'] = "success";
$_SESSION['message'] = "Location's Successfully Deleted!";
redirect(current_url());
}
}