使用自定义令牌进行 Firebase 身份验证

Por*_*iaz 5 ruby ruby-on-rails jwt firebase firebase-authentication

我有一个 firebase 项目,我试图从我的 rails 服务器进行身份验证,使用库 ruby​​-jwt 创建自定义令牌,如文档中所说,但我不断收到相同的错误:

auth/invalid-custom-token,自定义令牌格式不正确。请检查文档。

credentials.json是我在谷歌做出控制台服务帐户,UID是从前端向API发送。

def generate_auth_token(uid)
  now_seconds = Time.now.to_i
  credentials = JSON.parse(File.read("credentials.json"))
  private_key = OpenSSL::PKey::RSA.new credentials["private_key"]
  payload = {
      :iss => credentials["client_email"],
      :sub => credentials["client_email"],
      :aud => 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit',
      :iat => now_seconds,
      :exp => now_seconds+(60*60), # Maximum expiration time is one hour
      :uid => uid.to_s,
      :claims => {:premium_account => true}
    }
  JWT.encode(payload, private_key, 'RS256')
end
Run Code Online (Sandbox Code Playgroud)

在 jwt.io 中看起来像这样

{
  "iss": "defered@defered.iam.gserviceaccount.com",
  "sub": "defered@defered.iam.gserviceaccount.com",
  "aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
  "iat": 1486824545,
  "exp": 1486828145,
  "uid": "4",
  "claims": {
     "premium_account": true
   }
}
Run Code Online (Sandbox Code Playgroud)

Por*_*iaz 2

我找到了一种更好的身份验证方法,我只是发送 firebase 为您提供的令牌,并使用我需要的信息在 Rails 上验证它,仅此而已。