0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ウェブアプリで Google 認証して API 呼出してみたの続き

0
Posted at

はじめに

以前にウェブアプリから Google アカウント認証して API 呼出してみました。

ウェブアプリで Google アカウント認証して API 呼出してみた #JavaScript - Qiita

このときはログインするのに gapi.auth2.getAuthInstance().signIn() しているのですが、現在は非推奨となっています。
(https://developers.google.com/identity/gsi/web/guides/migration?hl=ja)
代わって Google Identity Services を利用するようにしたいと思います。
(https://developers.google.com/identity/oauth2/web/guides/migration-to-gis?hl=ja)

ウェブクライアントアプリを作成する

既存のウェブクライアントアプリを使用します。

Google アカウント認証の準備する

  1. 開発者の Google アカウントで Google Developer Console を開く
    (https://console.cloud.google.com/)
  2. プロジェクトを作成する
    (https://console.developers.google.com/project)
  3. 使用したい API を選択して有効にする
    (https://console.developers.google.com/apis/library)
  4. 認証情報を作成する
    (https://console.developers.google.com/apis/credentials)

OAuth 認証情報を作成する

OAuth 認証情報 は、まず API キー を作成します。

以下の項目を設定します。

  • 名前 ←任意です
  • 制限 ←必要に応じて指定します

以下の情報が作成されます。後で使用します。

  • API キー

続いて、OAuth クライアント ID を作成します。

タイプ(種類)ウェブアプリケーション

以下の項目を設定します。

  • 名前 ←任意です
  • JavaScript 生成元 ←クライアントアプリのサーバの URL
  • リダイレクト URI ←設定は不要

以下の情報が作成されます。後で使用します。

  • クライアント ID

利用したい API を有効にする

今回は Google Drive の情報を取得したいので、対象プロジェクトに対して Google Drive API を有効にしておきます。

スコープを調べておく

使用したい Google API に対応するスコープを調べておきます。

OAuth 2.0 Scopes for Google APIs | Google Identity Platform | Google Developers

今回は Google Drive API を使用したいので、スコープは https://www.googleapis.com/auth/drive になります。

ウェブクライアントアプリで Google アカウント認証する

アプリにクライアントライブラリを組込する

Google のウェブサイトでクライアントライブラリを入手します。

index.html
<script type="text/javascript" src="https://accounts.google.com/gsi/client"></script>
<script type="text/javascript" src="https://apis.google.com/js/api.js"></script>

クライアントライブラリを初期化する

上記で取得しておいた API キークライアント IDスコープ を指定して、クライアントライブラリを初期化します。

index.js
var apiKey = '●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●';
var clientId = '●●●●●●-●●●●●●●●●●●●●●●●.apps.googleusercontent.com';
var scope = 'https://www.googleapis.com/auth/drive';

document.addEventListener('DOMContentLoaded', function(){
    var client = google.accounts.oauth2.initTokenClient({
        client_id: clientId,
        scope: scope,
    });

    gapi.load('client', function(){
        gapi.client.init({
            apiKey: apiKey,
            clientId: clientId,
            scope: scope
        })
        .then(function(){
            console.log("gapi loaded.");
        })
        .catch(function(error){
            console.log("Error: ", error);
        });
    });
(後略)

ログインボタンを用意する

アプリの画面に、ログインするためのボタンを用意しましょう。

index.html
<button id="login">Login</button>
<p id="status">Not logged in.</p>

ログインするコードを追加する

ログインするコードを追加します。

index.js
document.querySelector('#login').addEventListener('click', function(){
    client.callback = (response) => {
        if (!response.error) {    // 認証に成功
            document.querySelector('#status').innerHTML = "Succeeded. " + JSON.stringify(response);
        }
        else {    // 認証に失敗
            document.querySelector('#status').innerHTML = "Failed. " + JSON.stringify(response);
        }
    };
    client.requestAccessToken();    // 認証を開始する
});

requestAccessToken() すると Google のログイン画面が開きます。ユーザが操作して認証されると callback に指定した処理されます。

ログイン処理のエラー

ここで、「アクセスをブロック:認証エラー」になりました。OAuth クライアントの JavaScript 生成元 の設定がない、あるいは適切でないと発生します。
http://localhosthttp://127.0.0.1 は別になります。例えば OAuth クライアントの設定が http://localhost でウェブアプリを開くのに http://127.0.0.1 だとエラーになります。これに気づくのに手間取りました。

ウェブクライアントアプリで Google API 呼出する

Google API 呼出ボタンを用意する

アプリの画面に、Goolge API 呼出するためのボタンを用意しましょう。

index.html
<button id="request">Call API</button>
<p id="result"></p>

Google API を呼出するコードを追加する

認証されたクライアントオブジェクトで Google API が呼出できます。

呼出するためのエンドポイント(URI)はリファレンスを参照します。
今回は Google Drive を操作します。API Reference | Drive REST API | Google Developers

index.js
document.querySelector('#request').addEventListener('click', function(){
    if (!gapi.client.getToken()) {    // アクセストークンがない場合
        document.querySelector('#status').innerHTML = "Failed. " + "No access token available.";
        return;
    }
    gapi.client.request({   // Google API を呼出する
        path: 'https://www.googleapis.com/drive/v3/about',
        method: 'GET',
        params: {
            'fields': 'user',
        }
    })
    .then(function(response){
        document.querySelector('#result').innerHTML = "Succeeded. " + JSON.stringify(response);
    })
    .catch(function(reason){
        document.querySelector('#result').innerHTML = "Failed. " + JSON.stringify(reason.body);
    });
});

API 呼出のエラー

ここで、ステータス 403(Access Not Configured. ... API has not been used in project ... before or it is disabled.)になりました。Google Developer Console で呼出する API を有効にしてないと発生します。

また、ステータス 403(Insufficient Permission)になりました。ログイン認証するときに指定するスコープが適切でないと発生します。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?