JSPM

@authok/authok-react

1.9.3
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 3
  • Score
    100M100P100Q33729F
  • License MIT

Authok SDK for React Single Page Applications (SPA)

Package Exports

  • @authok/authok-react
  • @authok/authok-react/dist/authok-react.cjs.js
  • @authok/authok-react/dist/authok-react.esm.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@authok/authok-react) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@authok/authok-react

用于React单页应用程序(SPA)的 Authok SDK.

CircleCI License npm codecov

目录

文档

安装

使用 npm

npm install @authok/authok-react

使用 yarn

yarn add @authok/authok-react

开始

把你的应用包含在 AuthokProvider 中:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { AuthokProvider } from '@authok/authok-react';
import App from './App';

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

在组件中使用 useAuthok hook 来访问认证状态 (isLoading, isAuthenticateduser) 和 认证方法 (loginWithRedirectlogout):

// src/App.js
import React from 'react';
import { useAuthok } from '@authok/authok-react';

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

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

  if (isAuthenticated) {
    return (
      <div>
        你好 {user.name}{' '}
        <button onClick={() => logout({ return_to: window.location.origin })}>
          退登
        </button>
      </div>
    );
  } else {
    return <button onClick={loginWithRedirect}>登录</button>;
  }
}

export default App;

如果你使用 TypeScript, 你可以传递类型参数给到 useAuthok 来指定 user 的类型:

const { user } = useAuthok<{ name: string }>();

user.name; // is a string

与类组件一起使用

使用 withAuthok 高阶组件来添加 authok 属性到类组件:

import React, { Component } from 'react';
import { withAuthok } from '@authok/authok-react';

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

export default withAuthok(Profile);

保护路由

使用 withAuthenticationRequired 高阶组件来保护路由. 未认证状态访问此路由会重定向用户到登录页面并在登录后返回此页面:

import React from 'react';
import { withAuthenticationRequired } from '@authok/authok-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>重定向到登录页...</div>,
});

注意 如果你使用自定义路由, 你需要提供给 AuthokProvider 一个自定义的 onRedirectCallback 方法来执行重定向回调的动作. 参考 react-router, Gatsby and Next.js.

调用 API

通过 Access Token 来调用收保护的 API:

import React, { useEffect, useState } from 'react';
import { useAuthok } from '@authok/authok-react';

const Posts = () => {
  const { getAccessTokenSilently } = useAuthok();
  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 hook,并使用 Access Token 访问受保护的API.

贡献

我们在这里感谢大家对本仓库的反馈和贡献!在开始之前,请参阅以下内容:

支持 + 反馈

如需支持或提供反馈,请 在我们的issue tracker 中提交 issue.

故障排除

有关如何解决常见问题的信息,请查看 故障排除 指南

常见问题

有关使用SDK时可能遇到的常见问题,请查看 FAQ.

漏洞报告

请不要在 GitHub 公开的问题跟踪器上报告安全漏洞. 披露计划 中详细说明了披露安全问题的流程.

什么是 Authok?

Authok 帮助您轻松地:

  • 使用多个身份提供程序实现身份验证, 包括社会化 (e.g., 微信, 企业微信, 支付宝, 抖音, 微博, Google, Facebook, Microsoft, LinkedIn, GitHub, Twitter 等), 或企业 (e.g., Windows Azure AD, Google Apps, Active Directory, ADFS, SAML 等.)
  • 用 用户名/密码 数据库模式, 免密模式, 或者 多因素认证 模式登录用户
  • 将多个用户账户进行关联
  • 生成签名 JSON Web Token 以授权API调用并安全地传递用户身份
  • 用户登录方式、时间, 地点的统计和分析
  • 使用可定制的JavaScript规则从其他数据源丰富用户档案

为什么使用 Authok?

许可(License)

本项目基于 MIT 许可. 参考 LICENSE 文件以获取更多信息.