Techioz Blog

Google API - 「アクティブなセッションが無効です。エラー コード: 4」

概要

Oauth2 を介して Google Drive API にアクセスしようとしていますが、検索時に結果が得られないエラーが発生しました。

これが私のコードです。

require "oauth2"
require "google/apis/gmail_v1"
require "google/apis/drive_v3"
require "googleauth"

token = { 
    access_token: ...,
    refresh_token: ...,
}

def get_gmail_service(token)
  service = Google::Apis::GmailV1::GmailService.new
  service.authorization = oauth_authorization(token,
    [ Google::Apis::GmailV1::AUTH_GMAIL_READONLY, Google::Apis::GmailV1::AUTH_GMAIL_LABELS]
  )
  service.request_options.retries = 3
  service
end

def get_drive_service(token)
  service = Google::Apis::DriveV3::DriveService.new
  service.authorization = oauth_authorization(token,
    [ Google::Apis::DriveV3::AUTH_DRIVE ]
  )
  service.request_options.retries = 3
  service
end

def oauth_authorization token, scope
  Signet::OAuth2::Client.new({
    authorization_uri: "https://accounts.google.com/o/oauth2/auth",
    token_credential_uri: "https://accounts.google.com/o/oauth2/token",
    client_id: ENV["G_CLIENT_ID"],
    client_secret: ENV["G_CLIENT_SECRET"],
    access_token: token["access_token"],
    refresh_token: token["refresh_token"],
    scope: scope
  })
end

get_gmail_service(token).create_user_label('me', 'test') #=> WORKS
get_drive_service(token).list_files #=> ERROR 

これが私が受け取るエラーです。

Google::Apis::AuthorizationError:Unauthorized
{
  "error": {
    "code": 401,
    "message": "The caller does not have permission",
    "errors": [
      {
        "message": "Active session is invalid. Error code: 4",
        "domain": "global",
        "reason": "authError",
        "location": "Authorization",
        "locationType": "header"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

すべての検索から、トークンの有効期限が切れているように見えますが、トークンは Gmail API でも同時に動作するため、期限切れではないと思います。

私は何を試しましたか?

解決策

この 403 応答は、Google ドライブがポリシーによって無効になっていることが原因で発生します。これは、組織単位ごとまたはグループ メンバーシップを通じて行うことができます。この 403 レスポンスは、Drive 自体ではなく、Drive SDK API を使用した Google ドライブへのアクセスのみがオフになっている場合に実際に役立つ詳細ペイロードとともに返される 401 レスポンスとは異なります。スーパー管理者の認証情報がそのような制限の対象になるとは思いませんが、Google Workspace は神秘的な生き物なので、その可能性はあります。

これはひどい間違いですが、ありがたいことに十分にユニークなので、人々がこの質問にたどり着くことが期待されます。

私の知る限りでは、GET /about エンドポイント (または同様の「常に機能するはずです」リクエスト) を呼び出し、401 または 403 応答をレスキューしてポリシーが適用されていることを事前に知る方法はありません。ユーザーごとの状況