Quick Starts => Single Page App を選択する。フロントで実行する場合にはこのサンプルプロジェクトをみる。サーバーサイドで実行する場合には Regular Web App もしくは Backend/API を選択する。

React

React Sample Project へのリンク

Get Your Application Keys

以下二つが auth0 と通信する際に必要になるキー。設定画面からみれる。

  • Domain
  • Client ID

Configure Callback URLs

auth0 を使った認証後に、アプリケーション内でユーザーを遷移させる先の URL。

また以下の説明を読むに、Allowed Callback URLs field にも同じ URL を入れ許可する必要があるようだ。

The callback URL for your app must be whitelisted in the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.

Configure Logout URLs

ログアウトした時に飛ばすパス。 全部をここに書く必要あり。また上記と同様に、ホワイトリストにも追加が必要。

API 実行側からは returnTo で指定する模様。

Configure Allowed Web Origins

細かいことはよくわからなかったが、ここを入れて許可しないと動かないとのこと。

Create a Sample Application

Auth0 SDK を使うバージョンではないっぽい。@auth0/auth0-spa-js を使うやつとのこと。

Content provier で auth0 関係の機能を提供するラッパーを作る

providing functions that allow the user to log in, log out, and information such as whether the user is logged in.

Restoring Login State with Social Providers

わからん!!!

Users who are logged in with username/password will be silently reauthenticated automatically when the application reloads. No further action is needed for this type of login.

If you are using the classic Universal Login experience and would like users to authenticate using social identity providers (such as Google, Apple, Facebook, etc.), then you will need to configure those connections in your Auth0 Dashboard.

In the navigation menu, choose Connections - Social, and select the social connection you’d like to support. In the connection’s settings, click “How to obtain a Client ID?“ and follow the instructions to set up your own ID and secret.

If you are using the new Universal Login experience, the default enabled social connections will silently reauthenticate without additional configuration. However, you should still set up your own keys and avoid using default Auth0 development keys in a production app.

設定の方

以下二つに開発時のパス?である http://localhost:3000 を追加する。しないとログインボタン押した時にエラー画面が出る。

  • Allowed Callback URLs
  • Allowed Web Origins,
  • Allowed Logout URL => ログアウトした時に遷移する先。これをいれないと auth0側の適当なページに移動してしまう。

Auth0 Single Page App SDK

React 等を使って SPA を作る際に、auth0 を活用するためのライブラリ。

翻訳元:公式ドキュメント

Auth0 Single Page App SDK は、SPA において Auth0 を用いた認証/承認をおこなうための新しいライブラリです。このライブラリは高度に抽象化された API を提供し、それによって SPA においてセキュリティを強固にするために必要な細かい問題を処理してくれます。それでいて書くコードは少なくなります。

The Auth0 Single Page App SDK is a new JavaScript library for implementing authentication & authorization in single page apps (SPA) with Auth0. It provides a high-level API and handles a lot of the details so you can secure SPAs using best practices while writing less code.

Auth0 SDK は、以下のことを処理します。

  • grant and protocol details
  • token に期限切れとその更新
  • token を保持したりキャッシングする

これらの背後では Universal LoginAuthorization Code Grant Flow with PKCE が用いられています。

The Auth0 SPA SDK handles grant and protocol details, token expiration and renewal, as well as token storage and cacheing. Under the hood, it implements Universal Login and the Authorization Code Grant Flow with PKCE.

本ライブラリは GitHub 上でホスティングされており、ドキュメントはこちらで参照できます。

The library is hosted on GitHub and you can find the API documentation here.

auth0.js を SPA において使っていて Auth0 SPA に移行したい場合には、移行の記事を参照してください。

If you're planning on migrating a SPA that uses auth0.js to the Auth0 SPA SDK, check out Migrate from Auth0.js to the Auth0 Single Page App SDK for examples.

問題が起きた場合にはこちらのイシューも参考にしてください。

インストール

yarn add @auth0/auth0-spa-js

始める

クライアントを作成する。

Create the client

まずは Auth0Client から新しいクライアント用のオブジェクトを作成します。Auth0Client instance の作成は、あなたのアプリケーションがレンダリングや初期化を行う前に実行せねばいけません。async/await もしくは primise を用いることができます。一つ以上のインスタンスを作成しないようにしてください。

First, you'll need to create a new instance of Auth0Client client object. Create the Auth0Client instance before rendering or initializing your application. You can do this using either the async/await method, or with promises. You should only create one instance of the client.

auth0クライアントの作成
// either with async/await
const auth0 = await createAuth0Client({
  domain: 'YOUR_DOMAIN',
  client_id: 'YOUR_CLIENT_ID'
});

ログインしてユーザー情報を取得する

ユーザーがクリックしてログインを開始するためのボタンを作成しましょう。

Next, create a button users can click to start logging in.

ログインを開始するボタン
<button id="login">Click to Login</button>

このボタンに対するクリックイベントを listen します。イベントが発生したら、望むログインメソッドを使って user を認証します。(このサンプルでは loginWithPopup() メソッドを使いました)user が認証されたら、user情報を getUser() メソッドで取得することができます。

訳注: loginWithPopup() じゃなくて redirect の気がする。

Listen for click events on the button you created. When the event occurs, use the desired login method to authenticate the user (loginWithPopup() in this example). After the user is authenticated, you can retrieve the user profile with the getUser() method.

認証
// either with async/await
document.getElementById('login').addEventListener('click', async () => {
  await auth0.loginWithRedirect({
    redirect_uri: 'http://localhost:3000/'
  });
  //logged in. you can get the user profile like this:
  const user = await auth0.getUser();
  console.log(user);
});

API を呼ぶ

API を呼び出すために、まずは user Access Token を取得しましょう。そうしたら Access Token を API を呼び出すリクエスト内で用います。以下の例では getTokenSilently メソッドを用いて Access Token を読み出しています。

To call your API, start by getting the user's Access Token. Then use the Access Token in your request. In this example the getTokenSilently method is used to retrieve the Access Token.

APIを呼び出すためのボタン
<button id="callApi">Call an API</button>
authToken を取得しそれをもとに API をコールする
// either with async/await
document.getElementById('callApi').addEventListener('click', async () => {
  const accessToken = await auth0.getTokenSilently();
  const result = await fetch('https://exampleco.com/api', {
    method: 'GET',
    headers: {
      Authorization: 'Bearer ' + accessToken
    }
  });
  const data = await result.json();
  console.log(data);
});

ログアウトする

ログアウト
document.getElementById('logout').addEventListener('click', () => {
  auth0.logout();
});