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?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?