愛と勇気と缶ビール

ふしぎとぼくらはなにをしたらよいか

Google accountでAuthenticationかましつつAuthorizationもかましたい場合

ハーイ。今日のお兄さんは優しくないので、タイトルの2つを混同してるやつ死刑ね。

Google Accounts Authentication and Authorization — Google Developers

とか

Using OAuth 2.0 for Login (OpenID Connect) - Google Accounts Authentication and Authorization — Google Developers

とかを見てると、「例えばJavaScriptからAPI叩きつつ、裏側でGoogle+ Platform — Google Developers使ってユーザ認証もしておきたい場合はどげんしたらいいの?どれをどう使えばいいの?一体どっちなの?」という疑問に捉われる。

正解はgoogle plus loginの方を使いつつ、gapi.client相当も読み込んでおいて

    <script type="text/javascript">
      (function() {
        var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
        po.src = 'https://apis.google.com/js/client:plusone.js?onload=onLoadCallback';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
      })();
    </script>

API叩く用のscopeも指定しつつAuthorization Request送って(以下はGoogle+ sign-in buttonを使う場合)

    <span id="sign-in">
        <span
            class="g-signin"
            data-callback="signinCallback"
            data-clientid="[YOUR CLIENT ID]"
            data-cookiepolicy="single_host_origin"
            data-scope="openid https://www.googleapis.com/auth/calendar.readonly"
        >
        </span>
    </span>

後は普通にJSからAPIを叩けばオケー。これ以降のユーザ認証についてはドキュメントに書いてある通りなので省略。

        function signinCallback(authResult) {
            console.log(authResult);
            if ( authResult.status.signed_in ) {
                gapi.client.load("calendar", "v3", processCalendar);
            }
            else {
                document.getElementById("sign-in").style.cssText += "display:inline;";
            }
        }

        function processCalendar() {
            gapi.client.calendar.calendarList.list().execute(function(res) {
                console.log(res);
            });
        }