はじめに
以前にウェブアプリから 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 アカウント認証の準備する
- 開発者の Google アカウントで Google Developer Console を開く
(https://console.cloud.google.com/) - プロジェクトを作成する
(https://console.developers.google.com/project) - 使用したい API を選択して有効にする
(https://console.developers.google.com/apis/library) - 認証情報を作成する
(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 のウェブサイトでクライアントライブラリを入手します。
<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 、スコープ を指定して、クライアントライブラリを初期化します。
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);
});
});
(後略)
ログインボタンを用意する
アプリの画面に、ログインするためのボタンを用意しましょう。
<button id="login">Login</button>
<p id="status">Not logged in.</p>
ログインするコードを追加する
ログインするコードを追加します。
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://localhost と http://127.0.0.1 は別になります。例えば OAuth クライアントの設定が http://localhost でウェブアプリを開くのに http://127.0.0.1 だとエラーになります。これに気づくのに手間取りました。
ウェブクライアントアプリで Google API 呼出する
Google API 呼出ボタンを用意する
アプリの画面に、Goolge API 呼出するためのボタンを用意しましょう。
<button id="request">Call API</button>
<p id="result"></p>
Google API を呼出するコードを追加する
認証されたクライアントオブジェクトで Google API が呼出できます。
呼出するためのエンドポイント(URI)はリファレンスを参照します。
今回は Google Drive を操作します。API Reference | Drive REST API | Google Developers
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)になりました。ログイン認証するときに指定するスコープが適切でないと発生します。