Ошибки аутентификации Firebase - после миграции проекта - PullRequest
1 голос
/ 07 июля 2019

Ожидаемое

Приложение Kotlin, работающее в IntelliJ, было перенесено с MacBook Pro 2009 года на MacBook Pro 2019 года. Предполагается, что при наличии одинаковых учетных данных в проекте будет выполняться идентичный код для доступа к базе данных Firestore и Firestore Storage .

Наблюдаемые

Код не будет работать на новом компьютере из-за ошибок oauth .

Ошибка

  1. com.google.api.gax.grpc.InstantiatingGrpcChannelProvider не определяет и не наследует реализацию разрешенного метода abstract needsCredentials ()

  2. Не удалось определить, работаем ли мы на Google Compute Engine.

Вход

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Jul 07, 2019 11:45:41 AM com.google.auth.oauth2.ComputeEngineCredentials runningOnComputeEngine
INFO: Failed to detect whether we are running on Google Compute Engine.
Exception in thread "Timer-0" java.lang.AbstractMethodError: Receiver class com.google.api.gax.grpc.InstantiatingGrpcChannelProvider does not define or inherit an implementation of the resolved method abstract needsCredentials()Z of interface com.google.api.gax.rpc.TransportChannelProvider.
at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:157)
at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:122)
at com.google.cloud.firestore.spi.v1beta1.GrpcFirestoreRpc.<init>(GrpcFirestoreRpc.java:121)
at com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreRpcFactory.create(FirestoreOptions.java:80)
at com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreRpcFactory.create(FirestoreOptions.java:72)
at com.google.cloud.ServiceOptions.getRpc(ServiceOptions.java:510)
at com.google.cloud.firestore.FirestoreOptions.getFirestoreRpc(FirestoreOptions.java:315)
at com.google.cloud.firestore.FirestoreImpl.<init>(FirestoreImpl.java:76)
at com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreFactory.create(FirestoreOptions.java:63)
at com.google.cloud.firestore.FirestoreOptions$DefaultFirestoreFactory.create(FirestoreOptions.java:56)
at com.google.cloud.ServiceOptions.getService(ServiceOptions.java:498)
at com.google.firebase.cloud.FirestoreClient.<init>(FirestoreClient.java:51)
at com.google.firebase.cloud.FirestoreClient.<init>(FirestoreClient.java:29)
at com.google.firebase.cloud.FirestoreClient$FirestoreClientService.<init>(FirestoreClient.java:95)
at com.google.firebase.cloud.FirestoreClient.getInstance(FirestoreClient.java:85)
at com.google.firebase.cloud.FirestoreClient.getFirestore(FirestoreClient.java:78)
at com.google.firebase.cloud.FirestoreClient.getFirestore(FirestoreClient.java:64)
at utils.FirebaseClient.<clinit>(FirebaseClient.kt:10)
at utils.FirestoreCollectionsKt.<clinit>(FirestoreCollections.kt:5)
at content.ContentTasks.getExistingContentSet(ContentTasks.kt:89)
at content.ContentTasks.run(ContentTasks.kt:39)
at java.base/java.util.TimerThread.mainLoop(Timer.java:556)
at java.base/java.util.TimerThread.run(Timer.java:506)

Process finished with exit code 0

Существующий код для аутентификации

Initialization.kt

object Initialization {
    @JvmStatic
    fun main(args: Array<String>) {
        set(Enums.EnvironmentType.STAGING)
        initializeFirestore()
        getContent()
    }

    private fun initializeFirestore() {
        FirebaseApp.initializeApp(FirebaseOptions.Builder()
            .setCredentials(fromStream(Gson().toJson(getFirebaseCredentials()).byteInputStream()))
            .setFirestoreOptions(FirestoreOptions.newBuilder().setTimestampsInSnapshotsEnabled(true).build())
            .build())
    }
}

CredentialsHelper.kt

fun getFirebaseCredentials() =
    if (environmentType == PRODUCTION) FirebaseCredentials(
            "service_account",
            "[projectId]",
            "[privateKeyId]",
            "[privateKey]",
            "[clientEmail]",
            "[clientId]",
            "https://accounts.google.com/o/oauth2/auth",
            "https://accounts.google.com/o/oauth2/token",
            "https://www.googleapis.com/oauth2/v1/certs",
            "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-0z4rn%40carpecoin-media-211903.iam.gserviceaccount.com")
    else FirebaseCredentials(
            "service_account",
            "[projectId]",
            "[privateKeyId]",
            "[privateKey]",
            "[clientEmail]",
            "[clientId]",
            "https://accounts.google.com/o/oauth2/auth",
            "https://accounts.google.com/o/oauth2/token",
            "https://www.googleapis.com/oauth2/v1/certs",
            "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-dhr30%40coinverse-media-staging.iam.gserviceaccount.com")

Попытка решения

Обновление версий библиотеки в build.gradle на случай, если проблема вызвана конфликтом зависимостей.

build.gradle

buildscript {
    ext.kotlin_version = '1.3.41'
    ext.junitJupiterVersion  = '5.5.0'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.3'
    }
}

plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.2.51'
}

version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    testImplementation group: 'junit', name: 'junit', version: '5.3.2'
    // JUnit Jupiter API and TestEngine implementation
    testImplementation("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
    testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")
    testImplementation "org.assertj:assertj-core:3.12.2"
    // To avoid compiler warnings about @API annotations in JUnit code
    testCompileOnly 'org.apiguardian:apiguardian-api:1.1.0'
    implementation 'com.squareup.retrofit2:retrofit:2.6.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.6.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.10'
    implementation 'com.google.firebase:firebase-admin:6.8.1'
    implementation 'com.google.cloud:google-cloud-storage:1.79.0'
    implementation 'com.google.apis:google-api-services-youtube:v3-rev212-1.25.0'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

1 Ответ

0 голосов
/ 11 июля 2019

Это потому, что «gax», от которого «firebase-admin» зависит от «gax-grpc», устарел, поэтому более новый «gax», который представляет другая библиотека, возможно, «google-cloud-storage» в вашем случае, выбран Gradle, что приводит к проблеме совместимости.

В моем случае, принудительное использование Gradle последней версии gax-grpc, как показано ниже, решило проблему. Надеюсь, это поможет и вам.

implementation group: 'com.google.api', name: 'gax-grpc', version: '1.47.1'
...