npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@authok/authok-react

v1.9.3

Published

Authok SDK for React Single Page Applications (SPA)

Downloads

12

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 文件以获取更多信息.