Open2

Auth0-reactを読んでいく

taroodrtaroodr

https://github.com/auth0/auth0-react/blob/master/src/auth0-provider.tsx を読んでいく

処理の流れ

Auth0Clientインスタンス生成

  const [client] = useState(
    () => new Auth0Client(toAuth0ClientOptions(clientOpts))
  );

useReducerを使って認証状態を管理するstateを初期化

  const [state, dispatch] = useReducer(reducer, initialAuthState);

stateの定義はこちら https://github.com/auth0/auth0-react/blob/master/src/auth-state.tsx

export interface AuthState {
  error?: Error;
  isAuthenticated: boolean;
  isLoading: boolean;
  user?: User;
}

/**
 * The initial auth state.
 */
export const initialAuthState: AuthState = {
  isAuthenticated: false,
  // In SSR mode the library will never check the session, so loading should be 
initialised as false
  isLoading: typeof window !== 'undefined',
};

認証状態のチェック

  useEffect(() => {
    (async (): Promise<void> => {
      try {
        if (hasAuthParams() && !skipRedirectCallback) {
          const { appState } = await client.handleRedirectCallback();
          onRedirectCallback(appState);
        } else {
          await client.checkSession();
        }
        const user = await client.getUser();
        dispatch({ type: 'INITIALISED', user });
      } catch (error) {
        dispatch({ type: 'ERROR', error: loginError(error) });
      }
    })();
  }, [client, onRedirectCallback, skipRedirectCallback]);

hasAuthParams() && !skipRedirectCallback 分岐は、認可サーバーから認可コードが返ってきたときに使われる分岐と思われるがこのあたりは知識不足なので調査が必要。

hasAuthParams() && !skipRedirectCallback がfalseの場合は else句に入り、 client.checkSession(); メソッドが呼ばれる.
コメントは以下の通り。
つまり、cookieに 'auth0.is.authenticated' が存在しない場合は認証状態にはならない.

Check if the user is logged in using getTokenSilently. The difference
with getTokenSilently is that this doesn't return a token, but it will
pre-fill the token cache.
This method also heeds the auth0.is.authenticated cookie, as an optimization
to prevent calling Auth0 unnecessarily. If the cookie is not present because
there was no previous login (or it has expired) then tokens will not be refreshed.
It should be used for silently logging in the user when you instantiate the
Auth0Client constructor. You should not need this if you are using the
createAuth0Client factory.

ユーザが ログインしているかどうかをgetTokenSilentlyを使って調べる。getTokenSilentlyとの違いは、トークンを返さないことですが、トークンキャッシュをpre-fil(事前入力)します。 このメソッドは auth0.is.authenticated クッキーも考慮しており、不必要にAuth0を呼ばないようにするための最適化です。クッキーが存在しないのは、前回のログインがなかったため (または期限が切れていたため)、トークンはリフレッシュされません。 これは、Auth0Client コンストラクタをインスタンス化する際に、ユーザを黙ってログインさせるために使われるべきです。コンストラクタを使用している場合は必要ありません。createAuth0Client ファクトリを使用しています。

その他は、 provider経由で渡す各種メソッドが定義されている。
基本的に各種auth0-clientのメソッドをラップしたもので、メソッドを呼び出した結果によってstateを変更している。