googleapis / google-api-java-client

Google APIs Client Library for Java
Apache License 2.0
1.35k stars 699 forks source link

AppScript in Android authorization error #1430

Closed jakubMitura14 closed 1 month ago

jakubMitura14 commented 4 years ago

Environment details

  1. google-api-services-script version: 'v1-rev437-1.25.0'
  2. Android 10
  3. Java version: 8
  4. google-api-client-android', version: '1.30.5'

Steps to reproduce

try to connect to App Script through android lie in the code below

Code example

Stack trace

first I establish scopes

/**gets Strings of scopes that we are intrested in*/
    private fun createListOfScopesStrings(): ArrayList<String> {
        val res = ArrayList<String>()
        res.addAll(ScriptScopes.all())
        res.addAll(
            arrayListOf(
                ClassroomScopes.CLASSROOM_ANNOUNCEMENTS,
                ClassroomScopes.CLASSROOM_COURSES,
                ClassroomScopes.CLASSROOM_COURSEWORK_ME,
                ClassroomScopes.CLASSROOM_COURSEWORK_STUDENTS,
                ClassroomScopes.CLASSROOM_GUARDIANLINKS_STUDENTS
                ,
                ClassroomScopes.CLASSROOM_PROFILE_EMAILS,
                ClassroomScopes.CLASSROOM_PUSH_NOTIFICATIONS,
                ClassroomScopes.CLASSROOM_ROSTERS,
                ClassroomScopes.CLASSROOM_TOPICS,
                ClassroomScopes.CLASSROOM_STUDENT_SUBMISSIONS_STUDENTS_READONLY
            )
        )
        res.addAll(DriveScopes.all())
        res.addAll(CalendarScopes.all())
        res.addAll(SheetsScopes.all())
        res.addAll(ScriptScopes.all())

        return res
    }

I invoke reqest sign in in onCreate

    private fun requestSignIn() {
        val client = buildGoogleSignInClient()
        startActivityForResult(client.signInIntent, REQUEST_SIGN_IN)
    }

    private fun buildGoogleSignInClient(): GoogleSignInClient {
        val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            // .requestScopes(Drive.SCOPE_FILE)
            // .requestScopes(Scope(DriveScopes.DRIVE_FILE))
            .requestEmail()
            .apply { listOfScopes.map { Scope(it) }.forEach { scope -> this.requestScopes(scope) } }
            .build()

        return GoogleSignIn.getClient(this, signInOptions)
    }

then i Create credential on the basis of sign in result

private fun handleSignInResult(result: Intent) {
        GoogleSignIn.getSignedInAccountFromIntent(result)
            .addOnSuccessListener { googleAccount ->
                // Use the authenticated account to sign in to the Drive service.
                val credential = GoogleAccountCredential.usingOAuth2(
                    this, listOfScopes
                )
                credential.selectedAccount = googleAccount.account

than I use it to build in the same way couple services like for drive and app script in a way specified below

  val appScriptService = Script.Builder(
                        createHttpTransport(),
                        JacksonFactory.getDefaultInstance(),
                        createRequestInitializer(credential)
                    )
                        .setApplicationName(getString(R.string.app_name))
                        .build()
 val googleDriveService: Drive = Drive.Builder(
                        createHttpTransport(),
                        JacksonFactory.getDefaultInstance(),
                        createRequestInitializer(credential)
                    )
                        .setApplicationName(getString(R.string.app_name))
                        .build()

 // creating http transport for sign in  use
    fun createHttpTransport(): HttpTransport {
        var res = ApacheHttpTransport.Builder().build()
return res
    }

    fun createRequestInitializer(reqInit: HttpRequestInitializer): HttpRequestInitializer {

        var res =  object : HttpRequestInitializer {
            override fun initialize(request: HttpRequest?) {
                reqInit.initialize(request);
                request?.setConnectTimeout(10 * 600000);
                request?.setReadTimeout(10 * 600000);
            }
        }
        return res
    }

as visible above the appscript and google drive services are created identically (the same applies to docs etc and all of those other services apart from app scipt works!)

then when I try to use function appScriptService.scripts().run() on any object I get error that will be specified below I had created app Script in google console published, enabled api in the console, enabled in cloud console all authority credentials and IT WORKED up to yesterday. I did not changed anything in code Hovewer when I woke up and tried to develop I was unable to connect to App service, Code when ivoked in App Script editor works fine Because other services that are authenthicated in identical way are woring and code stopped working with no changes in part of code responsible for authenthicating I suppose it may be bug

Any relevant stacktrace here.

D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@3912bc0[MainActivity]
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/AbstractGoogleClient: Application name is not set. Call Builder#setApplicationName.
W/DefaultRequestDirector: Authentication error: Unable to respond to any of these challenges: {}
W/DefaultRequestDirector: Authentication error: Unable to respond to any of these challenges: {}
E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-4
    Process: com.example.mituratest, PID: 28327
    com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
    {
      "code" : 401,
      "errors" : [ {
        "domain" : "global",
        "message" : "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "reason" : "unauthorized"
      } ],
      "message" : "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
      "status" : "UNAUTHENTICATED"
    }
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:443)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1092)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:541)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:474)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:591)
        at com.example.mituratest.mainObjects.AppsScriptConnection$checkIsFormReady$2.invokeSuspend(AppsScriptConnection.kt:209)
        at com.example.mituratest.mainObjects.AppsScriptConnection$checkIsFormReady$2.invoke(Unknown Source:10)
        at com.example.mituratest.utils.MyNet.err(MyNet.kt:15)
        at com.example.mituratest.mainObjects.AppsScriptConnection.checkIsFormReady(AppsScriptConnection.kt:209)
        at com.example.mituratest.MainActivity$handleSignInResult$1$1$1.invokeSuspend(MainActivity.kt:220)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:594)
        at kotlinx.coroutines.scheduling.CoroutineScheduler.access$runSafely(CoroutineScheduler.kt:60)
        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:740)

