> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev-docs-event-stream-action-templates.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# シングルページアプリ用Auth0 React SDK

> Reactシングルページアプリ用Auth0 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) + "*****MASKED*****";
          }
          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は、付与とプロトコルの詳細、トークンの失効と更新、そして、トークンの保管とキャッシュをも処理します。内部では、[ユニバーサルログイン](/docs/ja-jp/authenticate/login/auth0-universal-login)と[PKCEを用いた認可コード付与フロー](/docs/ja-jp/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/)。

## インストール

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

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

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

## 開始

まず、アプリケーションを1つの`Auth0Provider`コンポーネントでラップする必要があります。これにより、アプリケーションの内部に配置されたコンポーネントにReactのコンテキストが提供されます。

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="javascript" />

## isLoadingとerror

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

```javascript 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;
```

## ログイン

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

```javascript 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;
```

## ログアウト

`logout`を使用して、ユーザーをログアウトさせます。<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=auth0-dashboard" tip="Auth0 Dashboard: サービスを構成するためのAuth0の主製品。" cta="用語集の表示">Auth0 Dashboard</Tooltip>の「Allowed Logout URLs（許可されているログアウトURL）」に`returnTo`が指定されていることを確認してください。

```javascript 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;
```

## ［User（ユーザー）］

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

```javascript 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;
```

## クラスコンポーネントと併用する

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

```javascript 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);
```

## ルートを保護する

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

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

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

export default withAuthenticationRequired(PrivateRoute, {
  // Show a message while the user waits to be redirected to the login page.
  onRedirecting: () => (<div>Redirecting you to the login page...</div>)
});
```

**注** カスタムルーターを使用している場合、`Auth0Provider`にカスタムの`onRedirectCallback`メソッドを提供して、ユーザーを保護されたページに戻すアクションを実行する必要があります。[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)の例を参照してください。

## APIを呼び出す

アクセストークンを使用して保護されたAPIを呼び出すには、`Auth0Provider`または`getAccessTokenSilently`のいずれかで、必ず[アクセストークン](/docs/ja-jp/secure/tokens/access-tokens/get-access-tokens)の`audience`および`scope`を指定してください。その後、これを要求の`Authorization`ヘッダーに渡して、保護されたAPIを呼び出します。

```javascript lines 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', // Scope that exists for the API being called. You can create these through the Auth0 Management API or through the Auth0 Dashboard in the Permissions view of your API.
          }
        });
        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;
```
