LoginSignup
4
5

More than 5 years have passed since last update.

PythonからGoogle APIsを利用する際のOAuth2エラーの対処方法

Last updated at Posted at 2015-07-16

下記の記事を参考に、Google APIs Client for PythonからBigQueryを利用した際、OAuth認証関連のエラーが出たので対処方法を残しておく。ファイルのパーミッションが原因で、接続可能なSSL証明書が定義されたcacerts.txtというファイルが読めなかったために発生したようだ。

BigQueryをpythonから利用する。
http://qiita.com/shibacow/items/b8f6445058b374291be5

Using OAuth 2.0 for Server to Server Applications
https://developers.google.com/api-client-library/python/auth/service-accounts

環境

OSX 10.10.3
Python 2.7.6
httplib2 0.9.1
google-api-python-client 1.4.1

事象

Google APIs Client Library for Python を利用し、P12ファイルを利用して、BigQueryを利用した際に、認証関係のエラーが生じAPIへのアクセスができなかった。

ssl.SSLError: [Errno 185090050] _ssl.c:343: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib

なお、実行したファイルは下記の通り。

bq-access.py
import json
from httplib2 import Http
from oauth2client.client import SignedJwtAssertionCredentials
from apiclient.discovery import build

SERVICE_ACCOUNT_EMAIL = '**********@developer.gserviceaccount.com'
PROJECT_NUMBER = '**********'
KEYFILE='******************.p12'

with open(KEYFILE) as f:
  private_key = f.read()

credentials = SignedJwtAssertionCredentials(
    SERVICE_ACCOUNT_EMAIL, private_key,
    'https://www.googleapis.com/auth/bigquery')

http = Http()
credentials.authorize(http)

service = build('bigquery', 'v2', http=http)
response = service.datasets().list(projectId='************').execute()

print response

対処方法

下記のページがとても参考になった。

PYTHON OAUTH2 FAILING WITH X509 ERROR
http://bretthutley.com/tag/mac-osx/

http2libのcacerts.txtというファイルの権限に問題があるとのことなので調べてみると、確かにwheelというグループでないと読めないようになっていた。

> cd /Library/Python/2.7/site-packages/httplib2-0.9.1-py2.7.egg/httplib2/
> ls -l cacerts.txt
-rw-r-----  1 root  wheel  134862  7 13 18:36 cacerts.txt

従って、chmodコマンドでファイルの権限を下記の通り変更したところ、問題なくアクセスできるようになった。

> sudo chmod 644 cacerts.txt
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5