useAuth

为您的 React 应用添加身份验证的最简单方法。为您处理一切。用户、登录表单、重定向、组件间共享状态。所有的一切。「The simplest way to add authentication to your React app. Handles everything for you. Users, login forms, redirects, sharing state between components. Everything」

Github星跟踪图

The simplest way to add authentication to your React app. Handles everything for you. Users, login forms, redirects, sharing state between components. Everything

How to use useAuth

useAuth is designed to be quick to setup. You'll need an Auth0 account with an app domain and client id.

1. Install the hook

$ yarn add react-use-auth

Downloads from npm, adds to your package.json, etc. You can use npm as well.

2. Set up AuthProvider

useAuth uses an AuthProvider component to configure the Auth0 client and share state between components. It's using React context with a reducer behind the scenes, but that's an implementation detail.

I recommend adding this around your root component. In Gatsby that's done in gatsby-browser.js and gatsby-ssr.js. Yes useAuth is built so it doesn't break server-side rendering. ✌️

But of course server-side "you" will always be logged out.

// gatsby-browser.js

import React from "react";
import { navigate } from "gatsby";

import { AuthProvider } from "react-use-auth";

export const wrapRootElement = ({ element }) => (
    <AuthProvider
        navigate={navigate}
        auth0_domain="useauth.auth0.com"
        auth0_client_id="GjWNFNOHq1ino7lQNJBwEywa1aYtbIzh"
    >
        {element}
    </AuthProvider>
);

<AuthProvider> creates a context, sets up a state reducer, initializes an Auth0 client and so on. Everything you need for authentication to work in your whole app :)

The API takes a couple config options:

  1. navigate – your navigation function, used for redirects. I've tested with Gatsby, but anything should work
  2. auth0_domain – from your Auth0 app
  3. auth0_client_id – from your Auth0 app
  4. auth0_params – an object that lets you overwrite any of the default Auth0 client parameters

PS: even though Auth doesn't do anything server-side, useAuth will throw errors during build, if its context doesn't exist

Default Auth0 params

By default useAuth's Auth0 client uses these params:

const params = {
    domain: auth0_domain,
    clientID: auth0_client_id,
    redirectUri: `${callback_domain}/auth0_callback`,
    audience: `https://${auth0_audience_domain

主要指标

概览
名称与所有者Swizec/useAuth
主编程语言TypeScript
编程语言TypeScript (语言数: 2)
平台Linux, Mac, Windows
许可证MIT License
所有者活动
创建于2019-08-04 21:11:28
推送于2023-01-11 19:53:29
最后一次提交2021-01-27 06:29:03
发布数33
最新版本名称v2.0.4 (发布于 2020-12-31 11:06:10)
第一版名称v0.2.0 (发布于 2019-08-09 22:57:57)
用户参与
星数2.6k
关注者数25
派生数109
提交数487
已启用问题?
问题数48
打开的问题数22
拉请求数95
打开的拉请求数135
关闭的拉请求数41
项目设置
已启用Wiki?
已存档?
是复刻?
已锁定?
是镜像?
是私有?