Chrome Extension+Google App Engine(+OAuth)

2013-08-18T00:00:00+00:00 Chrome Extension Google App Engine

http://blogs.dion.ne.jp/kotemaru/archives/10093611.html

を参考にすれば良い。でサーバー側はOAuthServiceクラスを使ってOAuth利用による通信であるかっていうのを検知するような方式を利用する

で問題はそれをどうやってChrome Extensionで行うかって所だと思いますけど、一応公式的にはchrome_ex_oauthっていうのを使って利用可能な模様

という事でやってみた

manifest.json

{
  "name": "test",
  "version": "0.1",
  "manifest_version": 2,
  "background": {
    "scripts": [
      "chrome_ex_oauth.js",
      "chrome_ex_oauthsimple.js",
      "const.js",
      "bg.js"
    ]
  },
  "permissions": ["https://*/*"]
}

const.jsはOAUTH_CONSUMER_KEY及びOAUTH_CONSUMER_SECRETなconstを定義しているだけなので省略する

bg.js

(function(undefined) {
  var oauth = ChromeExOAuth.initBackgroundPage({
    "request_url": "https://shareroid.appspot.com/_ah/OAuthGetRequestToken",
    "authorize_url": "https://shareroid.appspot.com/_ah/OAuthAuthorizeToken",
    "access_url": "https://shareroid.appspot.com/_ah/OAuthGetAccessToken",
    "consumer_key": OAUTH_CONSUMER_KEY,
    "consumer_secret": OAUTH_CONSUMER_SECRET,
    "app_name": "shareroid"
  });
  oauth.authorize(function() {
    oauth.sendSignedRequest(
      "https://shareroid.appspot.com/read",
      function() {
        console.log(arguments);
      },
      { "method": "GET" }
    );
  });
})();

でauthorize時に認証していない場合においてはchrome_ex_oauth.htmlがオープンされる

chrome_ex_oauth.html

<!DOCTYPE html>
<html>
  <head>
    <title>OAuth Redirect Page</title>
    <script type="text/javascript" src="js/chrome_ex_oauthsimple.js"></script>
    <script type="text/javascript" src="js/chrome_ex_oauth.js"></script>
    <script type="text/javascript" src="js/onload.js"></script>
  </head>
  <body>
  </body>
</html>

onload.jsでは

(function(undefined) {
  ChromeExOAuth.initCallbackPage();
})();

を行ってるだけ。で認証されてない場合には認証要求なページへリダイレクトされる。でその後にauthorizeな引数に指定したコールバックが作用する

っていう感じで使えばGoogle App EngineでOAuthServiceより保護されるアクション等をChrome Extensionからアクセスする事は可能な模様

余談

上記で呼ばれるchrome_ex_oauth.html自体はChromeExOAuthなインスタンスでcallback_pageなプロパティを設定する事で変える事自体は可能

ざっくりとindexedDBを使ってみる codemodelを使ってアノテーションプロセッサ利用によるJavaコードの生成