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

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

Auth0 React SDKは、付与とプロトコルの詳細、トークンの失効と更新、そして、トークンの保管とキャッシュをも処理します。内部では、ユニバーサルログインPKCEを用いた認可コード付与フローを実装しています。

ライブラリはGitHubで提供しておりAPIに関するさらなる詳細を読むことができます

インストール

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

  • npmから:

    npm install @auth0/auth0-react

  • yarnから: yarn add @auth0/auth0-react

開始

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

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')
 );

Was this helpful?

/

isLoadingとerror

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

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;

Was this helpful?

/

ログイン

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

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;

Was this helpful?

/

ログアウト

logoutを使用して、ユーザーをログアウトさせます。Auth0 Dashboardの「Allowed Logout URLs(許可されているログアウトURL)」にreturnToが指定されていることを確認してください。

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;

Was this helpful?

/

[User(ユーザー)]

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

import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';

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

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

export default Profile;

Was this helpful?

/

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

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

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

Was this helpful?

/

ルートを保護する

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

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>)
});

Was this helpful?

/

 カスタムルーターを使用している場合、Auth0ProviderにカスタムのonRedirectCallbackメソッドを提供して、ユーザーを保護されたページに戻すアクションを実行する必要があります。react-routerGatsby、およびNext.jsの例を参照してください。

APIを呼び出す

アクセストークンを使用して保護されたAPIを呼び出すには、Auth0ProviderまたはgetAccessTokenSilentlyのいずれかで、必ずアクセストークンaudienceおよびscopeを指定してください。その後、これを要求のAuthorizationヘッダーに渡して、保護されたAPIを呼び出します。

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;

Was this helpful?

/