@a-type/auth0-react 中文文档教程

发布于 4年前 浏览 32 项目主页 更新于 3年前

@a-type/auth0-react

用于 React 单页应用程序 (SPA) 的 Auth0 SDK。

CircleCI许可证npmcodecov

Table of Contents

Documentation

Installation

使用 npm

npm install @a-type/auth0-react

使用 yarn

yarn add @a-type/auth0-react

Getting Started

通过在 Auth0Provider 中包装您的应用程序来配置 SDK:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Auth0Provider } from '@a-type/auth0-react';
import App from './App';

ReactDOM.render(
  <Auth0Provider
    domain="YOUR_AUTH0_DOMAIN"
    clientId="YOUR_AUTH0_CLIENT_ID"
    redirectUri={window.location.origin}
  >
    <App />
  </Auth0Provider>,
  document.getElementById('app')
);

在您的组件中使用 useAuth0 挂钩来访问身份验证状态(isLoading< /code>、isAuthenticateduser)和身份验证方法(loginWithRedirectlogout):

// src/App.js
import React from 'react';
import { useAuth0 } from '@a-type/auth0-react';

function App() {
  const {
    isLoading,
    isAuthenticated,
    error,
    user,
    loginWithRedirect,
    logout,
  } = useAuth0();

  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return <div>Oops... {error.message}</div>;
  }

  if (isAuthenticated) {
    return (
      <div>
        Hello {user.name}{' '}
        <button onClick={() => logout({ returnTo: window.location.origin })}>
          Log out
        </button>
      </div>
    );
  } else {
    return <button onClick={loginWithRedirect}>Log in</button>;
  }
}

export default App;

Use with a Class Component

使用 withAuth0 高阶组件将 auth0 属性添加到类组件:

import React, { Component } from 'react';
import { withAuth0 } from '@a-type/auth0-react';

class Profile extends Component {
  render() {
    // `this.props.auth0` has all the same properties as the `useAuth0` hook
    const { user } = this.props.auth0;
    return <div>Hello {user.name}</div>;
  }
}

export default withAuth0(Profile);

Protect a Route

使用 withAuthenticationRequired 高阶组件保护路由组件。 未经身份验证访问此路由会将用户重定向到登录页面,并在登录后返回此页面:

import React from 'react';
import { withAuthenticationRequired } from '@a-type/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 方法来执行将用户返回到受保护页面的操作。 查看示例 反应路由器GatsbyNext.js

Call an API

使用访问令牌调用受保护的 API:

