LoginSignup
18
15

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-01-19

はじめに

Cordova アプリから Google アカウント認証して API 呼出してみました。

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

いわゆるウェブクライアントアプリでも同様のことをしておきたいと思います。

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

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

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

  1. Google アカウントを作成する。既にあればそれを使用する
    (https://www.google.com/accounts)

  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 同意画面 を設定します。

OAuth クライアント ID を作成する

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

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

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

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

  • API キー

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

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

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

  • 名前 ←任意です
  • JavaScript 生成元
  • リダイレクト 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://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).ready(function(){
    gapi.load('client', function(){
        gapi.client.init({
            apiKey: apiKey,
            clientId: clientId,
            scope: scope
        })
        .then(function(){
            console.log("gapi loaded.");
        })
    });
});

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

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

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

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

ログインするコードを追加します。このサンプルは jQuery を使用しています。

index.js
$('#login').click(function(){
    gapi.auth2.getAuthInstance().signIn()
    .then(function(obj){
        if (!obj.error) {    // 認証に成功
            $('#status').html("Success: " + obj.w3.U3);
            $('#image').attr('src', obj.w3.Paa);
            $('#image').show();
        }
        else {    // 認証に失敗
            $('#status').html("Error: " + obj.error);
        }
    });
});

ウェブクライアントアプリで 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
$('#request').click(function(){
    if (!gapi.auth2.getAuthInstance().isSignedIn.get()) {
        return;
    }
    gapi.client.request({
        path: 'https://www.googleapis.com/drive/v3/about',
        method: 'GET',
        body: {
            'fields': 'user',
        }
    })
    .then(function(response){
        console.log('Succeeded. ');
        console.log(response);
    },function(reason){
        console.log('Failed. ');
        console.log(reason.body)
    });
});

メモ

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

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

18
15
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
18
15