在编写想要验证 firebase id token (jwt) 的 AppEngine/Go 后端时,我在 AppEngine 上运行时遇到了这个问题:
http.DefaultTransport and http.DefaultClient are not available in App Engine. See https://cloud.google.com/appengine/docs/go/urlfetch/
此处描述了 Admin SDK:https://firebase.google.com/docs/admin/setup
只有当 client.ks 是一个导出的属性并且因此可以使用 lib 从应用程序写入时,以下内容可能会修复它:
client, err := app.Auth()
if err != nil {
log.Errorf(ctx, "Error getting auth client: %v", err)
writeJsonResponse(ctx, w, apiResponse{Message: "Firebase error"},
http.StatusInternalServerError)
return
}
// Override the HTTP client by using the urlfetch client to
// make it work under AppEngine
client.ks.HTTPClient = urlfetch.Client(ctx)
我的选择是否仅限于 a) fork 它并手动添加对 urlfetch 的支持 b) 除了看似官方的解决方案之外寻找其他解决方案..:o
编辑:按照 Gavin 的建议,我尝试将其更改为以下内容:
// Override the default HTTP client with AppEngine's urlfetch
opt := option.WithHTTPClient(urlfetch.Client(ctx))
app, err := firebase.NewApp(ctx, nil, opt)
if err != nil {
log.Errorf(ctx, "Error initializing firebase app: %v", err)
writeJsonResponse(ctx, w, apiResponse{Message: "Firebase error"},
http.StatusInternalServerError)
return
}
然而,这并不能解决问题。据我所知(在上述库 “firebase.google.com/go”
中做了一些源代码潜水),http.Client 通过选项传入。Client 仅用于 Creds创建:
creds, err := transport.Creds(ctx, o...)
而在 crypto.go
的方法 refreshKeys()
中完成的实际 HTTP 通信不使用此;相反,它会尝试使用 httpKeySource
中设置的 HTTPClient 属性。 IMO 这永远不会在任何地方设置,因此它总是默认为 http.DefaultClient
。
最佳答案
使用 Firebase Admin SDK 创建新应用程序时,您可以传入“google.golang.org/api/option”包中的选项。你要传入的选项是WithHTTPClient .
func handleRequest(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
opt := option.WithHTTPClient(urlfetch.Client(ctx))
app, err := firebase.NewApp(ctx, config, opt)
...
}
关于google-app-engine - 从 AppEngine 使用 Firebase Admin SDK for Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46038318/