LoginSignup
8
6

More than 5 years have passed since last update.

ブラウザからGoogle OAuthの認証をやってみる

Last updated at Posted at 2017-08-27

create react appのおかげで、reactを使ってサンプルアプリを作るのが楽になりました。そのおかげで、GoogleのOAuth認証もReactで気軽に試せるようになりました。

今回はGoogleのOAuth(OpenID Connect)を使ってJWTTokenを取得するまでの手順のメモです。

インストールとセットアップ

create-react-appでサプリケーションを作って、hellojsをインストールします。hellojsはOAuthによる認証用のライブラリです。

create-react-app oauthsample
cd oauthsample
npm install hellojs

Googleのサーバ設定

Googleの管理コンソールの認証情報から「認証情報を作成」ボタンを押して、「OAuthクライアントID」を選択します。アプリケーションの種類で「ウェブアプリケーション」を選択して、名前を適当に設定します。「承認済みリダレクトURI」でhttp://localhost:3000/ を指定します。今回はlocalhostからしかアクセスしないので。

これで保存するとclient idとsecret keyが取得できます。それらをあとで利用します。

auth serverの設定

hellojsはAuth Serverを認証用のプロキシとしてこっそり使っているようです。この辺を使うのいろいろ言うところもありそうな気がします。とりあえずは気にしないでおきます。サイトにアクセスしてsign iAnします。適当なIDプロバイダを設定すると、サインアップとログインができます。素敵な世界です。

Manage appsでdomainにlocalhost、client_idとclient_secretをそれぞれGoogleのサーバ設定で取得したもののを設定して保存します。

Auth Serverは自前で立てることもできます。oauth shimを利用します。

ブラウザで認証

App.jsを編集してきます。まずはなにはともあれ、hellojsをインポートします。

import hello from 'hellojs';

componentDidMountでhellojsを初期化します。すでに認証済みの場合は、getAuthResponse()した時に認証情報も取得できます。optionのscopeでopenid emailを設定しないと、JWTの中にemailの情報がセットされません。
hello.onでログインが成功した場合のイベントを設定します。

  componentDidMount() {
    hello.init({
      google: 'クライアントID'
    }, {
      scope: 'openid email',
      redirect_uri:  window.location.href
    })
    let authResponse = hello("google").getAuthResponse()
    if (authResponse) {
      console.log(authResponse)
    }

    hello.on('auth.login', this.getAuth.bind(this))
  }

getAuthの中身はこんな感じ。auth.authResponseのid_tokenでJWTTokenが取得できます。

  getAuth(auth) {
    console.log(auth.authResponse.id_token)
  }

ログインボタンを押した時の処理がこれ。見ればわかります。

  triggerLogin() {
    hello('google').login({
      response_type: 'code'
    })
  }

最後にhtmlの中にボタンを作っておきましょう

<button onClick={this.triggerLogin.bind(this)}>Sign-In with Google</button>

おしまい

これでJWTTokenが取れました。tokenのレフレッシュはこれ?

tokenが取れたのであとは、web appと通信する時にヘッダーのどこかにtokenをのせてやり取りするだけです。サーバ側はtokenをベリファイする必要があります。ベリファイの仕方はそのうち。

8
6
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
8
6