> ## Documentation Index
> Fetch the complete documentation index at: https://translations.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> React シングルページアプリケーション向け Auth0 SDK の説明

# シングルページアプリケーション向け Auth0 React SDK

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****マスク済み*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

Auth0 React SDK (auth0-react.js) は、Auth0 を使用して React アプリに認証と認可を実装するための JavaScript ライブラリです。カスタム React フックやその他の 高階コンポーネント を提供しており、ベストプラクティスに従って React アプリを保護しながら、コード量を減らせます。

Auth0 React SDK は、グラントやプロトコルの詳細、トークンの有効期限と更新、トークンの保存とキャッシュを処理します。内部では、[Universal Login](/ja/docs/authenticate/login/auth0-universal-login) と [PKCE を使用する認可コードグラントフロー](/ja/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce) を実装しています。

このライブラリは [GitHub で公開](https://github.com/auth0/auth0-react) されており、[API の詳細](https://auth0.github.io/auth0-react/) を確認できます。

<div id="installation">
  ## インストール
</div>

プロジェクトで auth0-react.js を使用するには、いくつかの選択肢があります。

* [npm](https://npmjs.org/) から:

  `npm install @auth0/auth0-react`
* [yarn](https://yarnpkg.com/) から:
  `yarn add @auth0/auth0-react`

<div id="getting-started">
  ## はじめに
</div>

まず、アプリケーション全体を 1 つの `Auth0Provider` コンポーネントでラップする必要があります。これにより、アプリケーション内のコンポーネントで React Context を利用できるようになります。

export const codeExample = `import React from 'react';
    import ReactDOM from 'react-dom';
    import { Auth0Provider } from '@auth0/auth0-react';
    import App from './App';
    ReactDOM.render(
      <Auth0Provider
        domain="{yourDomain}"
        clientId="{yourClientId}"
        authorizationParams={{
          redirect_uri: window.location.origin
        }}
    >
      <App />
    </Auth0Provider>,
    document.getElementById('app')
 );`;

<AuthCodeBlock children={codeExample} language="js" />

<div id="isloading-and-error">
  ## isLoading と error
</div>

SDK の初期化が完了するまで待機し、`isLoading` と `error` の状態を使ってエラーを処理します。

```js lines theme={null}
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';
function Wrapper({ children }) {
  const {
    isLoading,
    error,
  } = useAuth0();
  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return <div>Oops... {error.message}</div>;
  }
  return <>{children}</>;
}
export default Wrapper;
```

<div id="login">
  ## ログイン
</div>

`loginWithRedirect` または `loginWithPopup` を使用して、ユーザーをログインさせます。

```js lines theme={null}
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';

function LoginButton() {
  const {
    isAuthenticated,
    loginWithRedirect,
  } = useAuth0();

  return !isAuthenticated && (
    <button onClick={loginWithRedirect}>Log in</button>
  );
}

export default LoginButton;
```

<div id="logout">
  ## ログアウト
</div>

ユーザーをログアウトするには、`logout` を使用します。<Tooltip tip="Auth0 Dashboard: サービスを設定するための Auth0 の主要製品です。" cta="用語集を表示" href="/ja/docs/glossary?term=Auth0+Dashboard">Auth0 Dashboard</Tooltip> の「Allowed Logout URLs」に `returnTo` が指定されていることを確認してください。

```js lines theme={null}
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';

function LogoutButton() {
  const {
    isAuthenticated,
    logout,
  } = useAuth0();

  return isAuthenticated && (
    <button onClick={() => {
      logout({ 
        logoutParams: {
          returnTo: window.location.origin
        }
      });
    }}>Log out</button>
  );
}

export default LogoutButton;
```

<div id="user">
  ## ユーザー
</div>

`user` の値を使用して、ユーザープロフィール情報にアクセスできます。

```js lines theme={null}
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';

function Profile() {
  const { user } = useAuth0();

  return <div>Hello {user.name}</div>;
}

export default Profile;
```

<div id="use-with-a-class-component">
  ## クラスコンポーネントで使用する
</div>

フックを使用する代わりに、`withAuth0` 高階コンポーネント を使用して、クラスコンポーネントに `auth0` プロパティを追加します。

```jsx lines theme={null}
import React, { Component } from 'react';
import { withAuth0 } from '@auth0/auth0-react';

class Profile extends Component {
  render() {
    const { user } = this.props.auth0;
    return <div>Hello {user.name}</div>;
  }
}

export default withAuth0(Profile);
```

<div id="protect-a-route">
  ## ルートを保護する
</div>

`withAuthenticationRequired` 高階コンポーネントを使用して、ルートコンポーネントを保護します。未認証の状態でこのルートにアクセスすると、ユーザーはログインページにリダイレクトされ、ログイン後にこのページに戻ります。

```js lines theme={null}
import React from 'react';
import { withAuthenticationRequired } from '@auth0/auth0-react';

const PrivateRoute = () => (<div>Private</div>);

export default withAuthenticationRequired(PrivateRoute, {
  // ユーザーがログインページにリダイレクトされるのを待つ間、メッセージを表示します。
  onRedirecting: () => (<div>Redirecting you to the login page...</div>)
});
```

**注** カスタムルーターを使用している場合は、ユーザーを保護されたページに戻す処理を行うために、カスタムの `onRedirectCallback` メソッドを `Auth0Provider` に渡す必要があります。例については、[react-router](https://github.com/auth0/auth0-react/blob/master/EXAMPLES.md#1-protecting-a-route-in-a-react-router-dom-app)、[Gatsby](https://github.com/auth0/auth0-react/blob/master/EXAMPLES.md#2-protecting-a-route-in-a-gatsby-app)、[Next.js](https://github.com/auth0/auth0-react/blob/master/EXAMPLES.md#3-protecting-a-route-in-a-nextjs-app-in-spa-mode) を参照してください。

<div id="call-an-api">
  ## API を呼び出す
</div>

保護された API を <Tooltip tip="アクセストークン: API へのアクセスに使用する認可資格情報で、不透明な文字列または JWT の形式を取ります。" cta="用語集を表示" href="/ja/docs/glossary?term=Access+Token">アクセストークン</Tooltip> で呼び出すには、`Auth0Provider` または `getAccessTokenSilently` で [アクセストークン](/ja/docs/secure/tokens/access-tokens/get-access-tokens) の `audience` と `scope` を必ず指定してください。続いて、そのトークンをリクエストの `Authorization` ヘッダーに渡して、保護された API を呼び出します。

```jsx lines expandable theme={null}
import React, { useEffect, useState } from 'react';
import { useAuth0 } from '@auth0/auth0-react';

const Posts = () => {
  const { getAccessTokenSilently } = useAuth0();
  const [posts, setPosts] = useState(null);

  useEffect(() => {
    (async () => {
      try {
        const token = await getAccessTokenSilently({
          authorizationParams: {
            audience: 'https://api.example.com/', // Value in Identifier field for the API being called.
            scope: 'read:posts', // 呼び出すAPIに存在するスコープ。Auth0 Management APIまたはAuth0 DashboardのAPIのPermissionsビューから作成できます。
          }
        });
        const response = await fetch('https://api.example.com/posts', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        setPosts(await response.json());
      } catch (e) {
        console.error(e);
      }
    })();
  }, [getAccessTokenSilently]);

  if (!posts) {
    return <div>Loading...</div>;
  }

  return (
    <ul>
      {posts.map((post, index) => {
        return <li key={index}>{post}</li>;
      })}
    </ul>
  );
};

export default Posts;
```