Any additional information below

buid gradle

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {

    compileSdkVersion 29
    buildToolsVersion "29.0.1"
    defaultConfig {
        applicationId "com.example.mituratest"
        minSdkVersion 26
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }

}
repositories {
    google()
    maven { url 'https://jitpack.io' }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.navigation:navigation-fragment:2.1.0'
    implementation 'androidx.navigation:navigation-ui:2.1.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.1.0'
    implementation 'androidx.navigation:navigation-ui-ktx:2.1.0'
   implementation group: 'com.google.api-client', name: 'google-api-client-android', version: '1.30.5'
    implementation 'com.google.android.gms:play-services-cronet:17.0.0'
//        implementation('com.google.api-client:google-api-client-android:30.2') {
//        exclude group: 'org.apache.httpcomponents'
//        exclude module: 'guava-jdk5'
//    }
   implementation 'com.google.android.gms:play-services-auth:17.0.0'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'
    //implementation 'com.jakewharton.timber:timber:4.7.1'
    implementation group: 'com.google.apis', name: 'google-api-services-drive', version: 'v3-rev173-1.25.0'
    implementation group: 'com.google.apis', name: 'google-api-services-sheets', version: 'v4-rev581-1.25.0'
    implementation group: 'com.google.apis', name: 'google-api-services-calendar', version: 'v3-rev379-1.25.0'
    implementation group: 'com.google.apis', name: 'google-api-services-gmail', version: 'v1-rev105-1.25.0'
    implementation group: 'com.google.apis', name: 'google-api-services-docs', version: 'v1-rev29-1.25.0'
    implementation group: 'com.google.apis', name: 'google-api-services-classroom', version: 'v1-rev302-1.25.0'
    implementation group: 'org.jsoup', name: 'jsoup', version: '1.12.1'
 //   implementation group: 'io.selendroid', name: 'selendroid-standalone', version: '0.17.0'
    implementation  group: 'com.google.apis', name: 'google-api-services-script', version: 'v1-rev437-1.25.0'
   // implementation  group: 'com.jayway.android.robotium', name: 'robotium-solo', version: '5.6.3'
    implementation 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
    implementation 'com.squareup.okio:okio:1.14.0'
    implementation 'com.google.firebase:firebase-ml-vision:24.0.1'
    implementation 'com.google.firebase:firebase-ml-vision-barcode-model:16.0.2'
    implementation 'com.google.zxing:core:3.2.1'
    implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    implementation 'com.github.salomonbrys.kotson:kotson:2.5.0'

}

Thanks!

burkedavison commented 1 month ago

Closing this issue as we are unable to provide adequate customer support through this forum. If you feel there is a bug or a feature request associated with this ticket, please open a new issue. Otherwise, https://cloud.google.com/support is best able to provide timely answers to API-specific questions.