シングルページアプリ用Auth0 React SDK
Auth0 React SDK(auth0-react.js)は、Auth0を使用してReactアプリケーションで認証と認可を実装するためのJavaScriptライブラリです。カスタムReactフックとその他の高階コンポーネントを提供し、ベストプラクティスに従ってReactアプリをセキュリティ保護しながら、同時にコードの量を減らすことができます。
Auth0 React SDKは、付与とプロトコルの詳細、トークンの失効と更新、そして、トークンの保管とキャッシュをも処理します。内部では、ユニバーサルログインとPKCEを用いた認可コード付与フローを実装しています。
ライブラリはGitHubで提供しており、APIに関するさらなる詳細を読むことができます。
インストール
プロジェクトでauth0-react.jsを使用するには、いくつかのオプションがあります。
開始
まず、アプリケーションを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-router、Gatsby、および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?