import React, { useEffect, useState } from 'react';
import { useAuth0 } from '@a-type/auth0-react';

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

  useEffect(() => {
    (async () => {
      try {
        const token = await getAccessTokenSilently({
          audience: 'https://api.example.com/',
          scope: 'read:posts',
        });
        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;

有关更详细的示例,请参阅如何 创建一个 useApi 挂钩,用于使用访问令牌访问受保护的 API

Contributing

我们感谢对此回购的反馈和贡献! 在开始之前,请参阅以下内容:

Support + Feedback

如需支持或提供反馈,请在我们的问题跟踪器上提出问题< /a>。

Troubleshooting

有关如何解决常见问题的信息,请查看疑难解答指南

Frequently Asked Questions

如需了解您在使用 SDK 时可能遇到的常见问题,请查看常见问题解答

Vulnerability Reporting

请不要在公共 GitHub 问题跟踪器上报告安全漏洞。  负责任的披露计划 详细说明了披露安全问题的程序。

What is Auth0?

Auth0 可帮助您轻松地:

  • Implement authentication with multiple identity providers, including social (e.g., Google, Facebook, Microsoft, LinkedIn, GitHub, Twitter, etc), or enterprise (e.g., Windows Azure AD, Google Apps, Active Directory, ADFS, SAML, etc.)
  • Log in users with username/password databases, passwordless, or multi-factor authentication
  • Link multiple user accounts together
  • Generate signed JSON Web Tokens to authorize your API calls and flow the user identity securely
  • Access demographics and analytics detailing how, when, and where users are logging in
  • Enrich user profiles from other data sources using customizable JavaScript rules

为什么选择 Auth0?

License

该项目已获得 MIT 许可。 有关详细信息,请参阅 LICENSE 文件。

@a-type/auth0-react

Auth0 SDK for React Single Page Applications (SPA).

CircleCILicensenpmcodecov

Table of Contents

Documentation

Installation

Using npm

npm install @a-type/auth0-react

Using yarn

yarn add @a-type/auth0-react

Getting Started

Configure the SDK by wrapping your application in Auth0Provider:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Auth0Provider } from '@a-type/auth0-react';
import App from './App';

ReactDOM.render(
  <Auth0Provider
    domain="YOUR_AUTH0_DOMAIN"
    clientId="YOUR_AUTH0_CLIENT_ID"
    redirectUri={window.location.origin}
  >
    <App />
  </Auth0Provider>,
  document.getElementById('app')
);

Use the useAuth0 hook in your components to access authentication state (isLoading, isAuthenticated and user) and authentication methods (loginWithRedirect and logout):

// src/App.js
import React from 'react';
import { useAuth0 } from '@a-type/auth0-react';

function App() {
  const {
    isLoading,
    isAuthenticated,
    error,
    user,
    loginWithRedirect,
    logout,
  } = useAuth0();

  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (error) {
    return <div>Oops... {error.message}</div>;
  }

  if (isAuthenticated) {
    return (
      <div>
        Hello {user.name}{' '}
        <button onClick={() => logout({ returnTo: window.location.origin })}>
          Log out
        </button>
      </div>
    );
  } else {
    return <button onClick={loginWithRedirect}>Log in</button>;
  }
}

export default App;

Use with a Class Component

Use the withAuth0 higher order component to add the auth0 property to Class components:

import React, { Component } from 'react';
import { withAuth0 } from '@a-type/auth0-react';

class Profile extends Component {
  render() {
    // `this.props.auth0` has all the same properties as the `useAuth0` hook
    const { user } = this.props.auth0;
    return <div>Hello {user.name}</div>;
  }
}

export default withAuth0(Profile);

Protect a Route

Protect a route component using the withAuthenticationRequired higher order component. Visits to this route when unauthenticated will redirect the user to the login page and back to this page after login:

import React from 'react';
import { withAuthenticationRequired } from '@a-type/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>,
});

Note If you are using a custom router, you will need to supply the Auth0Provider with a custom onRedirectCallback method to perform the action that returns the user to the protected page. See examples for react-router, Gatsby and Next.js.

Call an API

Call a protected API with an Access Token:

import React, { useEffect, useState } from 'react';
import { useAuth0 } from '@a-type/auth0-react';

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

  useEffect(() => {
    (async () => {
      try {
        const token = await getAccessTokenSilently({
          audience: 'https://api.example.com/',
          scope: 'read:posts',
        });
        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;

For a more detailed example see how to create a useApi hook for accessing protected APIs with an access token.

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Support + Feedback

For support or to provide feedback, please raise an issue on our issue tracker.

Troubleshooting

For information on how to solve common problems, check out the Troubleshooting guide

Frequently Asked Questions

For a rundown of common issues you might encounter when using the SDK, please check out the FAQ.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

Auth0 helps you to easily:

  • Implement authentication with multiple identity providers, including social (e.g., Google, Facebook, Microsoft, LinkedIn, GitHub, Twitter, etc), or enterprise (e.g., Windows Azure AD, Google Apps, Active Directory, ADFS, SAML, etc.)
  • Log in users with username/password databases, passwordless, or multi-factor authentication
  • Link multiple user accounts together
  • Generate signed JSON Web Tokens to authorize your API calls and flow the user identity securely
  • Access demographics and analytics detailing how, when, and where users are logging in
  • Enrich user profiles from other data sources using customizable JavaScript rules

Why Auth0?

License

This project is licensed under the MIT license. See the LICENSE file for more info.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文