1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Auth0チュートリアルをReactで

Last updated at Posted at 2023-02-02

Windows 11で

ネタ元

  1. https://zenn.dev/mikakane/articles/react_auth0_tutorial
  2. https://auth0.com/docs/quickstart/spa/react/interactive

事前準備

  1. Nodeインストール - https://nodejs.org/ja/download/

アカウント及びテナント作成&アプリケーション設定

  1. https://auth0.com/jp で[無料トライアル]から登録&テナント作成&アプリケーション設定
    1. Account Typeはother
    2. I need advanced settingsをチェック
    3. Tenant domainは適当に
    4. RegionはJapan
  2. 作成されたテナントのダッシュボードが表示される
  3. 左メニューのApplicationsのApplicationsに進む
  4. Default Appが作成済になっているのでDefault Appの中に入り、Settingsタブを開く
  5. Basic InformationのDomain・Client IDの値をメモっておく ★1
  6. Application PropertiesのApplication TypeをSingle Page Applicationに変える
    1. これにより次項目のToken Endpoint Authentication MethodがNoneに固定される、こうなっていないと後でユーザー情報が表示されない (Auth0のログには「Unauthorized」と出ていたかも)
  7. Application URIsのAllowed Callback URLs・Allowed Logout URLs・Allowed Web Originsにhttp://localhost:3000/を記入する
  8. [Save Changes]を押下

アプリ作成

  1. コマンドプロンプト起動
  2. npx create-react-app my-react-auth0-sampleapp
  3. cd my-react-auth0-sampleapp
  4. npm install @auth0/auth0-react
  5. src\index.js書き換え
    src\index.js
    import { createRoot } from 'react-dom/client';
    import { Auth0Provider } from '@auth0/auth0-react';
    import App from './App';
    
    createRoot(document.getElementById("root")).render(
      <Auth0Provider
        domain="★1より"
        clientId="★1より"
        authorizationParams={{
          redirect_uri: window.location.origin
        }}
      >
        <App />
      </Auth0Provider>
    );
    
    1. redirect_uriがredirectUriとかになっているとAuth0がエラー画面を表示する (ログには「Unable to issue redirect for OAuth 2.0 transaction」と出ていたかも)
  6. src\App.js書き換え
    src\App.js
    import logo from './logo.svg';
    import './App.css';
    import LoginButton from './login';
    import LogoutButton from './logout';
    import Profile from './profile';
    
    function App() {
      return (
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <p>
              Edit <code>src/App.js</code> and save to reload.
            </p>
            <a
              className="App-link"
              href="https://reactjs.org"
              target="_blank"
              rel="noopener noreferrer"
            >
              Learn React
            </a>
            <LoginButton></LoginButton>
            <LogoutButton></LogoutButton>
            <Profile></Profile>
          </header>
        </div>
      );
    }
    
    export default App;
    
  7. src/login.js作成
    src/login.js
    import { useAuth0 } from '@auth0/auth0-react';
    
    const LoginButton = () => {
        const { loginWithRedirect } = useAuth0();
        return <button onClick={() => loginWithRedirect()}>Log In</button>;
    };
    
    export default LoginButton;
    
  8. src/logout.js作成
    src/logout.js
    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;
    
  9. src/profile.js作成
    src/profile.js
    import { useAuth0 } from '@auth0/auth0-react';
    
    const Profile = () => {
        const { user, isAuthenticated, isLoading } = useAuth0();
    
        if (isLoading) {
            return <div>Loading ...</div>;
        }
    
        return (
            isAuthenticated && (
                <div>
                    <img src={user.picture} alt={user.name} />
                    <h2>{user.name}</h2>
                    <p>{user.email}</p>
                </div>
            )
        );
    };
    
    export default Profile;
    

実行

  1. npm start
    1. しばらくたつとブラウザが起動して http://localhost:3000 にアクセスする
  2. [Log In]押下でAuth0のログイン画面に飛ぶのでそこからユーザー登録する
  3. 別ブラウザで http://localhost:3000 を開き、[Log In]押下でログインしてユーザー情報が表示されることを確認
  4. [Log Out]押下でログアウトしてユーザー情報が表示されなくなることを確認

Auth0ダッシュボード

  1. User ManagementのUsersから登録ユーザーを確認できる
  2. MonitoringのLogsからログを確認できる
  3. SettingsのGeneralタブのLanguagesからデフォルト言語を日本語とかに変更できる
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?