ReactにAuth0を導入する方法について説明します。
Auth0とは
Auth0は認証・認可のサービスです。以下のような特徴を持っています。
- ユーザー認証の構築が簡単
認証機能の実装を簡単かつ高速に行うことができ、認証機能の設定や管理を自分で行う必要がなくなります。 - 多様な認証プロバイダに対応
Google、Facebook、Twitter、GitHubなど、一般的な認証プロバイダに加え、企業向けのActive DirectoryやLDAPなどにも対応しています。 - セキュリティに優れている
2要素認証やSingle Sign-On(SSO)など、セキュリティに関する機能を多数提供しています。 - マルチテナント機能が備わっている
複数のクライアントを一元管理することができます。各クライアントごとに異なる認証設定を行うことができるため、複数のアプリケーションを開発する場合にも効率的に管理することができます。
前提条件
- Node.jsとnpmがインストールされていること。
- Reactの基本的な知識があること。
手順
- Auth0 アカウントの作成
Auth0のサインアップページ( https://auth0.com/signup ) にアクセスし、必要な情報を入力して、アカウントを作成します。 - React アプリの作成
Reactアプリを作成します。ここでは、create-react-appを使用します。
1 2 |
npx create-react-app my-app cd my-app |
- Auth0 SDK のインストール
Auth0 SDKとしてauth0-jsパッケージを使用しますので、npmでインストールします。
1 |
npm install auth0-js |
- Auth0 アプリケーションの作成
Auth0のダッシュボードで、新しいアプリケーションを作成します。テナントを作成
ダッシュボード(https://manage.auth0.com/dashboard )でテナントを作成します。
アプリケーションを作成
サイドバーの「Applications」からアプリケーションを作成します。「Application Type」は
Single Web Page Application
を選択します。
Domain, Client IDを作成
後ほどReactアプリケーションで使用するDomainとClient IDを確認します。
Redirect URIsを設定
Auth0でログイン後やログアウト後にリダイレクトするURLを設定する必要があるので、以下のようにします。
- Callback URLs : http://localhost:3000
- Logout URLs : http://localhost:3000
- Allowed Web Origins : http://localhost:3000 - React アプリに Auth0 を統合
Auth0 SDKを初期化
src/index.jsファイルで、次のようにアプリケーションにAuth0のプロバイダーを適用します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { Auth0Provider } from '@auth0/auth0-react'; const root = ReactDOM.createRoot(document.getElementById('root')); const domain="test-react-app.jp.auth0.com" const clientId="alZnc2kN0H45XP37pE6pxFVio0as7cTj" root.render( <Auth0Provider domain={domain} clientId={clientId} authorizationParams={{ redirect_uri: window.location.origin }} > <App /> </Auth0Provider> ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); |
ログインボタンを作成
ログインボタンをsrc/components/loginButton.jsに作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; const LogoutButton = () => { const { logout } = useAuth0(); return ( <button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}> Log Out </button> ); }; export default LogoutButton; |
ログアウトボタンを作成
ログアウトボタンをsrc/components/logoutButton.jsに作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; const LogoutButton = () => { const { logout } = useAuth0(); return ( <button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}> Log Out </button> ); }; export default LogoutButton; |
プロフィール情報を作成
ログインしたユーザのプロフィール情報をsrc/components/profile.jsに作成します。
useAuth0
フックのuser
により認証されたユーザ情報を取得できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; const Profile = () => { const { user } = useAuth0(); return ( <div> <img src={user.picture} alt={user.name} /> <h2>{user.name}</h2> <p>{user.email}</p> </div> ); }; export default Profile; |
App.jsを編集
未ログイン時はログインボタンを表示して、ログイン時はログアウトボタンとプロフィール情報を表示するようにsrc/App.jsを編集します。
isAuthenticated
によって現在認証されているかどうかが返却されます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import './App.css'; import LoginButton from './components/loginButton'; import LogoutButton from './components/logoutButton'; import { useAuth0 } from "@auth0/auth0-react"; import Profile from './components/profile'; function App() { const { isAuthenticated } = useAuth0() return ( <div className="App"> { isAuthenticated ? ( <div> <LogoutButton /> <Profile /> </div> ) : <LoginButton /> } </div> ); } export default App; |
動作テスト
npm start
を実行しhttp://localhost:3000 にアクセスします。
1 |
npm start |
Auth0のダッシュボードのサイドバーの「User Management」の「Users」に認証済みのユーザ一覧が表示されるので確認します。
まとめ
この記事では、ReactにAuth0を導入する方法について紹介しました。
ReactにAuth0を導入することにより、認証機能を簡単に実装でき、セキュリティにも配慮したアプリケーションを開発することができます。是非、本記事を参考にして、ReactアプリにAuth0を導入してみてください。
参考
Auth0 公式ドキュメント(https://auth0.com/docs)
Auth0 React QuickStart(https://auth0.com/docs/quickstart/spa/react/01-login)