2014-10-30 147 views
0

我一直試圖實施OAuth2 for Go與App引擎服務器到服務器請求。Go App引擎oauth2請求

這裏是代碼(以下例子):

oauthConf, err := google.NewServiceAccountJSONConfig(
    "./key.json", 
    "https://www.googleapis.com/auth/adsense.readonly", 
) 
if err != nil { 
    log.Fatal(err) 
} 

client := http.Client{Transport: oauthConf.NewTransport()} 
resp, err := client.Get(urlStr) 
... 

而我得到的錯誤信息:

http.DefaultTransport和http.DefaultClient不可在App Engine中。

我敢肯定的json.key文件是爲其他的東西

谷歌搜索使我明白,這是最好使用網址抓取有效的,但我無法弄清楚如何使用oauth2配置進行設置。

回答

0

NewServiceAccountJSONConfig返回oauth2.JWTConfig https://github.com/golang/oauth2/blob/master/google/google.go#L69-L87

.NewTransport()您使用:
https://github.com/golang/oauth2/blob/master/jwt.go#L86-L88

默認爲http.DefaultTransport,不支持AppEngine上:
https://github.com/golang/oauth2/blob/master/jwt.go#L163-L168

我會去代替使用AppEnigneConfig(如果可能)。見http://godoc.org/github.com/golang/oauth2/google

c := appengine.NewContext(nil) 
config := google.NewAppEngineConfig(c, "https://www.googleapis.com/auth/bigquery") 
// The following client will be authorized by the App Engine 
// app's service account for the provided scopes. 
client := http.Client{Transport: config.NewTransport()} 
client.Get("...") 

否則,如果你需要使用ServiceAccountJSONConfig,你或許可以,但你需要使用urlfetchClientTransport。看看如何設置AppEngineConfighttps://github.com/golang/oauth2/blob/master/google/appengine.go

+0

我看不到我可以在哪裏爲oauth2插入key.json(或替代客戶端憑據+私鑰) – drtf 2014-10-31 14:26:14

+0

@MrKlint不,在appengine中使用Google服務帳戶,所以它將使用appengine項目的憑證。如果您需要使用其他憑據,則必須自行推出。查看https://github.com/golang/oauth2/blob/master/google/appengine.go查看傳輸和客戶端是如何設置的。 – fredrik 2014-11-04 00:05:56