LoginSignup
22
21

More than 5 years have passed since last update.

chrome.identity を使ってChrome拡張でもOAuthのAPIを使う

Last updated at Posted at 2018-04-22

例としてQiitaのAPIを使う。

まずはOAuthのリダイレクト先のURLの項目をhttps://{拡張機能のID}.chromiumapp.orgで登録しておく。
IDは拡張機能の画面で確認することができる。

extension.png

extension_qiita.png

次にOAuthの認可画面を表示するコードを書く。

chrome.launchWebAuthFlow({
  url: `https://qiita.com/api/v2/oauth/authorize?client_id=${clientId}&scopes=read_qiita&state=${適当な文字列}`,
  interactive: true
}, responseUrl => {
  // 後述
})

chrome.launchWebAuthFlowでユーザーを認可用のページにアクセスさせることができる。

interactivetrueにするとユーザーから認可を取得していない場合は認可用のページを表示、取得済みの場合はなにもせずコールバックを呼ぶという処理になる。

次にコールバック内の処理。

chrome.identity.launchWebAuthFlow({
  // 省略
}, responseUrl => {
  let url = new URL(responseUrl)
  let code = url.searchParams.get("code")

  fetch("https://qiita.com/api/v2/access_tokens", {
    method: "post",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      client_id: clientId,
      client_secret: clientSecret,
      code: code
    })
  }).then(res => res.json())
    .then(json => {
      let token = json["token"] // アクセストークン取得
    })
})

responseURLのGETパラメーターにcodeが入っている。

それをアクセストークン取得のAPIにClientIdとClientSecretと一緒に送るとアクセストークンが取得できる。

22
21
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
22
21