【问题标题】:Using Firebase Admin SDK for Go from AppEngine从 AppEngine 使用 Firebase Admin SDK for Go
【发布时间】:2018-02-12 18:23:50
【问题描述】:

在编写想要验证 Firebase id 令牌 (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) 分叉并手动添加对 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" 中进行了一些源代码潜水),通过 options.Client 传入的 http.Client 仅用于创建 Creds:

creds, err := transport.Creds(ctx, o...)

并且在crypto.go的方法refreshKeys()中完成的实际HTTP通信不使用这个;相反,它尝试使用在httpKeySource 中设置的HTTPClient 属性。 IMO 永远不会在任何地方设置它,因此它始终默认为 http.DefaultClient

【问题讨论】:

    标签: google-app-engine firebase go firebase-authentication firebase-admin


    【解决方案1】:

    使用 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)
        ...
    }
    

    【讨论】:

    • 谢谢,这是个好主意。但是,该库似乎没有使用此 http.Client 与密钥服务器进行 HTTP 通信;请看我的编辑。库中的错误/监督?
    • 好收获。 Admin SDK 当前在获取公钥证书时使用http.DefaultClient。这需要修复以使用初始化应用程序时传递的客户端选项。
    • github.com/firebase/firebase-admin-go/pull/12 正在开发一个修复程序。您应该可以通过构建 hkj-http-client 分支来尝试它。非常感谢任何反馈。
    • 你真的试过这个吗?它对我在 appengine 中进行托管取得了成功。
    • @Gavin 是的,我确实尝试过。 @HiranyaJayathilaka 估计什么时候会出现在您使用go get 获得的版本中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    • 2018-03-20
    • 2020-03-23
    • 2018-09-02
    相关资源
    最近更新 更多